49 #define DEBUG_TYPE "globalopt"
51 STATISTIC(NumMarked ,
"Number of globals marked constant");
52 STATISTIC(NumUnnamed ,
"Number of globals marked unnamed_addr");
53 STATISTIC(NumSRA ,
"Number of aggregate globals broken into scalars");
54 STATISTIC(NumHeapSRA ,
"Number of heap objects SRA'd");
55 STATISTIC(NumSubstitute,
"Number of globals with initializers stored into them");
56 STATISTIC(NumDeleted ,
"Number of globals deleted");
57 STATISTIC(NumFnDeleted ,
"Number of functions deleted");
58 STATISTIC(NumGlobUses ,
"Number of global uses devirtualized");
59 STATISTIC(NumLocalized ,
"Number of globals localized");
60 STATISTIC(NumShrunkToBool ,
"Number of global vars shrunk to booleans");
61 STATISTIC(NumFastCallFns ,
"Number of functions converted to fastcc");
62 STATISTIC(NumCtorsEvaluated,
"Number of static ctors evaluated");
63 STATISTIC(NumNestRemoved ,
"Number of nest attributes removed");
64 STATISTIC(NumAliasesResolved,
"Number of global aliases resolved");
65 STATISTIC(NumAliasesRemoved,
"Number of global aliases eliminated");
66 STATISTIC(NumCXXDtorsRemoved,
"Number of global C++ destructors removed");
78 bool runOnModule(
Module &M)
override;
81 bool OptimizeFunctions(
Module &M);
82 bool OptimizeGlobalVars(
Module &M);
83 bool OptimizeGlobalAliases(
Module &M);
87 bool OptimizeEmptyGlobalCXXDtors(
Function *CXAAtExitFn);
96 "Global Variable Optimizer",
false,
false)
138 if (isa<PointerType>(InnerTy))
return true;
139 if (isa<CompositeType>(InnerTy))
145 if (--Limit == 0)
return true;
146 }
while (!Types.
empty());
155 if (isa<Constant>(V))
159 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
169 if (!
GEP->hasAllConstantIndices())
194 bool Changed =
false;
205 Value *V =
SI->getValueOperand();
206 if (isa<Constant>(V)) {
208 SI->eraseFromParent();
213 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
214 if (isa<Constant>(MSI->getValue())) {
216 MSI->eraseFromParent();
217 }
else if (
Instruction *
I = dyn_cast<Instruction>(MSI->getValue())) {
225 MTI->eraseFromParent();
226 }
else if (
Instruction *
I = dyn_cast<Instruction>(MemSrc)) {
230 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
231 if (CE->use_empty()) {
232 CE->destroyConstant();
235 }
else if (
Constant *C = dyn_cast<Constant>(U)) {
237 C->destroyConstant();
246 for (
int i = 0, e = Dead.
size(); i != e; ++i) {
248 Dead[i].second->eraseFromParent();
273 bool Changed =
false;
279 while (!WorkList.empty()) {
280 Value *UV = WorkList.pop_back_val();
284 User *U = cast<User>(UV);
286 if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
290 LI->eraseFromParent();
293 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(U)) {
295 SI->eraseFromParent();
297 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
298 if (CE->getOpcode() == Instruction::GetElementPtr) {
303 }
else if ((CE->getOpcode() == Instruction::BitCast &&
304 CE->getType()->isPointerTy()) ||
305 CE->getOpcode() == Instruction::AddrSpaceCast) {
310 if (CE->use_empty()) {
311 CE->destroyConstant();
319 if (!isa<ConstantExpr>(
GEP->getOperand(0))) {
322 if (Init && CE && CE->
getOpcode() == Instruction::GetElementPtr)
328 if (Init && isa<ConstantAggregateZero>(Init) &&
GEP->isInBounds())
333 if (
GEP->use_empty()) {
334 GEP->eraseFromParent();
338 if (
MI->getRawDest() == V) {
339 MI->eraseFromParent();
343 }
else if (
Constant *C = dyn_cast<Constant>(U)) {
347 C->destroyConstant();
360 if (
Constant *C = dyn_cast<Constant>(V))
364 if (!I)
return false;
367 if (isa<LoadInst>(I))
return true;
371 return SI->getOperand(0) != V;
375 if (!GEPI)
return false;
378 !cast<Constant>(GEPI->
getOperand(1))->isNullValue())
393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
403 !cast<Constant>(U->
getOperand(1))->isNullValue() ||
411 if (
ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412 uint64_t NumElements = AT->getNumElements();
431 uint64_t NumElements;
432 if (
ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433 NumElements = SubArrayTy->getNumElements();
434 else if (
VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
435 NumElements = SubVectorTy->getNumElements();
437 assert((*GEPI)->isStructTy() &&
438 "Indexed GEP type is not array, vector, or struct!");
479 Type *Ty = Init->getType();
481 std::vector<GlobalVariable*> NewGlobals;
486 if (StartAlignment == 0)
489 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
490 NewGlobals.reserve(STy->getNumElements());
492 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
494 assert(In &&
"Couldn't get element of initializer?");
501 NewGlobals.push_back(NGV);
512 unsigned NumElements = 0;
513 if (
ArrayType *ATy = dyn_cast<ArrayType>(STy))
514 NumElements = ATy->getNumElements();
516 NumElements = cast<VectorType>(STy)->getNumElements();
520 NewGlobals.reserve(NumElements);
524 for (
unsigned i = 0, e = NumElements; i != e; ++i) {
526 assert(In &&
"Couldn't get element of initializer?");
534 NewGlobals.push_back(NGV);
540 if (NewAlign > EltAlign)
545 if (NewGlobals.empty())
548 DEBUG(
dbgs() <<
"PERFORMING GLOBAL SRA ON: " << *GV);
556 assert(((isa<ConstantExpr>(GEP) &&
557 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
558 isa<GetElementPtrInst>(GEP)) &&
"NonGEP CE's are not SRAable!");
563 unsigned Val = cast<ConstantInt>(GEP->
getOperand(2))->getZExtValue();
564 if (Val >= NewGlobals.size()) Val = 0;
566 Value *NewPtr = NewGlobals[Val];
567 Type *NewTy = NewGlobals[Val]->getValueType();
574 for (
unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
585 NewTy, NewPtr, Idxs, GEPI->
getName() +
"." +
Twine(Val), GEPI);
591 GEPI->eraseFromParent();
593 cast<ConstantExpr>(
GEP)->destroyConstant();
603 unsigned FirstGlobal = 0;
604 for (
unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
605 if (NewGlobals[i]->use_empty()) {
606 Globals.
erase(NewGlobals[i]);
607 if (FirstGlobal == i) ++FirstGlobal;
610 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] :
nullptr;
619 if (isa<LoadInst>(U)) {
621 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(U)) {
622 if (
SI->getOperand(0) == V) {
626 }
else if (
const CallInst *CI = dyn_cast<CallInst>(U)) {
627 if (CI->getCalledValue() != V) {
631 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
632 if (II->getCalledValue() != V) {
636 }
else if (
const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
640 }
else if (
const PHINode *PN = dyn_cast<PHINode>(U)) {
645 }
else if (isa<ICmpInst>(U) &&
646 isa<ConstantPointerNull>(U->getOperand(1))) {
661 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
665 }
else if (isa<StoreInst>(U)) {
676 bool Changed =
false;
679 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
680 LI->setOperand(0, NewV);
682 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
683 if (
SI->getOperand(1) == V) {
684 SI->setOperand(1, NewV);
687 }
else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
694 bool PassedAsArg =
false;
695 for (
unsigned i = 0, e = CS.
arg_size(); i != e; ++i)
706 }
else if (
CastInst *CI = dyn_cast<CastInst>(I)) {
710 if (CI->use_empty()) {
712 CI->eraseFromParent();
717 Idxs.
reserve(GEPI->getNumOperands()-1);
720 if (
Constant *C = dyn_cast<Constant>(*i))
724 if (Idxs.
size() == GEPI->getNumOperands()-1)
727 if (GEPI->use_empty()) {
729 GEPI->eraseFromParent();
745 bool Changed =
false;
749 bool AllNonStoreUsesGone =
true;
753 User *GlobalUser = *GUI++;
754 if (
LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
757 if (LI->use_empty()) {
758 LI->eraseFromParent();
761 AllNonStoreUsesGone =
false;
763 }
else if (isa<StoreInst>(GlobalUser)) {
766 "Must be storing *to* the global");
768 AllNonStoreUsesGone =
false;
772 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
773 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
774 isa<BitCastInst>(GlobalUser) ||
775 isa<GetElementPtrInst>(GlobalUser)) &&
776 "Only expect load and stores!");
781 DEBUG(
dbgs() <<
"OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
787 if (AllNonStoreUsesGone) {
795 DEBUG(
dbgs() <<
" *** GLOBAL NOW DEAD!\n");
811 I->replaceAllUsesWith(NewC);
815 while (UI != E && *UI ==
I)
817 I->eraseFromParent();
830 DEBUG(
errs() <<
"PROMOTING GLOBAL: " << *GV <<
" CALL = " << *CI <<
'\n');
834 GlobalType = AllocTy;
855 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
856 if (BCI->getType() == NewGV->getType()) {
858 BCI->eraseFromParent();
860 BCI->setOperand(0, NewGV);
878 GlobalValue::InternalLinkage,
881 bool InitBoolUsed =
false;
888 SI->getOrdering(),
SI->getSynchScope(),
SI);
889 SI->eraseFromParent();
935 cast<StoreInst>(InitBool->
user_back())->eraseFromParent();
948 if (RepValue != NewGV)
964 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
968 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
969 if (
SI->getOperand(0) == V &&
SI->getOperand(1) != GV)
975 if (isa<GetElementPtrInst>(Inst) && Inst->
getNumOperands() >= 3) {
981 if (
const PHINode *PN = dyn_cast<PHINode>(Inst)) {
984 if (PHIs.
insert(PN).second)
990 if (
const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1013 if (
SI->getOperand(1) == GV) {
1014 SI->eraseFromParent();
1017 }
else if (
PHINode *PN = dyn_cast<PHINode>(U)) {
1020 InsertPt = PN->getIncomingBlock(*Alloc->
use_begin())->getTerminator();
1021 }
else if (isa<BitCastInst>(U)) {
1029 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1030 if (
StoreInst *
SI = dyn_cast<StoreInst>(GEPI->user_back()))
1031 if (
SI->getOperand(1) == GV) {
1035 GEPI->eraseFromParent();
1058 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
1059 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1067 if (GEPI->getNumOperands() < 3)
1074 if (
const PHINode *PN = dyn_cast<PHINode>(UI)) {
1075 if (!LoadUsingPHIsPerLoad.
insert(PN).second)
1079 if (!LoadUsingPHIs.
insert(PN).second)
1085 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1106 if (
const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1108 LoadUsingPHIsPerLoad))
1110 LoadUsingPHIsPerLoad.
clear();
1118 for (
const PHINode *PN : LoadUsingPHIs) {
1119 for (
unsigned op = 0, e = PN->getNumIncomingValues();
op != e; ++
op) {
1120 Value *InVal = PN->getIncomingValue(
op);
1123 if (InVal == StoredVal)
continue;
1125 if (
const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1127 if (LoadUsingPHIs.count(InPN))
1133 if (
const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1134 if (LI->getOperand(0) == GV)
1148 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1149 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1150 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1152 if (FieldNo >= FieldVals.size())
1153 FieldVals.resize(FieldNo+1);
1157 if (
Value *FieldVal = FieldVals[FieldNo])
1162 if (
LoadInst *LI = dyn_cast<LoadInst>(V)) {
1166 InsertedScalarizedValues,
1170 PHINode *PN = cast<PHINode>(V);
1175 StructType *
ST = cast<StructType>(PTy->getElementType());
1177 unsigned AS = PTy->getAddressSpace();
1183 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1186 return FieldVals[FieldNo] = Result;
1192 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1193 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1195 if (
ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1196 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1200 InsertedScalarizedValues, PHIsToRewrite);
1206 SCI->eraseFromParent();
1212 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1213 &&
"Unexpected GEPI!");
1216 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1218 InsertedScalarizedValues, PHIsToRewrite);
1223 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1228 GEPI->eraseFromParent();
1238 PHINode *PN = cast<PHINode>(LoadUser);
1239 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1240 std::vector<Value*>())).second)
1256 DenseMap<
Value*, std::vector<Value*> > &InsertedScalarizedValues,
1257 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1265 InsertedScalarizedValues.
erase(Load);
1274 DEBUG(
dbgs() <<
"SROA HEAP ALLOC: " << *GV <<
" MALLOC = " << *CI <<
'\n');
1286 std::vector<Value*> FieldGlobals;
1287 std::vector<Value*> FieldMallocs;
1290 for (
unsigned FieldNo = 0, e = STy->
getNumElements(); FieldNo != e;++FieldNo){
1300 FieldGlobals.push_back(NGV);
1310 FieldMallocs.push_back(NMI);
1329 ConstantZero,
"isneg");
1330 for (
unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1334 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond,
"tmp", CI);
1354 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1355 Value *GVVal =
new LoadInst(FieldGlobals[i],
"tmp", NullPtrBlock);
1371 NullPtrBlock = NextBlock;
1383 InsertedScalarizedValues[GV] = FieldGlobals;
1385 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1393 if (
LoadInst *LI = dyn_cast<LoadInst>(User)) {
1400 assert(isa<ConstantPointerNull>(SI->
getOperand(0)) &&
1401 "Unexpected heap-sra user!");
1404 for (
unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1405 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1407 new StoreInst(Null, FieldGlobals[i], SI);
1414 while (!PHIsToRewrite.empty()) {
1415 PHINode *PN = PHIsToRewrite.back().first;
1416 unsigned FieldNo = PHIsToRewrite.back().second;
1417 PHIsToRewrite.pop_back();
1418 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1432 I = InsertedScalarizedValues.
begin(), E = InsertedScalarizedValues.
end();
1434 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1435 PN->dropAllReferences();
1436 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1437 LI->dropAllReferences();
1442 I = InsertedScalarizedValues.
begin(), E = InsertedScalarizedValues.
end();
1444 if (
PHINode *PN = dyn_cast<PHINode>(
I->first))
1445 PN->eraseFromParent();
1446 else if (
LoadInst *LI = dyn_cast<LoadInst>(
I->first))
1447 LI->eraseFromParent();
1454 return cast<GlobalVariable>(FieldGlobals[0]);
1497 if (
ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1516 if (
ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1517 AllocTy = AT->getElementType();
1536 AllocSize, NumElements,
1541 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1542 CI = cast<CallInst>(BCI->getOperand(0));
1544 CI = cast<CallInst>(Malloc);
1571 if (
Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1610 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1613 DEBUG(
dbgs() <<
" *** SHRINKING TO BOOL: " << *GV);
1627 "No reason to shrink to bool!");
1631 bool IsOneZero =
false;
1632 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1633 IsOneZero = InitVal->
isNullValue() && CI->isOne();
1639 bool StoringOther =
SI->getOperand(0) == OtherVal;
1642 if (StoringOther ||
SI->getOperand(0) == InitVal) {
1649 Instruction *StoredVal = cast<Instruction>(
SI->getOperand(0));
1654 if (
LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1655 assert(LI->getOperand(0) == GV &&
"Not a copy!");
1658 LI->getOrdering(), LI->getSynchScope(), LI);
1660 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1661 "This is not a form that we understand!");
1663 assert(isa<LoadInst>(StoreVal) &&
"Not a load of NewGV!");
1666 new StoreInst(StoreVal, NewGV,
false, 0,
1667 SI->getOrdering(),
SI->getSynchScope(),
SI);
1700 DEBUG(
dbgs() <<
"GLOBAL DEAD: " << *GV);
1722 return ProcessInternalGlobal(GV, GVI, GS);
1745 DEBUG(
dbgs() <<
"LOCALIZING GLOBAL: " << *GV);
1764 DEBUG(
dbgs() <<
"GLOBAL NEVER LOADED: " << *GV);
1785 DEBUG(
dbgs() <<
"MARKING CONSTANT: " << *GV <<
"\n");
1793 DEBUG(
dbgs() <<
" *** Marking constant allowed us to simplify "
1794 <<
"all users and delete global!\n");
1821 DEBUG(
dbgs() <<
" *** Substituting initializer allowed us to "
1822 <<
"simplify all users and delete global!\n");
1857 if (isa<BlockAddress>(U))
1865 for (
unsigned i = 0, e = Attrs.
getNumSlots(); i != e; ++i) {
1880 if (isa<BlockAddress>(U))
1897 bool GlobalOpt::OptimizeFunctions(
Module &M) {
1898 bool Changed =
false;
1907 bool inComdat = C && NotDiscardableComdats.count(C);
1938 bool GlobalOpt::OptimizeGlobalVars(
Module &M) {
1939 bool Changed =
false;
1952 if (New && New != CE)
1960 Changed |= ProcessGlobal(GV, GVI);
1985 if (
auto *GV = dyn_cast<GlobalValue>(C))
1993 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
1994 isa<ConstantVector>(C)) {
2006 case Instruction::BitCast:
2010 case Instruction::IntToPtr:
2011 case Instruction::PtrToInt:
2020 case Instruction::GetElementPtr:
2026 case Instruction::Add:
2040 if (!SimpleConstants.
insert(C).second)
2055 if (!cast<PointerType>(C->
getType())->getElementType()->isSingleValueType())
2064 if (CE->getOpcode() == Instruction::GetElementPtr &&
2065 isa<GlobalVariable>(CE->getOperand(0)) &&
2066 cast<GEPOperator>(CE)->isInBounds()) {
2075 if (!CI || !CI->
isZero())
return false;
2079 if (!CE->isGEPWithNoNotionalOverIndexing())
2087 }
else if (CE->getOpcode() == Instruction::BitCast &&
2088 isa<GlobalVariable>(CE->getOperand(0))) {
2091 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2112 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2118 assert(Idx < STy->getNumElements() &&
"Struct index out of range!");
2129 if (
ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2130 NumElts = ATy->getNumElements();
2135 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2170 : DL(DL), TLI(TLI) {
2171 ValueStack.emplace_back();
2175 for (
auto &Tmp : AllocaTmps)
2179 if (!Tmp->use_empty())
2195 if (
Constant *CV = dyn_cast<Constant>(V))
return CV;
2196 Constant *R = ValueStack.back().lookup(V);
2197 assert(R &&
"Reference to an uncomputed value!");
2202 ValueStack.back()[V] =
C;
2206 return MutatedMemory;
2219 std::deque<DenseMap<Value*, Constant*>> ValueStack;
2257 if (I != MutatedMemory.
end())
return I->second;
2268 if (
CE->getOpcode() == Instruction::GetElementPtr &&
2269 isa<GlobalVariable>(
CE->getOperand(0))) {
2287 DEBUG(
dbgs() <<
"Evaluating Instruction: " << *CurInst <<
"\n");
2289 if (
StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2290 if (!
SI->isSimple()) {
2291 DEBUG(
dbgs() <<
"Store is not simple! Can not evaluate.\n");
2296 DEBUG(
dbgs() <<
"Folding constant ptr expression: " << *Ptr);
2298 DEBUG(
dbgs() <<
"; To: " << *Ptr <<
"\n");
2302 DEBUG(
dbgs() <<
"Pointer is too complex for us to evaluate store.");
2311 DEBUG(
dbgs() <<
"Store value is too complex to evaluate store. " << *Val
2317 if (
CE->getOpcode() == Instruction::BitCast) {
2318 DEBUG(
dbgs() <<
"Attempting to resolve bitcast on constant ptr.\n");
2322 Ptr =
CE->getOperand(0);
2324 Type *NewTy = cast<PointerType>(Ptr->
getType())->getElementType();
2333 if (
StructType *STy = dyn_cast<StructType>(NewTy)) {
2334 NewTy = STy->getTypeAtIndex(0U);
2338 Constant *
const IdxList[] = {IdxZero, IdxZero};
2347 DEBUG(
dbgs() <<
"Failed to bitcast constant ptr, can not "
2357 DEBUG(
dbgs() <<
"Evaluated bitcast: " << *Val <<
"\n");
2361 MutatedMemory[Ptr] = Val;
2362 }
else if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2364 getVal(BO->getOperand(0)),
2365 getVal(BO->getOperand(1)));
2366 DEBUG(
dbgs() <<
"Found a BinaryOperator! Simplifying: " << *InstResult
2368 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2370 getVal(CI->getOperand(0)),
2371 getVal(CI->getOperand(1)));
2372 DEBUG(
dbgs() <<
"Found a CmpInst! Simplifying: " << *InstResult
2374 }
else if (
CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2376 getVal(CI->getOperand(0)),
2378 DEBUG(
dbgs() <<
"Found a Cast! Simplifying: " << *InstResult
2380 }
else if (
SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2382 getVal(
SI->getOperand(1)),
2383 getVal(
SI->getOperand(2)));
2384 DEBUG(
dbgs() <<
"Found a Select! Simplifying: " << *InstResult
2386 }
else if (
auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
2388 getVal(EVI->getAggregateOperand()), EVI->getIndices());
2389 DEBUG(
dbgs() <<
"Found an ExtractValueInst! Simplifying: " << *InstResult
2391 }
else if (
auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
2393 getVal(IVI->getAggregateOperand()),
2394 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
2395 DEBUG(
dbgs() <<
"Found an InsertValueInst! Simplifying: " << *InstResult
2405 cast<GEPOperator>(
GEP)->isInBounds());
2406 DEBUG(
dbgs() <<
"Found a GEP! Simplifying: " << *InstResult
2408 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2410 if (!LI->isSimple()) {
2411 DEBUG(
dbgs() <<
"Found a Load! Not a simple load, can not evaluate.\n");
2415 Constant *Ptr = getVal(LI->getOperand(0));
2418 DEBUG(
dbgs() <<
"Found a constant pointer expression, constant "
2419 "folding: " << *Ptr <<
"\n");
2421 InstResult = ComputeLoadResult(Ptr);
2423 DEBUG(
dbgs() <<
"Failed to compute load result. Can not evaluate load."
2428 DEBUG(
dbgs() <<
"Evaluated load: " << *InstResult <<
"\n");
2429 }
else if (
AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2430 if (AI->isArrayAllocation()) {
2431 DEBUG(
dbgs() <<
"Found an array alloca. Can not evaluate.\n");
2434 Type *Ty = AI->getType()->getElementType();
2435 AllocaTmps.push_back(
2438 InstResult = AllocaTmps.back().get();
2439 DEBUG(
dbgs() <<
"Found an alloca. Result: " << *InstResult <<
"\n");
2440 }
else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2444 if (isa<DbgInfoIntrinsic>(
CS.getInstruction())) {
2445 DEBUG(
dbgs() <<
"Ignoring debug info.\n");
2451 if (isa<InlineAsm>(
CS.getCalledValue())) {
2452 DEBUG(
dbgs() <<
"Found inline asm, can not evaluate.\n");
2456 if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(
CS.getInstruction())) {
2457 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2458 if (MSI->isVolatile()) {
2459 DEBUG(
dbgs() <<
"Can not optimize a volatile memset " <<
2463 Constant *Ptr = getVal(MSI->getDest());
2464 Constant *Val = getVal(MSI->getValue());
2465 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2466 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2468 DEBUG(
dbgs() <<
"Ignoring no-op memset.\n");
2474 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2475 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2476 DEBUG(
dbgs() <<
"Ignoring lifetime intrinsic.\n");
2481 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2484 if (!II->use_empty()) {
2485 DEBUG(
dbgs() <<
"Found unused invariant_start. Can't evaluate.\n");
2488 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2489 Value *PtrArg = getVal(II->getArgOperand(1));
2492 Type *ElemTy = cast<PointerType>(GV->
getType())->getElementType();
2496 Invariants.insert(GV);
2497 DEBUG(
dbgs() <<
"Found a global var that is an invariant: " << *GV
2500 DEBUG(
dbgs() <<
"Found a global var, but can not treat it as an "
2509 DEBUG(
dbgs() <<
"Unknown intrinsic. Can not evaluate.\n");
2516 DEBUG(
dbgs() <<
"Can not resolve function pointer.\n");
2528 DEBUG(
dbgs() <<
"Constant folded function call. Result: " <<
2529 *InstResult <<
"\n");
2531 DEBUG(
dbgs() <<
"Can not constant fold function call.\n");
2536 DEBUG(
dbgs() <<
"Can not constant fold vararg function call.\n");
2542 ValueStack.emplace_back();
2543 if (!EvaluateFunction(Callee, RetVal, Formals)) {
2544 DEBUG(
dbgs() <<
"Failed to evaluate function.\n");
2547 ValueStack.pop_back();
2548 InstResult = RetVal;
2551 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: " <<
2552 InstResult <<
"\n\n");
2554 DEBUG(
dbgs() <<
"Successfully evaluated function. Result: 0\n\n");
2557 }
else if (isa<TerminatorInst>(CurInst)) {
2558 DEBUG(
dbgs() <<
"Found a terminator instruction.\n");
2560 if (
BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2561 if (BI->isUnconditional()) {
2562 NextBB = BI->getSuccessor(0);
2566 if (!Cond)
return false;
2570 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2573 if (!Val)
return false;
2574 NextBB =
SI->findCaseValue(Val).getCaseSuccessor();
2575 }
else if (
IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2576 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2578 NextBB = BA->getBasicBlock();
2581 }
else if (isa<ReturnInst>(CurInst)) {
2585 DEBUG(
dbgs() <<
"Can not handle terminator.");
2590 DEBUG(
dbgs() <<
"Successfully evaluated block.\n");
2594 DEBUG(
dbgs() <<
"Failed to evaluate block due to unhandled instruction."
2599 if (!CurInst->use_empty()) {
2600 if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2603 setVal(CurInst, InstResult);
2607 if (
InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2608 NextBB = II->getNormalDest();
2609 DEBUG(
dbgs() <<
"Found an invoke instruction. Finished Block.\n\n");
2625 if (std::find(CallStack.begin(), CallStack.end(),
F) != CallStack.end())
2628 CallStack.push_back(F);
2634 setVal(AI, ActualArgs[ArgNo]);
2648 DEBUG(
dbgs() <<
"Trying to evaluate BB: " << *CurBB <<
"\n");
2650 if (!EvaluateBlock(CurInst, NextBB))
2659 CallStack.pop_back();
2666 if (!ExecutedBlocks.
insert(NextBB).second)
2673 for (CurInst = NextBB->
begin();
2689 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2693 ++NumCtorsEvaluated;
2696 DEBUG(
dbgs() <<
"FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2697 << F->
getName() <<
"' to " << Eval.getMutatedMemory().size()
2700 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2711 return (*A)->getName().compare((*B)->getName());
2728 UsedArray.push_back(Cast);
2759 iterator usedBegin() {
return Used.
begin(); }
2760 iterator usedEnd() {
return Used.end(); }
2761 used_iterator_range used() {
2762 return used_iterator_range(usedBegin(), usedEnd());
2764 iterator compilerUsedBegin() {
return CompilerUsed.begin(); }
2765 iterator compilerUsedEnd() {
return CompilerUsed.end(); }
2766 used_iterator_range compilerUsed() {
2767 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2769 bool usedCount(
GlobalValue *GV)
const {
return Used.count(GV); }
2771 return CompilerUsed.count(GV);
2773 bool usedErase(
GlobalValue *GV) {
return Used.erase(GV); }
2774 bool compilerUsedErase(
GlobalValue *GV) {
return CompilerUsed.erase(GV); }
2775 bool usedInsert(
GlobalValue *GV) {
return Used.insert(GV).second; }
2777 return CompilerUsed.insert(GV).second;
2780 void syncVariablesAndSets() {
2793 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2794 "We should have removed the duplicated "
2795 "element from llvm.compiler.used");
2802 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2806 const LLVMUsed &U) {
2808 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2809 "We should have removed the duplicated "
2810 "element from llvm.compiler.used");
2811 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2820 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2824 bool &RenameTarget) {
2825 RenameTarget =
false;
2851 RenameTarget =
true;
2855 bool GlobalOpt::OptimizeGlobalAliases(
Module &M) {
2856 bool Changed =
false;
2860 Used.compilerUsedErase(GV);
2866 if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
2869 if (J->mayBeOverridden())
2872 Constant *Aliasee = J->getAliasee();
2887 ++NumAliasesResolved;
2897 if (Used.usedErase(J))
2898 Used.usedInsert(Target);
2900 if (Used.compilerUsedErase(J))
2901 Used.compilerUsedInsert(Target);
2907 ++NumAliasesRemoved;
2911 Used.syncVariablesAndSets();
2917 if (!TLI->
has(LibFunc::cxa_atexit))
2958 if (
const CallInst *CI = dyn_cast<CallInst>(I)) {
2960 if (isa<DbgInfoIntrinsic>(CI))
2963 const Function *CalledFn = CI->getCalledFunction();
2971 if (!NewCalledFunctions.
insert(CalledFn).second)
2976 }
else if (isa<ReturnInst>(*I))
2978 else if (I->mayHaveSideEffects())
2985 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(
Function *CXAAtExitFn) {
3000 bool Changed =
false;
3024 ++NumCXXDtorsRemoved;
3032 bool GlobalOpt::runOnModule(
Module &M) {
3033 bool Changed =
false;
3036 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3038 bool LocalChange =
true;
3039 while (LocalChange) {
3040 LocalChange =
false;
3042 NotDiscardableComdats.clear();
3046 NotDiscardableComdats.insert(C);
3050 NotDiscardableComdats.insert(C);
3052 if (
const Comdat *C = GA.getComdat())
3053 if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3054 NotDiscardableComdats.insert(C);
3057 LocalChange |= OptimizeFunctions(M);
3065 LocalChange |= OptimizeGlobalVars(M);
3068 LocalChange |= OptimizeGlobalAliases(M);
3074 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3076 Changed |= LocalChange;
void setVisibility(VisibilityTypes V)
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
ReturnInst - Return a value (possibly void), from a function.
static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateStaticConstructor - Evaluate static constructors in the function, if we can.
iplist< Instruction >::iterator eraseFromParent()
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. ...
static ConstantInt * getFalse(LLVMContext &Context)
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, const DataLayout &DL, TargetLibraryInfo *TLI)
CleanupConstantGlobalUsers - We just marked GV constant.
This class is the base class for the comparison instructions.
bool IsLoaded
True if the global is ever loaded.
static bool isLeakCheckerRoot(GlobalVariable *GV)
isLeakCheckerRoot - Is this global variable possibly used by a leak checker as a root? If so, we might not really want to eliminate the stores to it.
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)
addIncoming - 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. ...
const Function * AccessingFunction
These start out null/false.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
STATISTIC(NumFunctions,"Total number of functions")
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
isOpaque - 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.
ValTy * getArgument(unsigned ArgNo) const
A Module instance is used to store all the information related to an LLVM module. ...
unsigned getNumParams() const
getNumParams - Return the number of fixed parameters this function type requires. ...
INITIALIZE_PASS_BEGIN(GlobalOpt,"globalopt","Global Variable Optimizer", false, false) INITIALIZE_PASS_END(GlobalOpt
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, GlobalVariable *GV)
ReplaceUsesOfMallocWithGlobal - 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
Nested function static chain.
static bool isSafeSROAElementUse(Value *V)
isSafeSROAElementUse - Return true if the specified instruction is a safe user of a derived expressio...
CallInst - This class represents a function call, abstracting a target machine's calling convention...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
PointerType::get - This constructs a pointer to an object of the specified type in a numbered address...
gep_type_iterator gep_type_end(const User *GEP)
bool mayHaveSideEffects() const
mayHaveSideEffects - Return true if the instruction may have side effects.
static Constant * EvaluateStoreInto(Constant *Init, Constant *Val, ConstantExpr *Addr, unsigned OpNo)
EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global initializer.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static GlobalVariable * OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy, ConstantInt *NElements, const DataLayout &DL, TargetLibraryInfo *TLI)
OptimizeGlobalAddressOfMalloc - This function takes the specified global variable, and transforms the program as if it always contained the result of the specified malloc.
bool HasMultipleAccessingFunctions
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
MemSetInst - This class wraps the llvm.memset intrinsic.
void setAttributes(const AttributeSet &PAL)
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
LoadInst - an instruction for reading from memory.
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
CreateFree - Generate the IR for a call to the builtin free function.
static GlobalVariable * PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, Value *NElems, const DataLayout &DL, const TargetLibraryInfo *TLI)
PerformHeapAllocSRoA - CI is an allocation of an array of structures.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
void reserve(size_type N)
void setAlignment(unsigned Align)
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.
Constant * ConstantFoldConstantExpression(const ConstantExpr *CE, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstantExpression - Attempt to fold the constant expression using the specified DataLayo...
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
const Constant * getAliasee() const
unsigned getOpcode() const
getOpcode - Return the opcode at the root of this constant expression
static bool AllUsesOfValueWillTrapIfNull(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs)
AllUsesOfValueWillTrapIfNull - Return true if all users of the specified value will trap if the value...
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...
static int compareNames(Constant *const *A, Constant *const *B)
static Constant * getNullValue(Type *Ty)
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
isSingleValueType - Return true if the type is a valid type for a register in codegen.
element_iterator element_end() const
BlockAddress - The address of a basic block.
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)
AttributeSet removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Attr) const
Remove the specified attribute at the specified index from this attribute list.
SelectInst - This class represents the LLVM 'select' instruction.
static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV)
AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads from GV will trap if the lo...
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.
const APInt & getValue() const
Return the constant as an APInt value reference.
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.
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
StructType - Class to represent struct types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A Use represents the edge between a Value definition and its users.
void initializeGlobalOptPass(PassRegistry &)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
bool canLosslesslyBitCastTo(Type *Ty) const
canLosslesslyBitCastTo - Return true if this type could be converted with a lossless BitCast to type ...
static Constant * get(ArrayRef< Constant * > V)
static bool isSimpleEnoughValueToCommitHelper(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
isSimpleEnoughValueToCommit - Return true if the specified constant can be handled by the code genera...
StoredType
Keep track of what stores to the global look like.
bool isSized(SmallPtrSetImpl< const Type * > *Visited=nullptr) const
isSized - Return true if it makes sense to take the size of this type.
Windows NT (Windows on ARM)
element_iterator element_begin() const
bool HasNonInstructionUser
Set to true if this global has a user that is not an instruction (e.g.
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
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)
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal)
TryToShrinkGlobalToBoolean - At this point, we have learned that the only two values ever stored into...
static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U)
bool hasPrivateLinkage() const
SynchronizationScope getSynchScope() const
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()
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
user_iterator_impl< User > user_iterator
FunctionType - Class to represent function types.
ConstantExpr - a constant value that is initialized with an expression using other constant values...
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
ValTy * getCalledValue() const
getCalledValue - Return the pointer to function that is being called.
static void ChangeCalleesToFastCall(Function *F)
ChangeCalleesToFastCall - Walk all of the direct calls of the specified function, changing them to Fa...
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)
RewriteHeapSROALoadUser - Given a load instruction and a value derived from the load, rewrite the derived value to use the HeapSRoA'd load.
unsigned getAlignment() const
ArrayType - Class to represent array types.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
This class represents a no-op cast from one type to another.
TypeID getTypeID() const
getTypeID - Return the type id for the type.
bool isFloatingPointTy() const
isFloatingPointTy - Return true if this is one of the six floating point types
StoreInst - an instruction for storing to memory.
void setCallingConv(CallingConv::ID CC)
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
isArrayTy - True if this is an instance of ArrayType.
static bool isSimpleEnoughValueToCommit(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
aa Exhaustive Alias Analysis Precision Evaluator
void takeName(Value *V)
Transfer the name from V to this value.
Type * getElementType() const
PointerType - Class to represent pointers.
This global is stored to, but only its initializer and one other value is ever stored to it...
unsigned getNumIncomingValues() const
getNumIncomingValues - 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.
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)
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
void setCallingConv(CallingConv::ID CC)
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
Type * getParamType(unsigned i) const
Parameter type accessors.
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.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
Constant * stripPointerCasts()
alias_iterator alias_end()
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static bool mayBeOverridden(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time...
This is an important class for using LLVM in a threaded context.
BranchInst - Conditional or Unconditional Branch instruction.
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
bool isVectorTy() const
isVectorTy - 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...
IndirectBrInst - Indirect Branch Instruction.
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 bool isSimpleEnoughPointerToCommit(Constant *C)
isSimpleEnoughPointerToCommit - Return true if this constant is simple enough for us to understand...
static void RemoveNestAttribute(Function *F)
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI, Type *AllocTy, AtomicOrdering Ordering, Module::global_iterator &GVI, const DataLayout &DL, TargetLibraryInfo *TLI)
TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a pointer global variable wi...
This instruction compares its operands according to the predicate given to the constructor.
iterator insert(iterator where, NodeTy *New)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
User * getUser() const
Returns the User that contains this Use.
static bool cxxDtorIsEmpty(const Function &Fn, SmallPtrSet< const Function *, 8 > &CalledFunctions)
cxxDtorIsEmpty - Returns whether the given function is an empty C++ destructor and can therefore be e...
Value * getOperand(unsigned i) const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Class to represent integer types.
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
getAggregateElement - For aggregates (struct/array/vector) return the constant that corresponds to th...
static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV)
IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
void setConstant(bool Val)
static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, const LLVMUsed &U)
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
bool isPointerTy() const
isPointerTy - True if this is an instance of PointerType.
static UndefValue * get(Type *T)
get() - 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.
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)
ConstantPropUsersOf - Walk the use list of V, constant folding all of the instructions that are folda...
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
iterator erase(iterator where)
global_iterator global_end()
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...
SequentialType - This is the superclass of the array, pointer and vector type classes.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool hasExternalLinkage() const
bool hasDLLImportStorageClass() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
MemIntrinsic - This is the common base class for memset/memcpy/memmove.
Global Variable Optimizer
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)
CommitValueTo - We have decided that Addr (which satisfies the predicate isSimpleEnoughPointerToCommi...
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
15: 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...
unsigned getVectorNumElements() 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()
user_back - Specialize the methods defined in Value, as we know that an instruction can only be used ...
Provides information about what library functions are available for the current target.
void setUnnamedAddr(bool Val)
uint64_t getSizeInBytes() const
alias_iterator alias_begin()
unsigned arg_size() const
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.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
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 OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, AtomicOrdering Ordering, Module::global_iterator &GVI, const DataLayout &DL, TargetLibraryInfo *TLI)
bool isNullValue() const
isNullValue - Return true if this is the value that would be returned by getNullValue.
static ConstantInt * getTrue(LLVMContext &Context)
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isAllOnesValue() const
isAllOnesValue - Return true if this is the value that would be returned by getAllOnesValue.
AttributeSet getAttributes() const
Return the attribute list for this Function.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
A range adaptor for a pair of iterators.
VectorType - Class to represent vector types.
Target - Wrapper for Target specific information.
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
isIntegerTy - True if this is an instance of IntegerType.
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
iterator_range< user_iterator > users()
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent() override
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=nullptr, Function *MallocF=nullptr, const Twine &Name="")
CreateMalloc - Generate the IR for a call to malloc:
ThreadLocalMode getThreadLocalMode() const
Value * getOperand() const
uint64_t MinAlign(uint64_t A, uint64_t B)
MinAlign - A and B are either alignments or offsets.
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, Instruction *StoredVal)
AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from GV are simple enough to ...
PointerType * getType() const
Global values are always pointers.
MemTransferInst - 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)
GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it is safe for us to perform...
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, const GlobalVariable *GV, SmallPtrSetImpl< const PHINode * > &PHIs)
ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking to make sure that there a...
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...
bool hasAttrSomewhere(Attribute::AttrKind Attr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
void setCalledFunction(Value *V)
setCalledFunction - Set the callee to the specified value.
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...
FunctionType * getFunctionType() const
Fast - This calling convention attempts to make calls as fast as possible (e.g.
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...
GraphT::NodeType * Eval(DominatorTreeBase< typename GraphT::NodeType > &DT, typename GraphT::NodeType *VIn, unsigned LastLinked)
static GlobalVariable * SRAGlobal(GlobalVariable *GV, const DataLayout &DL)
SRAGlobal - Perform scalar replacement of aggregates on the specified global variable.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
X86_ThisCall - Similar to X86_StdCall.
const AttributeSet & getAttributes() const
getAttributes/setAttributes - get or set the parameter attributes of the call.
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.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
void setAttributes(AttributeSet attrs)
Set the attribute list for this Function.
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
bool hasLocalLinkage() const
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, const DataLayout &DL, TargetLibraryInfo *TLI)
OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null value stored into it...
SwitchInst - Multiway switch.
static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, DenseMap< Value *, std::vector< Value * > > &InsertedScalarizedValues, std::vector< std::pair< PHINode *, unsigned > > &PHIsToRewrite)
RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.
void setArgument(unsigned ArgNo, Value *newVal)
Type * getReturnType() const
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)
LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi of a load) are simple en...
void removeDeadConstantUsers() const
removeDeadConstantUsers - If there are any dead constant users dangling off of this constant...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
bool hasUnnamedAddr() const
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV)
GlobalVariable * collectUsedGlobalVariables(Module &M, SmallPtrSetImpl< GlobalValue * > &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
InvokeInst - Invoke instruction.
iterator_range< global_iterator > globals()
C - The default llvm calling convention, compatible with C.
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
static bool CleanupPointerRootUsers(GlobalVariable *GV, const TargetLibraryInfo *TLI)
CleanupPointerRootUsers - This GV is a pointer root.
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.
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.
void setSection(StringRef S)
const BasicBlock * getParent() const
void removeFromParent() override
removeFromParent - This method unlinks 'this' from the containing module, but does not delete it...
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
Constant * ConstantFoldCall(Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
AllocaInst - an instruction to allocate memory on the stack.
gep_type_iterator gep_type_begin(const User *GEP)