47#include "llvm/Config/llvm-config.h"
70#include "llvm/IR/IntrinsicsAArch64.h"
114#define DEBUG_TYPE "codegenprepare"
117STATISTIC(NumPHIsElim,
"Number of trivial PHIs eliminated");
118STATISTIC(NumGEPsElim,
"Number of GEPs converted to casts");
119STATISTIC(NumCmpUses,
"Number of uses of Cmp expressions replaced with uses of "
121STATISTIC(NumCastUses,
"Number of uses of Cast expressions replaced with uses "
123STATISTIC(NumMemoryInsts,
"Number of memory instructions whose address "
124 "computations were sunk");
126 "Number of phis created when address "
127 "computations were sunk to memory instructions");
129 "Number of select created when address "
130 "computations were sunk to memory instructions");
131STATISTIC(NumExtsMoved,
"Number of [s|z]ext instructions combined with loads");
132STATISTIC(NumExtUses,
"Number of uses of [s|z]ext instructions optimized");
134 "Number of and mask instructions added to form ext loads");
135STATISTIC(NumAndUses,
"Number of uses of and mask instructions optimized");
136STATISTIC(NumRetsDup,
"Number of return instructions duplicated");
137STATISTIC(NumDbgValueMoved,
"Number of debug value instructions moved");
138STATISTIC(NumSelectsExpanded,
"Number of selects turned into branches");
139STATISTIC(NumStoreExtractExposed,
"Number of store(extractelement) exposed");
167class TypePromotionTransaction;
169class CodeGenPrepare {
170 friend class CodeGenPrepareLegacyPass;
171 const CodeGenOptions &Opts;
172 const TargetMachine *TM =
nullptr;
173 const TargetSubtargetInfo *SubtargetInfo =
nullptr;
174 const TargetLowering *TLI =
nullptr;
175 const TargetRegisterInfo *TRI =
nullptr;
176 const TargetTransformInfo *TTI =
nullptr;
177 const BasicBlockSectionsProfileReader *BBSectionsProfileReader =
nullptr;
178 const TargetLibraryInfo *TLInfo =
nullptr;
179 DomTreeUpdater *DTU =
nullptr;
180 LoopInfo *LI =
nullptr;
181 BlockFrequencyInfo *BFI;
182 BranchProbabilityInfo *BPI;
183 ProfileSummaryInfo *PSI =
nullptr;
194 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
197 SetOfInstrs InsertedInsts;
201 InstrToOrigTy PromotedInsts;
204 SetOfInstrs RemovedInsts;
207 DenseMap<Value *, Instruction *> SeenChainsForSExt;
212 MapVector<AssertingVH<Value>,
217 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
220 DenseMap<AssertingVH<GetElementPtrInst>,
int> LargeOffsetGEPID;
223 ValueToSExts ValToSExtendedUses;
229 const DataLayout *DL =
nullptr;
232 CodeGenPrepare(
const TargetMachine *TM)
233 : Opts(cl::LibraryOptionsContext::
get<CodeGenOptions>(
234 TM->
Options.MCOptions.LibraryOptions)),
237 bool IsHugeFunc =
false;
243 SmallPtrSet<BasicBlock *, 32> FreshBBs;
245 void releaseMemory() {
247 InsertedInsts.clear();
248 PromotedInsts.clear();
255 template <
typename F>
256 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB,
F f) {
260 Value *CurValue = &*CurInstIterator;
261 WeakTrackingVH IterHandle(CurValue);
267 if (IterHandle != CurValue) {
268 CurInstIterator = BB->
begin();
274 DominatorTree &getDT() {
return DTU->getDomTree(); }
276 void removeAllAssertingVHReferences(
Value *
V);
279 bool eliminateMostlyEmptyBlocks(
Function &
F,
bool &ResetLI);
280 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
281 bool canMergeBlocks(
const BasicBlock *BB,
const BasicBlock *DestBB)
const;
282 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
283 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
285 bool makeBitReverse(Instruction &
I);
287 bool optimizeInst(Instruction *
I, ModifyDT &ModifiedDT);
288 bool optimizeMemoryInst(Instruction *MemoryInst,
Value *Addr,
Type *AccessTy,
290 bool optimizeGatherScatterInst(Instruction *MemoryInst,
Value *Ptr);
291 bool optimizeMulWithOverflow(Instruction *
I,
bool IsSigned,
292 ModifyDT &ModifiedDT);
293 bool optimizeInlineAsmInst(CallInst *CS);
295 bool optimizeExt(Instruction *&
I);
296 bool optimizeExtUses(Instruction *
I);
297 bool optimizeLoadExt(LoadInst *
Load);
298 bool optimizeShiftInst(BinaryOperator *BO);
299 bool optimizeFunnelShift(IntrinsicInst *Fsh);
300 bool optimizeSelectInst(SelectInst *SI);
301 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
302 bool optimizeSwitchType(SwitchInst *SI);
303 bool optimizeSwitchPhiConstants(SwitchInst *SI);
304 bool optimizeSwitchInst(SwitchInst *SI);
305 bool optimizeExtractElementInst(Instruction *Inst);
306 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
307 bool fixupDbgVariableRecord(DbgVariableRecord &
I);
308 bool fixupDbgVariableRecordsOnInst(Instruction &
I);
311 bool canFormExtLd(
const SmallVectorImpl<Instruction *> &MovedExts,
312 LoadInst *&LI, Instruction *&Inst,
bool HasPromoted);
313 bool tryToPromoteExts(TypePromotionTransaction &TPT,
314 const SmallVectorImpl<Instruction *> &Exts,
315 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
316 unsigned CreatedInstsCost = 0);
318 bool splitLargeGEPOffsets();
319 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
320 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
322 bool performAddressTypePromotion(
323 Instruction *&Inst,
bool AllowPromotionWithoutCommonHeader,
324 bool HasPromoted, TypePromotionTransaction &TPT,
325 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
327 bool simplifyOffsetableRelocate(GCStatepointInst &
I);
329 bool tryToSinkFreeOperands(Instruction *
I);
330 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO,
Value *Arg0,
Value *Arg1,
332 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
333 bool optimizeURem(Instruction *Rem);
334 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
335 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
336 bool unfoldPowerOf2Test(CmpInst *Cmp);
345 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
349 StringRef getPassName()
const override {
return "CodeGen Prepare"; }
351 void getAnalysisUsage(AnalysisUsage &AU)
const override {
359 AU.
addRequired<BranchProbabilityInfoWrapperPass>();
367char CodeGenPrepareLegacyPass::ID = 0;
369bool CodeGenPrepareLegacyPass::runOnFunction(
Function &
F) {
372 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
373 CodeGenPrepare CGP(TM);
374 CGP.DL = &
F.getDataLayout();
377 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
378 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
379 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
380 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
381 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
382 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
383 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
385 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
386 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() :
nullptr;
387 DomTreeUpdater DTUpdater(
388 &getAnalysis<DominatorTreeWrapperPass>().
getDomTree(),
389 DomTreeUpdater::UpdateStrategy::Lazy);
390 CGP.DTU = &DTUpdater;
396 "Optimize for code generation",
false,
false)
408 return new CodeGenPrepareLegacyPass();
413 CodeGenPrepare CGP(TM);
426 DL = &
F.getDataLayout();
439 "analysis to be available");
440 BBSectionsProfileReader =
443 DomTreeUpdater::UpdateStrategy::Lazy);
449 bool EverMadeChange =
false;
451 OptSize =
F.hasOptSize();
454 if (Opts.bbsections_guided_section_prefix && BBSectionsProfileReader &&
456 (void)
F.setSectionPrefix(
"hot");
457 }
else if (Opts.profile_guided_section_prefix) {
461 if (
F.hasFnAttribute(Attribute::Hot) ||
462 PSI->isFunctionHotInCallGraph(&
F, *BFI))
463 (void)
F.setSectionPrefix(
"hot");
467 else if (PSI->isFunctionColdInCallGraph(&
F, *BFI) ||
468 F.hasFnAttribute(Attribute::Cold))
469 (void)
F.setSectionPrefix(
"unlikely");
470 else if (Opts.profile_unknown_in_special_section &&
471 PSI->hasPartialSampleProfile() && PSI->isFunctionHotnessUnknown(
F))
472 (void)
F.setSectionPrefix(
"unknown");
478 const DenseMap<unsigned int, unsigned int> &BypassWidths =
481 while (BB !=
nullptr) {
494 EverMadeChange |= eliminateAssumptions(
F);
496 auto resetLoopInfo = [
this]() {
503 bool ResetLI =
false;
504 EverMadeChange |= eliminateMostlyEmptyBlocks(
F, ResetLI);
508 if (Opts.cgp_branch_opts)
509 EverMadeChange |= splitBranchCondition(
F);
515 EverMadeChange |=
Split;
521 assert(getDT().
verify(DominatorTree::VerificationLevel::Fast) &&
522 "Incorrect DominatorTree updates in CGP");
530 IsHugeFunc =
F.size() > Opts.cgp_huge_func;
532 bool MadeChange =
true;
533 bool FuncIterated =
false;
543 if (FuncIterated && !FreshBBs.
contains(&BB))
546 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
562 else if (FuncIterated)
567 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
572 FuncIterated = IsHugeFunc;
574 if (Opts.cgp_type_promotion_merge && !ValToSExtendedUses.empty())
575 MadeChange |= mergeSExts(
F);
576 if (!LargeOffsetGEPMap.
empty())
577 MadeChange |= splitLargeGEPOffsets();
578 MadeChange |= optimizePhiTypes(
F);
581 eliminateFallThrough(
F);
585 assert(getDT().
verify(DominatorTree::VerificationLevel::Fast) &&
586 "Incorrect DominatorTree updates in CGP");
593 for (Instruction *
I : RemovedInsts)
596 EverMadeChange |= MadeChange;
597 SeenChainsForSExt.
clear();
598 ValToSExtendedUses.clear();
599 RemovedInsts.clear();
600 LargeOffsetGEPMap.
clear();
601 LargeOffsetGEPID.
clear();
610 if (Opts.cgp_branch_opts) {
615 SmallSetVector<BasicBlock *, 8> WorkList;
616 for (BasicBlock &BB :
F) {
622 for (BasicBlock *Succ : Successors)
628 MadeChange |= !WorkList.
empty();
629 while (!WorkList.
empty()) {
635 for (BasicBlock *Succ : Successors)
645 if (EverMadeChange || MadeChange)
646 MadeChange |= eliminateFallThrough(
F);
648 EverMadeChange |= MadeChange;
651 if (Opts.cgp_gc_opts) {
653 for (BasicBlock &BB :
F)
654 for (Instruction &
I : BB)
657 for (
auto &
I : Statepoints)
658 EverMadeChange |= simplifyOffsetableRelocate(*
I);
663 EverMadeChange |= placeDbgValues(
F);
664 EverMadeChange |= placePseudoProbes(
F);
667 if (Opts.cgp_verify_bfi_updates)
671 return EverMadeChange;
674bool CodeGenPrepare::eliminateAssumptions(
Function &
F) {
675 bool MadeChange =
false;
676 for (BasicBlock &BB :
F) {
677 CurInstIterator = BB.begin();
678 while (CurInstIterator != BB.end()) {
683 Assume->eraseFromParent();
685 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
696void CodeGenPrepare::removeAllAssertingVHReferences(
Value *
V) {
697 LargeOffsetGEPMap.
erase(
V);
706 auto VecI = LargeOffsetGEPMap.
find(
GEP->getPointerOperand());
707 if (VecI == LargeOffsetGEPMap.
end())
710 auto &GEPVector = VecI->second;
713 if (GEPVector.empty())
714 LargeOffsetGEPMap.
erase(VecI);
718[[maybe_unused]]
void CodeGenPrepare::verifyBFIUpdates(
Function &
F) {
721 BranchProbabilityInfo NewBPI(
F, NewCI, TLInfo);
722 BlockFrequencyInfo NewBFI(
F, NewBPI, NewCI);
723 NewBFI.verifyMatch(*BFI);
729bool CodeGenPrepare::eliminateFallThrough(
Function &
F) {
731 SmallPtrSet<BasicBlock *, 8> Preds;
739 BasicBlock *SinglePred = BB->getSinglePredecessor();
742 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
755 FreshBBs.
insert(SinglePred);
763 for (
auto *
Pred : Preds)
771BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
780 if (BBI != BB->
begin()) {
791 if (!canMergeBlocks(BB, DestBB))
801bool CodeGenPrepare::eliminateMostlyEmptyBlocks(
Function &
F,
bool &ResetLI) {
802 SmallPtrSet<BasicBlock *, 16> Preheaders;
804 while (!LoopList.empty()) {
805 Loop *
L = LoopList.pop_back_val();
807 if (BasicBlock *Preheader =
L->getLoopPreheader())
808 Preheaders.
insert(Preheader);
812 bool MadeChange =
false;
813 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
817 if (Opts.cgp_delete_phis)
825 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
827 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.
count(BB)))
830 ResetLI |= eliminateMostlyEmptyBlock(BB);
836bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
843 if (Opts.cgp_preheader_prot && isPreheader &&
887 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
892 if (DestBBPred == BB)
896 return DestPN.getIncomingValueForBlock(BB) ==
897 DestPN.getIncomingValueForBlock(DestBBPred);
899 SameIncomingValueBBs.
insert(DestBBPred);
908 BlockFrequency PredFreq = BFI->getBlockFreq(
Pred);
909 BlockFrequency
BBFreq = BFI->getBlockFreq(BB);
911 for (
auto *SameValueBB : SameIncomingValueBBs)
912 if (SameValueBB->getUniquePredecessor() ==
Pred &&
913 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
914 BBFreq += BFI->getBlockFreq(SameValueBB);
916 std::optional<BlockFrequency> Limit =
917 BBFreq.mul(Opts.cgp_freq_ratio_to_skip_merge);
918 return !Limit || PredFreq <= *Limit;
924bool CodeGenPrepare::canMergeBlocks(
const BasicBlock *BB,
925 const BasicBlock *DestBB)
const {
929 for (
const PHINode &PN : BB->
phis()) {
930 for (
const Instruction *UI : PN.users()) {
936 if (UI->getParent() == DestBB) {
938 for (
unsigned I = 0,
E = UPN->getNumIncomingValues();
I !=
E; ++
I) {
941 Insn->
getParent() != UPN->getIncomingBlock(
I))
956 SmallPtrSet<const BasicBlock *, 16> BBPreds;
959 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
960 BBPreds.
insert(BBPN->getIncomingBlock(i));
969 for (
const PHINode &PN : DestBB->
phis()) {
970 const Value *
V1 = PN.getIncomingValueForBlock(
Pred);
971 const Value *V2 = PN.getIncomingValueForBlock(BB);
975 if (V2PN->getParent() == BB)
976 V2 = V2PN->getIncomingValueForBlock(
Pred);
993 if (OldI && IsHuge) {
1003bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1013 if (SinglePred != DestBB) {
1014 assert(SinglePred == BB &&
1015 "Single predecessor not the same as predecessor");
1024 FreshBBs.
insert(SinglePred);
1025 FreshBBs.
erase(DestBB);
1033 for (PHINode &PN : DestBB->
phis()) {
1035 Value *InVal = PN.removeIncomingValue(BB,
false);
1040 if (InValPhi && InValPhi->
getParent() == BB) {
1049 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1050 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1053 PN.addIncoming(InVal,
Pred);
1061 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1067 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1071 if (!PredOfDestBB.contains(
Pred)) {
1081 DTUpdates.
push_back({DominatorTree::Delete, BB, DestBB});
1101 for (
auto *ThisRelocate : AllRelocateCalls) {
1102 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1103 ThisRelocate->getDerivedPtrIndex());
1104 RelocateIdxMap.
insert(std::make_pair(
K, ThisRelocate));
1106 for (
auto &Item : RelocateIdxMap) {
1107 std::pair<unsigned, unsigned>
Key = Item.first;
1108 if (
Key.first ==
Key.second)
1113 auto BaseKey = std::make_pair(
Key.first,
Key.first);
1116 auto MaybeBase = RelocateIdxMap.
find(BaseKey);
1117 if (MaybeBase == RelocateIdxMap.
end())
1122 RelocateInstMap[MaybeBase->second].push_back(
I);
1130 for (
unsigned i = 1; i <
GEP->getNumOperands(); i++) {
1133 if (!
Op ||
Op->getZExtValue() > 20)
1137 for (
unsigned i = 1; i <
GEP->getNumOperands(); i++)
1147 bool MadeChange =
false;
1154 for (
auto R = RelocatedBase->
getParent()->getFirstInsertionPt();
1155 &*R != RelocatedBase; ++R)
1159 RelocatedBase->
moveBefore(RI->getIterator());
1166 "Not relocating a derived object of the original base object");
1167 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1172 if (RelocatedBase->
getParent() != ToReplace->getParent()) {
1182 if (!Derived || Derived->getPointerOperand() !=
Base)
1191 "Should always have one since it's not a terminator");
1195 Builder.disableGEPCanonicalization();
1196 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1198 Value *Replacement = Builder.CreateGEP(Derived->getSourceElementType(),
1201 ToReplace->replaceAllUsesWith(Replacement);
1202 ToReplace->eraseFromParent();
1226bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &
I) {
1227 bool MadeChange =
false;
1229 for (
auto *U :
I.users())
1236 if (AllRelocateCalls.
size() < 2)
1241 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1243 if (RelocateInstMap.
empty())
1246 for (
auto &Item : RelocateInstMap)
1260 bool MadeChange =
false;
1263 Use &TheUse = UI.getUse();
1270 UserBB = PN->getIncomingBlock(TheUse);
1278 if (
User->isEHPad())
1288 if (UserBB == DefBB)
1292 CastInst *&InsertedCast = InsertedCasts[UserBB];
1294 if (!InsertedCast) {
1302 TheUse = InsertedCast;
1321 if (!SrcInst || SrcInst->getParent() == BCI->
getParent() ||
1322 SrcInst->isTerminator())
1326 Type *SrcTy = SrcInst->getType();
1327 EVT SrcVT =
TLI.getValueType(
DL, SrcTy);
1328 EVT DestVT =
TLI.getValueType(
DL, DestTy);
1340 bool IsCrossDomain = DestTy->
isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1343 unsigned NativeWidth =
DL.getPointerSizeInBits();
1344 bool IsLargeScalar =
1346 DL.getTypeSizeInBits(DestTy).getFixedValue() > NativeWidth;
1348 if (IsCrossDomain || IsLargeScalar)
1354 : std::next(SrcInst->getIterator());
1370 if (!
TLI.isFreeAddrSpaceCast(
DL, ASC->getSrcAddressSpace(),
1371 ASC->getDestAddressSpace()))
1426static std::optional<std::pair<Instruction *, Constant *>>
1429 if (!L || L->getHeader() != PN->
getParent() || !L->getLoopLatch())
1430 return std::nullopt;
1433 if (!IVInc || LI->
getLoopFor(IVInc->getParent()) != L)
1434 return std::nullopt;
1438 return std::make_pair(IVInc, Step);
1439 return std::nullopt;
1452 return IVInc->first ==
I;
1456bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1460 auto IsReplacableIVIncrement = [
this, &
Cmp](BinaryOperator *BO) {
1464 assert(L &&
"L should not be null after isIVIncrement()");
1466 if (LI->getLoopFor(
Cmp->getParent()) != L)
1479 return BO->
hasOneUse() && DT.dominates(
Cmp->getParent(),
L->getLoopLatch());
1481 if (BO->
getParent() !=
Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1504 if (BO->
getOpcode() == Instruction::Add &&
1505 IID == Intrinsic::usub_with_overflow) {
1512 for (Instruction &Iter : *
Cmp->getParent()) {
1515 if ((BO->
getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1520 assert(InsertPt !=
nullptr &&
"Parent block did not contain cmp or binop");
1523 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1524 if (BO->
getOpcode() != Instruction::Xor) {
1525 Value *Math = Builder.CreateExtractValue(MathOV, 0,
"math");
1529 "Patterns with XOr should use the BO only in the compare");
1530 Value *OV = Builder.CreateExtractValue(MathOV, 1,
"ov");
1532 Cmp->eraseFromParent();
1542 Value *
A = Cmp->getOperand(0), *
B = Cmp->getOperand(1);
1550 B = ConstantInt::get(
B->getType(), 1);
1558 for (
User *U :
A->users()) {
1569bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1570 ModifyDT &ModifiedDT) {
1571 bool EdgeCase =
false;
1573 BinaryOperator *
Add;
1578 A =
Add->getOperand(0);
1579 B =
Add->getOperand(1);
1585 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1591 if (
Add->getParent() !=
Cmp->getParent() && !
Add->hasOneUse())
1594 if (!replaceMathCmpWithIntrinsic(
Add,
A,
B, Cmp,
1595 Intrinsic::uadd_with_overflow))
1599 ModifiedDT = ModifyDT::ModifyInstDT;
1603bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1604 ModifyDT &ModifiedDT) {
1611 ICmpInst::Predicate
Pred =
Cmp->getPredicate();
1612 if (
Pred == ICmpInst::ICMP_UGT) {
1614 Pred = ICmpInst::ICMP_ULT;
1618 B = ConstantInt::get(
B->getType(), 1);
1619 Pred = ICmpInst::ICMP_ULT;
1624 Pred = ICmpInst::ICMP_ULT;
1626 if (
Pred != ICmpInst::ICMP_ULT)
1633 BinaryOperator *
Sub =
nullptr;
1634 for (User *U : CmpVariableOperand->
users()) {
1642 const APInt *CmpC, *AddC;
1654 Sub->hasNUsesOrMore(1)))
1660 if (
Sub->getParent() !=
Cmp->getParent() && !
Sub->hasOneUse())
1663 if (!replaceMathCmpWithIntrinsic(
Sub,
Sub->getOperand(0),
Sub->getOperand(1),
1664 Cmp, Intrinsic::usub_with_overflow))
1668 ModifiedDT = ModifyDT::ModifyInstDT;
1675bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1688 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1694 Type *OpTy =
X->getType();
1702 if (
Pred == ICmpInst::ICMP_EQ) {
1703 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1704 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1706 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1712 if (IsPowerOf2OrZeroTest ||
1723 NewCmp = Builder.CreateICmp(NewPred,
And, ConstantInt::getNullValue(OpTy));
1732 NewCmp = Builder.CreateICmp(NewPred,
Xor,
Sub);
1735 Cmp->replaceAllUsesWith(NewCmp);
1748 if (
TLI.hasMultipleConditionRegisters(
EVT::getEVT(Cmp->getType())))
1755 bool UsedInPhiOrCurrentBlock =
any_of(Cmp->users(), [Cmp](
User *U) {
1756 return isa<PHINode>(U) ||
1757 cast<Instruction>(U)->getParent() == Cmp->getParent();
1762 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1763 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1764 DL.getLargestLegalIntTypeSizeInBits())
1770 bool MadeChange =
false;
1773 Use &TheUse = UI.getUse();
1788 if (UserBB == DefBB)
1792 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1798 Cmp->getOperand(0), Cmp->getOperand(1),
"");
1805 TheUse = InsertedCmp;
1811 if (Cmp->use_empty()) {
1812 Cmp->eraseFromParent();
1839 bool EnableICmpEqToICmpSt) {
1840 if (!EnableICmpEqToICmpSt &&
TLI.isEqualityCmpFoldedWithSignedCmp())
1849 for (
User *U : Cmp->users()) {
1871 if (CmpBB != FalseBB)
1874 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1888 for (
User *U : Cmp->users()) {
1890 BI->swapSuccessors();
1896 SI->swapProfMetadata();
1908 Value *Op0 = Cmp->getOperand(0);
1909 Value *Op1 = Cmp->getOperand(1);
1918 unsigned NumInspected = 0;
1921 if (++NumInspected > 128)
1929 if (GoodToSwap > 0) {
1930 Cmp->swapOperands();
1943 EVT VT =
TLI.getValueType(
DL, Cmp->getOperand(0)->getType());
1944 if (
TLI.isFAbsFree(VT) &&
1950 auto ShouldReverseTransform = [](
FPClassTest ClassTest) {
1953 auto [ClassVal, ClassTest] =
1959 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
1963 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
1964 Cmp->replaceAllUsesWith(IsFPClass);
1972 Value *Incr, *RemAmt;
1977 Value *AddInst, *AddOffset;
1980 if (PN !=
nullptr) {
1982 AddOffset =
nullptr;
2000 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2004 if (!L->contains(Rem))
2008 if (!L->isLoopInvariant(RemAmt))
2012 if (AddOffset && !L->isLoopInvariant(AddOffset))
2022 Constant *Step = LoopIncrInfo->second;
2026 if (!StepC || !RemC || StepC->isZero() ||
2027 StepC->getValue().uge(RemC->getValue()))
2031 (void)(RemC->getValue() - 1).uadd_ov(StepC->getValue(), Overflow);
2043 AddInstOut = AddInst;
2044 AddOffsetOut = AddOffset;
2066 Value *AddOffset, *RemAmt, *AddInst;
2070 AddOffset, LoopIncrPN, Step))
2099 IRBuilder<> PHBuilder(L->getLoopPreheader()->getTerminator());
2101 assert(AddOffset &&
"We found an add but missing values");
2107 if (!NewStart && !IsConstRem)
2109 Start = NewStart ? NewStart : PHBuilder.
CreateNUWAdd(Start, AddOffset);
2117 StartRem = PHBuilder.
CreateURem(Start, RemAmt);
2122 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2128 Value *RemAdd = Builder.CreateNUWAdd(NewRem, Step);
2135 Value *RemSub = Builder.CreateNUWSub(RemAdd, RemAmt);
2136 RemSel = Builder.CreateSelect(RemCmp, RemSub, RemAdd);
2141 NewRem->
addIncoming(StartRem, L->getLoopPreheader());
2145 FreshBBs.
insert(L->getLoopPreheader());
2147 FreshBBs.
insert(L->getLoopLatch());
2158bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2164bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2168 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2171 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2174 if (unfoldPowerOf2Test(Cmp))
2195 SetOfInstrs &InsertedInsts) {
2198 assert(!InsertedInsts.count(AndI) &&
2199 "Attempting to optimize already optimized and instruction");
2200 (void)InsertedInsts;
2220 if (!CmpC || !CmpC->
isZero())
2224 if (!
TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2235 Use &TheUse = UI.getUse();
2253 TheUse = InsertedAnd;
2270 if (
User->getOpcode() != Instruction::And ||
2276 if ((Cimm & (Cimm + 1)).getBoolValue())
2290 bool MadeChange =
false;
2293 TruncE = TruncI->user_end();
2294 TruncUI != TruncE;) {
2296 Use &TruncTheUse = TruncUI.getUse();
2302 int ISDOpcode =
TLI.InstructionOpcodeToISD(TruncUser->
getOpcode());
2311 if (
TLI.isOperationLegalOrCustom(
2312 ISDOpcode,
TLI.getValueType(
DL, TruncUser->
getType(),
true)))
2321 if (UserBB == TruncUserBB)
2325 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2327 if (!InsertedShift && !InsertedTrunc) {
2331 if (ShiftI->
getOpcode() == Instruction::AShr)
2333 BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
"");
2336 BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
"");
2344 TruncInsertPt.setHeadBit(
true);
2345 assert(TruncInsertPt != TruncUserBB->
end());
2349 InsertedTrunc->
insertBefore(*TruncUserBB, TruncInsertPt);
2350 InsertedTrunc->
setDebugLoc(TruncI->getDebugLoc());
2354 TruncTheUse = InsertedTrunc;
2385 bool shiftIsLegal =
TLI.isTypeLegal(
TLI.getValueType(
DL, ShiftI->
getType()));
2387 bool MadeChange =
false;
2391 Use &TheUse = UI.getUse();
2405 if (UserBB == DefBB) {
2433 if (!InsertedShift) {
2437 if (ShiftI->
getOpcode() == Instruction::AShr)
2439 BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
"");
2442 BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
"");
2450 TheUse = InsertedShift;
2493 if ((IntrinsicID == Intrinsic::cttz &&
TLI->isCheapToSpeculateCttz(Ty)) ||
2494 (IntrinsicID == Intrinsic::ctlz &&
TLI->isCheapToSpeculateCtlz(Ty)))
2498 unsigned SizeInBits = Ty->getScalarSizeInBits();
2499 if (Ty->isVectorTy())
2510 nullptr,
"cond.false");
2512 FreshBBs.
insert(CallBlock);
2519 SplitPt.setHeadBit(
true);
2521 nullptr,
"cond.end");
2523 FreshBBs.
insert(EndBlock);
2527 Builder.SetCurrentDebugLocation(CountZeros->
getDebugLoc());
2534 Op = Builder.CreateFreeze(
Op,
Op->getName() +
".fr");
2535 Value *Cmp = Builder.CreateICmpEQ(
Op,
Zero,
"cmpz");
2536 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2542 Builder.SetInsertPoint(EndBlock->
begin());
2543 PHINode *PN = Builder.CreatePHI(Ty, 2,
"ctz");
2553 ModifiedDT = ModifyDT::ModifyBBDT;
2557bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2561 if (CI->
isInlineAsm() && optimizeInlineAsmInst(CI))
2569 for (
auto &Arg : CI->
args()) {
2574 if (!Arg->getType()->isPointerTy())
2576 APInt
Offset(
DL->getIndexSizeInBits(
2579 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*
DL,
Offset);
2586 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2604 MaybeAlign MIDestAlign =
MI->getDestAlign();
2605 if (!MIDestAlign || DestAlign > *MIDestAlign)
2606 MI->setDestAlignment(DestAlign);
2608 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2610 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2611 MTI->setSourceAlignment(SrcAlign);
2621 for (
auto &Arg : CI->
args()) {
2622 if (!Arg->getType()->isPointerTy())
2624 unsigned AS = Arg->getType()->getPointerAddressSpace();
2625 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2631 switch (
II->getIntrinsicID()) {
2634 case Intrinsic::assume:
2636 case Intrinsic::allow_runtime_check:
2637 case Intrinsic::allow_ubsan_check:
2638 case Intrinsic::experimental_widenable_condition: {
2642 if (
II->use_empty()) {
2643 II->eraseFromParent();
2647 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2652 case Intrinsic::objectsize:
2654 case Intrinsic::is_constant:
2656 case Intrinsic::aarch64_stlxr:
2657 case Intrinsic::aarch64_stxr: {
2666 InsertedInsts.insert(ExtVal);
2670 case Intrinsic::launder_invariant_group: {
2671 Value *ArgVal =
II->getArgOperand(0);
2672 auto it = LargeOffsetGEPMap.
find(
II);
2673 if (it != LargeOffsetGEPMap.
end()) {
2677 auto GEPs = std::move(it->second);
2678 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2683 II->eraseFromParent();
2686 case Intrinsic::cttz:
2687 case Intrinsic::ctlz:
2691 case Intrinsic::fshl:
2692 case Intrinsic::fshr:
2693 return optimizeFunnelShift(
II);
2694 case Intrinsic::masked_gather:
2695 return optimizeGatherScatterInst(
II,
II->getArgOperand(0));
2696 case Intrinsic::masked_scatter:
2697 return optimizeGatherScatterInst(
II,
II->getArgOperand(1));
2698 case Intrinsic::masked_load:
2701 if (VT->getNumElements() == 1) {
2702 Value *PtrVal =
II->getArgOperand(0);
2704 if (optimizeMemoryInst(
II, PtrVal, VT->getElementType(), AS))
2709 case Intrinsic::masked_store:
2713 if (VT->getNumElements() == 1) {
2714 Value *PtrVal =
II->getArgOperand(1);
2716 if (optimizeMemoryInst(
II, PtrVal, VT->getElementType(), AS))
2721 case Intrinsic::umul_with_overflow:
2722 return optimizeMulWithOverflow(
II,
false, ModifiedDT);
2723 case Intrinsic::smul_with_overflow:
2724 return optimizeMulWithOverflow(
II,
true, ModifiedDT);
2727 SmallVector<Value *, 2> PtrOps;
2730 while (!PtrOps.
empty()) {
2733 if (optimizeMemoryInst(
II, PtrVal, AccessTy, AS))
2747 FortifiedLibCallSimplifier Simplifier(TLInfo,
true);
2749 if (
Value *
V = Simplifier.optimizeCall(CI, Builder)) {
2759 auto GetUniformReturnValue = [](
const Function *
F) -> GlobalVariable * {
2760 if (!
F->getReturnType()->isPointerTy())
2763 GlobalVariable *UniformValue =
nullptr;
2764 for (
auto &BB : *
F) {
2769 else if (
V != UniformValue)
2777 return UniformValue;
2780 if (
Callee->hasExactDefinition()) {
2781 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2782 bool MadeChange =
false;
2808 switch (
II->getIntrinsicID()) {
2809 case Intrinsic::memset:
2810 case Intrinsic::memcpy:
2811 case Intrinsic::memmove:
2818 if (Callee && TLInfo)
2820 case LibFunc_strcpy:
2821 case LibFunc_strncpy:
2822 case LibFunc_strcat:
2823 case LibFunc_strncat:
2864bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2865 ModifyDT &ModifiedDT) {
2870 assert(LI->getLoopFor(BB) ==
nullptr &&
"A return block cannot be in a loop");
2872 PHINode *PN =
nullptr;
2873 ExtractValueInst *EVI =
nullptr;
2874 BitCastInst *BCI =
nullptr;
2896 auto isFakeUse = [&FakeUses](
const Instruction *Inst) {
2898 II &&
II->getIntrinsicID() == Intrinsic::fake_use) {
2927 auto MayBePermittedAsTailCall = [&](
const auto *CI) {
2944 MayBePermittedAsTailCall(CI)) {
2965 MayBePermittedAsTailCall(CI)) {
2972 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2976 if (Instruction *
I =
Pred->rbegin()->getPrevNode()) {
2978 if (CI && CI->
use_empty() && MayBePermittedAsTailCall(CI)) {
2993 for (
auto const &TailCallBB : TailCallBBs) {
3002 assert(!Opts.cgp_verify_bfi_updates ||
3003 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3004 BFI->setBlockFreq(BB,
3005 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
3006 ModifiedDT = ModifyDT::ModifyBBDT;
3015 for (
auto *CI : CallInsts) {
3016 for (
auto const *FakeUse : FakeUses) {
3017 auto *ClonedInst = FakeUse->clone();
3035struct ExtAddrMode :
public TargetLowering::AddrMode {
3036 Value *BaseReg =
nullptr;
3037 Value *ScaledReg =
nullptr;
3038 Value *OriginalValue =
nullptr;
3039 bool InBounds =
true;
3043 BaseRegField = 0x01,
3045 BaseOffsField = 0x04,
3046 ScaledRegField = 0x08,
3048 MultipleFields = 0xff
3051 ExtAddrMode() =
default;
3053 void print(raw_ostream &OS)
const;
3060 if (ScaledReg == From)
3064 FieldName
compare(
const ExtAddrMode &other) {
3067 if (BaseReg && other.
BaseReg &&
3069 return MultipleFields;
3070 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3071 return MultipleFields;
3074 return MultipleFields;
3077 if (InBounds != other.InBounds)
3078 return MultipleFields;
3081 unsigned Result = NoField;
3084 if (BaseGV != other.BaseGV)
3086 if (BaseOffs != other.BaseOffs)
3089 Result |= ScaledRegField;
3092 if (Scale && other.
Scale && Scale != other.
Scale)
3096 return MultipleFields;
3098 return static_cast<FieldName
>(
Result);
3108 return !BaseOffs && !Scale && !(BaseGV &&
BaseReg);
3119 case ScaledRegField:
3127 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3132 case ExtAddrMode::BaseRegField:
3135 case ExtAddrMode::BaseGVField:
3138 assert(BaseReg ==
nullptr);
3142 case ExtAddrMode::ScaledRegField:
3147 for (
const ExtAddrMode &AM : AddrModes)
3153 case ExtAddrMode::BaseOffsField:
3156 assert(ScaledReg ==
nullptr);
3166static inline raw_ostream &
operator<<(raw_ostream &OS,
const ExtAddrMode &AM) {
3172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3173void ExtAddrMode::print(raw_ostream &OS)
const {
3174 bool NeedPlus =
false;
3180 BaseGV->printAsOperand(OS,
false);
3185 OS << (NeedPlus ?
" + " :
"") << BaseOffs;
3190 OS << (NeedPlus ?
" + " :
"") <<
"Base:";
3191 BaseReg->printAsOperand(OS,
false);
3195 OS << (NeedPlus ?
" + " :
"") << Scale <<
"*";
3218class TypePromotionTransaction {
3222 class TypePromotionAction {
3230 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3232 virtual ~TypePromotionAction() =
default;
3239 virtual void undo() = 0;
3244 virtual void commit() {
3250 class InsertionHandler {
3259 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3262 bool HasPrevInstruction;
3266 InsertionHandler(Instruction *Inst) {
3274 if (HasPrevInstruction) {
3282 void insert(Instruction *Inst) {
3283 if (HasPrevInstruction) {
3295 Inst->
getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3300 class OperandSetter :
public TypePromotionAction {
3309 OperandSetter(Instruction *Inst,
unsigned Idx,
Value *NewVal)
3310 : TypePromotionAction(Inst),
Idx(
Idx) {
3312 <<
"for:" << *Inst <<
"\n"
3313 <<
"with:" << *NewVal <<
"\n");
3319 void undo()
override {
3321 <<
"for: " << *Inst <<
"\n"
3322 <<
"with: " << *Origin <<
"\n");
3329 class OperandsHider :
public TypePromotionAction {
3331 SmallVector<Value *, 4> OriginalValues;
3335 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3338 OriginalValues.
reserve(NumOpnds);
3339 for (
unsigned It = 0; It < NumOpnds; ++It) {
3351 void undo()
override {
3353 for (
unsigned It = 0, EndIt = OriginalValues.
size(); It != EndIt; ++It)
3359 class TruncBuilder :
public TypePromotionAction {
3366 TruncBuilder(Instruction *Opnd,
Type *Ty) : TypePromotionAction(Opnd) {
3368 Builder.SetCurrentDebugLocation(
DebugLoc());
3369 Val = Builder.CreateTrunc(Opnd, Ty,
"promoted");
3374 Value *getBuiltValue() {
return Val; }
3377 void undo()
override {
3380 IVal->eraseFromParent();
3385 class SExtBuilder :
public TypePromotionAction {
3392 SExtBuilder(Instruction *InsertPt,
Value *Opnd,
Type *Ty)
3393 : TypePromotionAction(InsertPt) {
3395 Val = Builder.CreateSExt(Opnd, Ty,
"promoted");
3400 Value *getBuiltValue() {
return Val; }
3403 void undo()
override {
3406 IVal->eraseFromParent();
3411 class ZExtBuilder :
public TypePromotionAction {
3418 ZExtBuilder(Instruction *InsertPt,
Value *Opnd,
Type *Ty)
3419 : TypePromotionAction(InsertPt) {
3421 Builder.SetCurrentDebugLocation(
DebugLoc());
3422 Val = Builder.CreateZExt(Opnd, Ty,
"promoted");
3427 Value *getBuiltValue() {
return Val; }
3430 void undo()
override {
3433 IVal->eraseFromParent();
3438 class TypeMutator :
public TypePromotionAction {
3444 TypeMutator(Instruction *Inst,
Type *NewTy)
3445 : TypePromotionAction(Inst), OrigTy(Inst->
getType()) {
3446 LLVM_DEBUG(
dbgs() <<
"Do: MutateType: " << *Inst <<
" with " << *NewTy
3452 void undo()
override {
3453 LLVM_DEBUG(
dbgs() <<
"Undo: MutateType: " << *Inst <<
" with " << *OrigTy
3460 class UsesReplacer :
public TypePromotionAction {
3462 struct InstructionAndIdx {
3469 InstructionAndIdx(Instruction *Inst,
unsigned Idx)
3470 : Inst(Inst),
Idx(
Idx) {}
3476 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3484 UsesReplacer(Instruction *Inst,
Value *New)
3485 : TypePromotionAction(Inst),
New(
New) {
3486 LLVM_DEBUG(
dbgs() <<
"Do: UsersReplacer: " << *Inst <<
" with " << *New
3489 for (Use &U : Inst->
uses()) {
3491 OriginalUses.
push_back(InstructionAndIdx(UserI,
U.getOperandNo()));
3502 void undo()
override {
3504 for (InstructionAndIdx &Use : OriginalUses)
3505 Use.Inst->setOperand(
Use.Idx, Inst);
3510 for (DbgVariableRecord *DVR : DbgVariableRecords)
3511 DVR->replaceVariableLocationOp(New, Inst);
3516 class InstructionRemover :
public TypePromotionAction {
3518 InsertionHandler Inserter;
3522 OperandsHider Hider;
3525 UsesReplacer *Replacer =
nullptr;
3528 SetOfInstrs &RemovedInsts;
3535 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3536 Value *New =
nullptr)
3537 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3538 RemovedInsts(RemovedInsts) {
3540 Replacer =
new UsesReplacer(Inst, New);
3541 LLVM_DEBUG(
dbgs() <<
"Do: InstructionRemover: " << *Inst <<
"\n");
3542 RemovedInsts.insert(Inst);
3549 ~InstructionRemover()
override {
delete Replacer; }
3551 InstructionRemover &operator=(
const InstructionRemover &other) =
delete;
3552 InstructionRemover(
const InstructionRemover &other) =
delete;
3556 void undo()
override {
3557 LLVM_DEBUG(
dbgs() <<
"Undo: InstructionRemover: " << *Inst <<
"\n");
3558 Inserter.insert(Inst);
3562 RemovedInsts.erase(Inst);
3570 using ConstRestorationPt =
const TypePromotionAction *;
3572 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3573 : RemovedInsts(RemovedInsts) {}
3580 void rollback(ConstRestorationPt Point);
3583 ConstRestorationPt getRestorationPoint()
const;
3588 void setOperand(Instruction *Inst,
unsigned Idx,
Value *NewVal);
3597 void mutateType(Instruction *Inst,
Type *NewTy);
3600 Value *createTrunc(Instruction *Opnd,
Type *Ty);
3612 SetOfInstrs &RemovedInsts;
3617void TypePromotionTransaction::setOperand(Instruction *Inst,
unsigned Idx,
3619 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3620 Inst, Idx, NewVal));
3623void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3626 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3627 Inst, RemovedInsts, NewVal));
3630void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3633 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3636void TypePromotionTransaction::mutateType(Instruction *Inst,
Type *NewTy) {
3638 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3641Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
Type *Ty) {
3642 std::unique_ptr<TruncBuilder> Ptr(
new TruncBuilder(Opnd, Ty));
3643 Value *Val = Ptr->getBuiltValue();
3644 Actions.push_back(std::move(Ptr));
3648Value *TypePromotionTransaction::createSExt(Instruction *Inst,
Value *Opnd,
3650 std::unique_ptr<SExtBuilder> Ptr(
new SExtBuilder(Inst, Opnd, Ty));
3651 Value *Val = Ptr->getBuiltValue();
3652 Actions.push_back(std::move(Ptr));
3656Value *TypePromotionTransaction::createZExt(Instruction *Inst,
Value *Opnd,
3658 std::unique_ptr<ZExtBuilder> Ptr(
new ZExtBuilder(Inst, Opnd, Ty));
3659 Value *Val = Ptr->getBuiltValue();
3660 Actions.push_back(std::move(Ptr));
3664TypePromotionTransaction::ConstRestorationPt
3665TypePromotionTransaction::getRestorationPoint()
const {
3666 return !Actions.empty() ? Actions.back().get() :
nullptr;
3669bool TypePromotionTransaction::commit() {
3670 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3677void TypePromotionTransaction::rollback(
3678 TypePromotionTransaction::ConstRestorationPt Point) {
3679 while (!Actions.empty() && Point != Actions.back().get()) {
3680 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3690class AddressingModeMatcher {
3691 SmallVectorImpl<Instruction *> &AddrModeInsts;
3692 const TargetLowering &
TLI;
3693 const TargetRegisterInfo &
TRI;
3694 const DataLayout &
DL;
3696 const std::function<
const DominatorTree &()> getDTFn;
3709 const SetOfInstrs &InsertedInsts;
3712 InstrToOrigTy &PromotedInsts;
3715 TypePromotionTransaction &TPT;
3718 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3722 bool IgnoreProfitability;
3725 bool OptSize =
false;
3727 ProfileSummaryInfo *PSI;
3728 BlockFrequencyInfo *BFI;
3729 const CodeGenOptions &Opts;
3731 AddressingModeMatcher(
3732 SmallVectorImpl<Instruction *> &AMI,
const TargetLowering &
TLI,
3733 const TargetRegisterInfo &
TRI,
const LoopInfo &LI,
3734 const std::function<
const DominatorTree &()> getDTFn,
Type *AT,
3735 unsigned AS, Instruction *
MI, ExtAddrMode &AM,
3736 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3737 TypePromotionTransaction &TPT,
3738 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3739 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3740 const CodeGenOptions &Opts)
3742 getDTFn(getDTFn), AccessTy(AT), AddrSpace(AS), MemoryInst(
MI),
3743 AddrMode(AM), InsertedInsts(InsertedInsts),
3744 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP),
3745 OptSize(OptSize), PSI(PSI), BFI(BFI), Opts(Opts) {
3746 IgnoreProfitability =
false;
3758 Match(
Value *
V,
Type *AccessTy,
unsigned AS, Instruction *MemoryInst,
3759 SmallVectorImpl<Instruction *> &AddrModeInsts,
3760 const TargetLowering &
TLI,
const LoopInfo &LI,
3761 const std::function<
const DominatorTree &()> getDTFn,
3762 const TargetRegisterInfo &
TRI,
const SetOfInstrs &InsertedInsts,
3763 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3764 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3765 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3766 const CodeGenOptions &Opts) {
3769 bool Success = AddressingModeMatcher(
3770 AddrModeInsts,
TLI,
TRI, LI, getDTFn, AccessTy, AS,
3771 MemoryInst, Result, InsertedInsts, PromotedInsts, TPT,
3772 LargeOffsetGEP, OptSize, PSI, BFI, Opts)
3780 bool matchScaledValue(
Value *ScaleReg, int64_t Scale,
unsigned Depth);
3782 bool matchOperationAddr(User *AddrInst,
unsigned Opcode,
unsigned Depth,
3783 bool *MovedAway =
nullptr);
3784 bool isProfitableToFoldIntoAddressingMode(Instruction *
I,
3785 ExtAddrMode &AMBefore,
3786 ExtAddrMode &AMAfter);
3787 bool valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
Value *KnownLive2);
3788 bool isPromotionProfitable(
unsigned NewCost,
unsigned OldCost,
3789 Value *PromotedOperand)
const;
3795class PhiNodeSetIterator {
3796 PhiNodeSet *
const Set;
3797 size_t CurrentIndex = 0;
3802 PhiNodeSetIterator(PhiNodeSet *
const Set,
size_t Start);
3804 PhiNodeSetIterator &operator++();
3820 friend class PhiNodeSetIterator;
3822 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3823 using iterator = PhiNodeSetIterator;
3838 size_t FirstValidElement = 0;
3844 bool insert(PHINode *Ptr) {
3845 if (NodeMap.insert(std::make_pair(Ptr,
NodeList.
size())).second) {
3855 bool erase(PHINode *Ptr) {
3856 if (NodeMap.erase(Ptr)) {
3857 SkipRemovedElements(FirstValidElement);
3867 FirstValidElement = 0;
3873 if (FirstValidElement == 0)
3874 SkipRemovedElements(FirstValidElement);
3875 return PhiNodeSetIterator(
this, FirstValidElement);
3882 size_t size()
const {
return NodeMap.size(); }
3885 size_t count(PHINode *Ptr)
const {
return NodeMap.count(Ptr); }
3893 void SkipRemovedElements(
size_t &CurrentIndex) {
3895 auto it = NodeMap.find(NodeList[CurrentIndex]);
3898 if (it != NodeMap.end() && it->second == CurrentIndex)
3905PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *
const Set,
size_t Start)
3908PHINode *PhiNodeSetIterator::operator*()
const {
3910 "PhiNodeSet access out of range");
3911 return Set->NodeList[CurrentIndex];
3914PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3916 "PhiNodeSet access out of range");
3918 Set->SkipRemovedElements(CurrentIndex);
3922bool PhiNodeSetIterator::operator==(
const PhiNodeSetIterator &
RHS)
const {
3923 return CurrentIndex ==
RHS.CurrentIndex;
3926bool PhiNodeSetIterator::operator!=(
const PhiNodeSetIterator &
RHS)
const {
3927 return !((*this) ==
RHS);
3933class SimplificationTracker {
3934 DenseMap<Value *, Value *> Storage;
3937 PhiNodeSet AllPhiNodes;
3939 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3945 if (SV == Storage.
end())
3953 void ReplacePhi(PHINode *From, PHINode *To) {
3954 Value *OldReplacement = Get(From);
3955 while (OldReplacement != From) {
3958 OldReplacement = Get(From);
3960 assert(To && Get(To) == To &&
"Replacement PHI node is already replaced.");
3963 AllPhiNodes.erase(From);
3967 PhiNodeSet &newPhiNodes() {
return AllPhiNodes; }
3969 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3971 void insertNewSelect(SelectInst *SI) { AllSelectNodes.
insert(SI); }
3973 unsigned countNewPhiNodes()
const {
return AllPhiNodes.size(); }
3975 unsigned countNewSelectNodes()
const {
return AllSelectNodes.
size(); }
3977 void destroyNewNodes(
Type *CommonType) {
3980 for (
auto *
I : AllPhiNodes) {
3981 I->replaceAllUsesWith(Dummy);
3982 I->eraseFromParent();
3984 AllPhiNodes.clear();
3985 for (
auto *
I : AllSelectNodes) {
3986 I->replaceAllUsesWith(Dummy);
3987 I->eraseFromParent();
3989 AllSelectNodes.clear();
3994class AddressingModeCombiner {
3995 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3996 typedef std::pair<PHINode *, PHINode *> PHIPair;
4003 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4006 bool AllAddrModesTrivial =
true;
4009 Type *CommonType =
nullptr;
4011 const DataLayout &
DL;
4012 const CodeGenOptions &Opts;
4018 Value *CommonValue =
nullptr;
4021 AddressingModeCombiner(
const DataLayout &
DL,
const CodeGenOptions &Opts,
4022 Value *OriginalValue)
4023 :
DL(
DL), Opts(Opts), Original(OriginalValue) {}
4025 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4028 const ExtAddrMode &
getAddrMode()
const {
return AddrModes[0]; }
4033 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4037 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4040 if (AddrModes.
empty()) {
4048 ExtAddrMode::FieldName ThisDifferentField =
4049 AddrModes[0].compare(NewAddrMode);
4050 if (DifferentField == ExtAddrMode::NoField)
4051 DifferentField = ThisDifferentField;
4052 else if (DifferentField != ThisDifferentField)
4053 DifferentField = ExtAddrMode::MultipleFields;
4056 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4059 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4064 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4069 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4070 !NewAddrMode.HasBaseReg);
4087 bool combineAddrModes() {
4089 if (AddrModes.
size() == 0)
4093 if (AddrModes.
size() == 1 || DifferentField == ExtAddrMode::NoField)
4098 if (AllAddrModesTrivial)
4101 if (!addrModeCombiningAllowed())
4107 FoldAddrToValueMapping
Map;
4108 if (!initializeMap(Map))
4111 CommonValue = findCommon(Map);
4113 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4114 return CommonValue !=
nullptr;
4120 void eraseCommonValueIfDead() {
4121 if (CommonValue && CommonValue->
use_empty())
4123 CommonInst->eraseFromParent();
4131 bool initializeMap(FoldAddrToValueMapping &Map) {
4134 SmallVector<Value *, 2> NullValue;
4136 for (
auto &AM : AddrModes) {
4140 if (CommonType && CommonType !=
Type)
4143 Map[AM.OriginalValue] = DV;
4148 assert(CommonType &&
"At least one non-null value must be!");
4149 for (
auto *
V : NullValue)
4177 Value *findCommon(FoldAddrToValueMapping &Map) {
4185 SimplificationTracker
ST;
4190 InsertPlaceholders(Map, TraverseOrder, ST);
4193 FillPlaceholders(Map, TraverseOrder, ST);
4195 if (!Opts.cgp_addr_sink_new_select &&
ST.countNewSelectNodes() > 0) {
4196 ST.destroyNewNodes(CommonType);
4201 unsigned PhiNotMatchedCount = 0;
4202 if (!MatchPhiSet(ST, Opts.cgp_addr_sink_new_phis, PhiNotMatchedCount)) {
4203 ST.destroyNewNodes(CommonType);
4207 auto *
Result =
ST.Get(
Map.find(Original)->second);
4209 NumMemoryInstsPhiCreated +=
ST.countNewPhiNodes() + PhiNotMatchedCount;
4210 NumMemoryInstsSelectCreated +=
ST.countNewSelectNodes();
4217 bool MatchPhiNode(PHINode *
PHI, PHINode *Candidate,
4218 SmallSetVector<PHIPair, 8> &Matcher,
4219 PhiNodeSet &PhiNodesToMatch) {
4222 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4225 SmallSet<PHIPair, 8> Visited;
4226 while (!WorkList.
empty()) {
4228 if (!Visited.
insert(Item).second)
4235 for (
auto *
B : Item.first->blocks()) {
4236 Value *FirstValue = Item.first->getIncomingValueForBlock(
B);
4237 Value *SecondValue = Item.second->getIncomingValueForBlock(
B);
4238 if (FirstValue == SecondValue)
4248 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4253 if (Matcher.
count({FirstPhi, SecondPhi}))
4258 if (MatchedPHIs.
insert(FirstPhi).second)
4259 Matcher.
insert({FirstPhi, SecondPhi});
4261 WorkList.
push_back({FirstPhi, SecondPhi});
4270 bool MatchPhiSet(SimplificationTracker &ST,
bool AllowNewPhiNodes,
4271 unsigned &PhiNotMatchedCount) {
4275 SmallSetVector<PHIPair, 8> Matched;
4276 SmallPtrSet<PHINode *, 8> WillNotMatch;
4277 PhiNodeSet &PhiNodesToMatch =
ST.newPhiNodes();
4278 while (PhiNodesToMatch.size()) {
4279 PHINode *
PHI = *PhiNodesToMatch.begin();
4282 WillNotMatch.
clear();
4286 bool IsMatched =
false;
4287 for (
auto &
P :
PHI->getParent()->phis()) {
4289 if (PhiNodesToMatch.count(&
P))
4291 if ((IsMatched = MatchPhiNode(
PHI, &
P, Matched, PhiNodesToMatch)))
4301 for (
auto MV : Matched)
4302 ST.ReplacePhi(MV.first, MV.second);
4307 if (!AllowNewPhiNodes)
4310 PhiNotMatchedCount += WillNotMatch.
size();
4311 for (
auto *
P : WillNotMatch)
4312 PhiNodesToMatch.erase(
P);
4317 void FillPlaceholders(FoldAddrToValueMapping &Map,
4318 SmallVectorImpl<Value *> &TraverseOrder,
4319 SimplificationTracker &ST) {
4320 while (!TraverseOrder.
empty()) {
4322 assert(
Map.contains(Current) &&
"No node to fill!!!");
4328 auto *TrueValue = CurrentSelect->getTrueValue();
4329 assert(
Map.contains(TrueValue) &&
"No True Value!");
4330 Select->setTrueValue(
ST.Get(Map[TrueValue]));
4331 auto *FalseValue = CurrentSelect->getFalseValue();
4332 assert(
Map.contains(FalseValue) &&
"No False Value!");
4333 Select->setFalseValue(
ST.Get(Map[FalseValue]));
4340 assert(
Map.contains(PV) &&
"No predecessor Value!");
4341 PHI->addIncoming(
ST.Get(Map[PV]),
B);
4352 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4353 SmallVectorImpl<Value *> &TraverseOrder,
4354 SimplificationTracker &ST) {
4357 "Address must be a Phi or Select node");
4360 while (!Worklist.
empty()) {
4363 if (
Map.contains(Current))
4374 CurrentSelect->getName(),
4375 CurrentSelect->getIterator(), CurrentSelect);
4379 Worklist.
push_back(CurrentSelect->getTrueValue());
4380 Worklist.
push_back(CurrentSelect->getFalseValue());
4388 ST.insertNewPhi(
PHI);
4394 bool addrModeCombiningAllowed() {
4395 if (!Opts.cgp_complex_addr_modes)
4397 switch (DifferentField) {
4400 case ExtAddrMode::BaseRegField:
4401 return Opts.cgp_addr_sink_combine_base_reg;
4402 case ExtAddrMode::BaseGVField:
4403 return Opts.cgp_addr_sink_combine_base_gv;
4404 case ExtAddrMode::BaseOffsField:
4405 return Opts.cgp_addr_sink_combine_base_offs;
4406 case ExtAddrMode::ScaledRegField:
4407 return Opts.cgp_addr_sink_combine_scaled_reg;
4416bool AddressingModeMatcher::matchScaledValue(
Value *ScaleReg, int64_t Scale,
4421 return matchAddr(ScaleReg,
Depth);
4432 ExtAddrMode TestAddrMode =
AddrMode;
4436 TestAddrMode.
Scale += Scale;
4450 ConstantInt *CI =
nullptr;
4451 Value *AddLHS =
nullptr;
4455 TestAddrMode.InBounds =
false;
4472 auto GetConstantStep =
4473 [
this](
const Value *
V) -> std::optional<std::pair<Instruction *, APInt>> {
4476 return std::nullopt;
4479 return std::nullopt;
4487 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4488 return std::nullopt;
4490 return std::make_pair(IVInc->first, ConstantStep->getValue());
4491 return std::nullopt;
4506 if (
auto IVStep = GetConstantStep(ScaleReg)) {
4513 APInt Step = IVStep->second;
4515 if (
Offset.isSignedIntN(64)) {
4516 TestAddrMode.InBounds =
false;
4518 TestAddrMode.BaseOffs -=
Offset.getLimitedValue();
4523 getDTFn().
dominates(IVInc, MemoryInst)) {
4543 switch (
I->getOpcode()) {
4544 case Instruction::BitCast:
4545 case Instruction::AddrSpaceCast:
4547 if (
I->getType() ==
I->getOperand(0)->getType())
4549 return I->getType()->isIntOrPtrTy();
4550 case Instruction::PtrToInt:
4553 case Instruction::IntToPtr:
4556 case Instruction::Add:
4558 case Instruction::Or:
4560 case Instruction::Mul:
4561 case Instruction::Shl:
4564 case Instruction::GetElementPtr:
4580 int ISDOpcode =
TLI.InstructionOpcodeToISD(PromotedInst->
getOpcode());
4585 return TLI.isOperationLegalOrCustom(
4586 ISDOpcode,
TLI.getValueType(
DL, PromotedInst->
getType()));
4592class TypePromotionHelper {
4595 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4596 Instruction *ExtOpnd,
bool IsSExt) {
4597 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4598 auto [It,
Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4602 if (It->second.getInt() == ExtTy)
4608 ExtTy = BothExtension;
4610 It->second = TypeIsSExt(ExtOpnd->
getType(), ExtTy);
4617 static const Type *getOrigType(
const InstrToOrigTy &PromotedInsts,
4618 Instruction *Opnd,
bool IsSExt) {
4619 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4620 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4621 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4622 return It->second.getPointer();
4637 static bool canGetThrough(
const Instruction *Inst,
Type *ConsideredExtType,
4638 const InstrToOrigTy &PromotedInsts,
bool IsSExt);
4642 static bool shouldExtOperand(
const Instruction *Inst,
int OpIdx) {
4655 static Value *promoteOperandForTruncAndAnyExt(
4656 Instruction *Ext, TypePromotionTransaction &TPT,
4657 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4658 SmallVectorImpl<Instruction *> *Exts,
4659 SmallVectorImpl<Instruction *> *Truncs,
const TargetLowering &
TLI);
4670 static Value *promoteOperandForOther(Instruction *Ext,
4671 TypePromotionTransaction &TPT,
4672 InstrToOrigTy &PromotedInsts,
4673 unsigned &CreatedInstsCost,
4674 SmallVectorImpl<Instruction *> *Exts,
4675 SmallVectorImpl<Instruction *> *Truncs,
4676 const TargetLowering &
TLI,
bool IsSExt);
4679 static Value *signExtendOperandForOther(
4680 Instruction *Ext, TypePromotionTransaction &TPT,
4681 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4682 SmallVectorImpl<Instruction *> *Exts,
4683 SmallVectorImpl<Instruction *> *Truncs,
const TargetLowering &
TLI) {
4684 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4685 Exts, Truncs,
TLI,
true);
4689 static Value *zeroExtendOperandForOther(
4690 Instruction *Ext, TypePromotionTransaction &TPT,
4691 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4692 SmallVectorImpl<Instruction *> *Exts,
4693 SmallVectorImpl<Instruction *> *Truncs,
const TargetLowering &
TLI) {
4694 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4695 Exts, Truncs,
TLI,
false);
4700 using Action =
Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4701 InstrToOrigTy &PromotedInsts,
4702 unsigned &CreatedInstsCost,
4703 SmallVectorImpl<Instruction *> *Exts,
4704 SmallVectorImpl<Instruction *> *Truncs,
4705 const TargetLowering &
TLI);
4716 static Action getAction(Instruction *Ext,
const SetOfInstrs &InsertedInsts,
4717 const TargetLowering &
TLI,
4718 const InstrToOrigTy &PromotedInsts);
4723bool TypePromotionHelper::canGetThrough(
const Instruction *Inst,
4724 Type *ConsideredExtType,
4725 const InstrToOrigTy &PromotedInsts,
4745 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4746 (IsSExt && BinOp->hasNoSignedWrap())))
4750 if ((Inst->
getOpcode() == Instruction::And ||
4755 if (Inst->
getOpcode() == Instruction::Xor) {
4758 if (!Cst->getValue().isAllOnes())
4767 if (Inst->
getOpcode() == Instruction::LShr && !IsSExt)
4777 if (ExtInst->hasOneUse()) {
4778 const auto *AndInst = *ExtInst->user_begin();
4779 if (AndInst->getOpcode() == Instruction::And) {
4812 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4825TypePromotionHelper::Action TypePromotionHelper::getAction(
4826 Instruction *Ext,
const SetOfInstrs &InsertedInsts,
4827 const TargetLowering &
TLI,
const InstrToOrigTy &PromotedInsts) {
4829 "Unexpected instruction type");
4836 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4849 return promoteOperandForTruncAndAnyExt;
4855 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4858Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4859 Instruction *SExt, TypePromotionTransaction &TPT,
4860 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4861 SmallVectorImpl<Instruction *> *Exts,
4862 SmallVectorImpl<Instruction *> *Truncs,
const TargetLowering &
TLI) {
4866 Value *ExtVal = SExt;
4867 bool HasMergedNonFreeExt =
false;
4874 TPT.replaceAllUsesWith(SExt, ZExt);
4875 TPT.eraseInstruction(SExt);
4880 TPT.setOperand(SExt, 0, SExtOpnd->
getOperand(0));
4882 CreatedInstsCost = 0;
4886 TPT.eraseInstruction(SExtOpnd);
4894 CreatedInstsCost = !
TLI.
isExtFree(ExtInst) && !HasMergedNonFreeExt;
4902 TPT.eraseInstruction(ExtInst, NextVal);
4906Value *TypePromotionHelper::promoteOperandForOther(
4907 Instruction *Ext, TypePromotionTransaction &TPT,
4908 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4909 SmallVectorImpl<Instruction *> *Exts,
4910 SmallVectorImpl<Instruction *> *Truncs,
const TargetLowering &
TLI,
4915 CreatedInstsCost = 0;
4924 ITrunc->moveAfter(ExtOpnd);
4929 TPT.replaceAllUsesWith(ExtOpnd,
Trunc);
4932 TPT.setOperand(Ext, 0, ExtOpnd);
4942 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4944 TPT.mutateType(ExtOpnd, Ext->
getType());
4946 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4949 for (
int OpIdx = 0, EndOpIdx = ExtOpnd->
getNumOperands(); OpIdx != EndOpIdx;
4953 !shouldExtOperand(ExtOpnd, OpIdx)) {
4962 APInt CstVal = IsSExt ? Cst->getValue().sext(
BitWidth)
4964 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->
getType(), CstVal));
4975 Value *ValForExtOpnd = IsSExt
4976 ? TPT.createSExt(ExtOpnd, Opnd, Ext->
getType())
4977 : TPT.createZExt(ExtOpnd, Opnd, Ext->
getType());
4978 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4980 if (!InstForExtOpnd)
4989 TPT.eraseInstruction(Ext);
5001bool AddressingModeMatcher::isPromotionProfitable(
5002 unsigned NewCost,
unsigned OldCost,
Value *PromotedOperand)
const {
5003 LLVM_DEBUG(
dbgs() <<
"OldCost: " << OldCost <<
"\tNewCost: " << NewCost
5008 if (NewCost > OldCost)
5010 if (NewCost < OldCost)
5029bool AddressingModeMatcher::matchOperationAddr(User *AddrInst,
unsigned Opcode,
5041 case Instruction::PtrToInt:
5044 case Instruction::IntToPtr: {
5052 case Instruction::BitCast:
5062 case Instruction::AddrSpaceCast: {
5070 case Instruction::Or:
5074 case Instruction::Add: {
5077 ExtAddrMode BackupAddrMode =
AddrMode;
5078 unsigned OldSize = AddrModeInsts.
size();
5083 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5084 TPT.getRestorationPoint();
5088 int First = 0, Second = 1;
5099 AddrModeInsts.
resize(OldSize);
5100 TPT.rollback(LastKnownGood);
5110 AddrModeInsts.
resize(OldSize);
5111 TPT.rollback(LastKnownGood);
5114 case Instruction::Mul:
5115 case Instruction::Shl: {
5119 if (!
RHS ||
RHS->getBitWidth() > 64)
5121 int64_t Scale = Opcode == Instruction::Shl
5122 ? 1LL <<
RHS->getLimitedValue(
RHS->getBitWidth() - 1)
5123 :
RHS->getSExtValue();
5127 case Instruction::GetElementPtr: {
5130 int VariableOperand = -1;
5131 unsigned VariableScale = 0;
5133 int64_t ConstantOffset = 0;
5135 for (
unsigned i = 1, e = AddrInst->
getNumOperands(); i != e; ++i, ++GTI) {
5137 const StructLayout *SL =
DL.getStructLayout(STy);
5148 if (ConstantInt *CI =
5150 const APInt &CVal = CI->
getValue();
5157 if (VariableOperand != -1)
5161 VariableOperand = i;
5162 VariableScale = TypeSize;
5169 if (VariableOperand == -1) {
5170 AddrMode.BaseOffs += ConstantOffset;
5176 AddrMode.BaseOffs -= ConstantOffset;
5180 ConstantOffset != 0) {
5194 BaseI ? BaseI->getParent() : &
GEP->getFunction()->getEntryBlock();
5196 LargeOffsetGEP = std::make_pair(
GEP, ConstantOffset);
5204 ExtAddrMode BackupAddrMode =
AddrMode;
5205 unsigned OldSize = AddrModeInsts.
size();
5208 AddrMode.BaseOffs += ConstantOffset;
5217 AddrModeInsts.
resize(OldSize);
5225 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand), VariableScale,
5230 AddrModeInsts.
resize(OldSize);
5235 AddrMode.BaseOffs += ConstantOffset;
5236 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand),
5237 VariableScale,
Depth)) {
5240 AddrModeInsts.
resize(OldSize);
5247 case Instruction::SExt:
5248 case Instruction::ZExt: {
5255 TypePromotionHelper::Action TPH =
5256 TypePromotionHelper::getAction(Ext, InsertedInsts,
TLI, PromotedInsts);
5260 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5261 TPT.getRestorationPoint();
5262 unsigned CreatedInstsCost = 0;
5264 Value *PromotedOperand =
5265 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost,
nullptr,
nullptr,
TLI);
5280 assert(PromotedOperand &&
5281 "TypePromotionHelper should have filtered out those cases");
5283 ExtAddrMode BackupAddrMode =
AddrMode;
5284 unsigned OldSize = AddrModeInsts.
size();
5286 if (!matchAddr(PromotedOperand,
Depth) ||
5291 !isPromotionProfitable(CreatedInstsCost,
5292 ExtCost + (AddrModeInsts.
size() - OldSize),
5295 AddrModeInsts.
resize(OldSize);
5296 LLVM_DEBUG(
dbgs() <<
"Sign extension does not pay off: rollback\n");
5297 TPT.rollback(LastKnownGood);
5302 AddrMode.replaceWith(Ext, PromotedOperand);
5305 case Instruction::Call:
5307 if (
II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5323bool AddressingModeMatcher::matchAddr(
Value *Addr,
unsigned Depth) {
5326 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5327 TPT.getRestorationPoint();
5351 ExtAddrMode BackupAddrMode =
AddrMode;
5352 unsigned OldSize = AddrModeInsts.
size();
5355 bool MovedAway =
false;
5356 if (matchOperationAddr(
I,
I->getOpcode(),
Depth, &MovedAway)) {
5364 if (
I->hasOneUse() ||
5365 isProfitableToFoldIntoAddressingMode(
I, BackupAddrMode,
AddrMode)) {
5372 AddrModeInsts.
resize(OldSize);
5373 TPT.rollback(LastKnownGood);
5376 if (matchOperationAddr(CE,
CE->getOpcode(),
Depth))
5378 TPT.rollback(LastKnownGood);
5405 TPT.rollback(LastKnownGood);
5416 TLI.ParseConstraints(
F->getDataLayout(), &
TRI, *CI);
5420 TLI.ComputeConstraintToUse(OpInfo,
SDValue());
5424 if (OpInfo.CallOperandVal == OpVal &&
5426 !OpInfo.isIndirect))
5442 if (!ConsideredInsts.
insert(
I).second)
5450 for (
Use &U :
I->uses()) {
5453 if (SeenInsts++ >= MaxUsersToScan)
5458 MemoryUses.push_back({&U, LI->getType()});
5465 MemoryUses.push_back({&U,
SI->getValueOperand()->getType()});
5472 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5479 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5486 if (!
TLI.getAddrModeArguments(
II, PtrOps, AccessTy))
5489 if (!
find(PtrOps, U.get()))
5492 MemoryUses.push_back({&U, AccessTy});
5497 if (CI->hasFnAttr(Attribute::Cold)) {
5515 PSI, BFI, SeenInsts, MaxUsersToScan))
5526 unsigned SeenInsts = 0;
5529 PSI, BFI, SeenInsts, MaxUsersToScan);
5536bool AddressingModeMatcher::valueAlreadyLiveAtInst(
Value *Val,
5538 Value *KnownLive2) {
5540 if (Val ==
nullptr || Val == KnownLive1 || Val == KnownLive2)
5581bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5582 Instruction *
I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5583 if (IgnoreProfitability)
5601 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.
BaseReg, AMBefore.
ScaledReg))
5602 ScaledReg =
nullptr;
5606 if (!BaseReg && !ScaledReg)
5615 Opts.cgp_max_address_users_to_scan))
5628 for (
const std::pair<Use *, Type *> &Pair : MemoryUses) {
5631 Type *AddressAccessTy = Pair.second;
5632 unsigned AS =
Address->getType()->getPointerAddressSpace();
5638 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
5640 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5641 TPT.getRestorationPoint();
5642 AddressingModeMatcher Matcher(MatchedAddrModeInsts,
TLI,
TRI, LI, getDTFn,
5643 AddressAccessTy, AS, UserI, Result,
5644 InsertedInsts, PromotedInsts, TPT,
5645 LargeOffsetGEP, OptSize, PSI, BFI, Opts);
5646 Matcher.IgnoreProfitability =
true;
5654 TPT.rollback(LastKnownGood);
5660 MatchedAddrModeInsts.
clear();
5670 return I->getParent() != BB;
5686 return std::next(AddrInst->getIterator());
5697 Earliest = UserInst;
5722bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst,
Value *Addr,
5723 Type *AccessTy,
unsigned AddrSpace) {
5728 SmallVector<Value *, 8> worklist;
5729 SmallPtrSet<Value *, 16> Visited;
5735 bool PhiOrSelectSeen =
false;
5736 SmallVector<Instruction *, 16> AddrModeInsts;
5737 AddressingModeCombiner AddrModes(*
DL, Opts, Addr);
5738 TypePromotionTransaction TPT(RemovedInsts);
5739 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5740 TPT.getRestorationPoint();
5741 while (!worklist.
empty()) {
5753 if (!Visited.
insert(
V).second)
5759 PhiOrSelectSeen =
true;
5766 PhiOrSelectSeen =
true;
5773 AddrModeInsts.
clear();
5774 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
5779 auto getDTFn = [
this]() ->
const DominatorTree & {
return getDT(); };
5780 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5781 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *
TLI, *LI, getDTFn,
5782 *
TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5785 GetElementPtrInst *
GEP = LargeOffsetGEP.first;
5790 LargeOffsetGEPMap[
GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5791 LargeOffsetGEPID.
insert(std::make_pair(
GEP, LargeOffsetGEPID.
size()));
5794 NewAddrMode.OriginalValue =
V;
5795 if (!AddrModes.addNewAddrMode(NewAddrMode))
5802 if (!AddrModes.combineAddrModes()) {
5803 TPT.rollback(LastKnownGood);
5809 ExtAddrMode
AddrMode = AddrModes.getAddrMode();
5815 if (!PhiOrSelectSeen &&
none_of(AddrModeInsts, [&](
Value *
V) {
5829 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5852 <<
" for " << *MemoryInst <<
"\n");
5856 !
DL->isNonIntegralPointerType(Addr->
getType())) {
5862 SunkAddr = Builder.CreatePtrToInt(SunkAddr,
IntPtrTy,
"sunkaddr");
5864 Builder.CreateIntToPtr(SunkAddr, Addr->
getType(),
"sunkaddr");
5866 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->
getType());
5870 <<
" for " << *MemoryInst <<
"\n");
5871 Value *ResultPtr =
nullptr, *ResultIndex =
nullptr;
5882 if (ResultPtr ||
AddrMode.Scale != 1)
5903 GlobalValue *BaseGV =
AddrMode.BaseGV;
5904 if (BaseGV !=
nullptr) {
5909 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
5918 if (!
DL->isNonIntegralPointerType(Addr->
getType())) {
5919 if (!ResultPtr &&
AddrMode.BaseReg) {
5923 }
else if (!ResultPtr &&
AddrMode.Scale == 1) {
5924 ResultPtr = Builder.CreateIntToPtr(
AddrMode.ScaledReg, Addr->
getType(),
5933 }
else if (!ResultPtr) {
5946 if (
V->getType() != IdxTy)
5947 V = Builder.CreateIntCast(
V, IdxTy,
true,
"sunkaddr");
5955 if (
V->getType() == IdxTy) {
5960 "We can't transform if ScaledReg is too narrow");
5961 V = Builder.CreateTrunc(
V, IdxTy,
"sunkaddr");
5965 V = Builder.CreateMul(
5968 ResultIndex = Builder.CreateAdd(ResultIndex,
V,
"sunkaddr");
5979 if (ResultPtr->
getType() != I8PtrTy)
5980 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5981 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex,
"sunkaddr",
5994 if (PtrInst && PtrInst->getParent() != MemoryInst->
getParent())
5996 SunkAddr = ResultPtr;
5998 if (ResultPtr->
getType() != I8PtrTy)
5999 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6000 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex,
"sunkaddr",
6007 !
DL->isNonIntegralPointerType(Addr->
getType())) {
6013 SunkAddr = Builder.CreatePtrToInt(SunkAddr,
IntPtrTy,
"sunkaddr");
6015 Builder.CreateIntToPtr(SunkAddr, Addr->
getType(),
"sunkaddr");
6017 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->
getType());
6025 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6030 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6031 RecursivelyDeleteTriviallyDeadInstructions(
6032 Repl, TLInfo, nullptr,
6033 [&](Value *V) { removeAllAssertingVHReferences(V); });
6063bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6071 if (SunkAddr && SunkAddr->getParent() == BB &&
6072 SunkAddr->comesBefore(MemoryInst)) {
6076 if (!
GEP->hasIndices())
6079 bool SinkGEP =
GEP->getParent() != BB;
6081 SmallVector<Value *, 2>
Ops(
GEP->operands());
6082 Type *SourceTy =
GEP->getSourceElementType();
6084 Type *OffsetTy =
nullptr;
6087 bool RewriteGEP = SinkGEP;
6094 if (!BaseGEP || !BaseGEP->hasIndices())
6096 Value *
Base = BaseGEP->getPointerOperand();
6097 if (
Base->getType()->isVectorTy())
6102 if (
Idx->getType()->isVectorTy())
6108 OffsetTy = SourceTy;
6109 SourceTy = BaseGEP->getSourceElementType();
6110 Ops.assign(BaseGEP->op_begin(), BaseGEP->op_end());
6116 unsigned FinalIndex =
Ops.size() - 1;
6121 for (
unsigned i = 1; i < FinalIndex; ++i) {
6126 C =
C->getSplatValue();
6128 if (!CI || !CI->
isZero())
6135 if (
Ops[FinalIndex]->
getType()->isVectorTy()) {
6139 if (!
C || !
C->isZero()) {
6140 Ops[FinalIndex] =
V;
6148 if (!RewriteGEP &&
Ops.size() == 2)
6154 Builder.disableGEPCanonicalization();
6157 Ops[0] = Builder.CreateGEP(OffsetTy,
Ops[0], OffsetIdxs);
6159 Type *ScalarIndexTy =
DL->getIndexType(
Ops[0]->
getType()->getScalarType());
6163 if (!
Ops[FinalIndex]->
getType()->isVectorTy()) {
6164 NewAddr = Builder.CreateGEP(SourceTy,
Ops[0],
ArrayRef(
Ops).drop_front());
6165 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6175 if (
Ops.size() != 2) {
6185 NewAddr = Builder.CreateGEP(SourceTy,
Base, Index);
6189 SunkAddrs[Ptr] = WeakTrackingVH(NewAddr);
6200 Builder.disableGEPCanonicalization();
6203 Type *ScalarIndexTy =
DL->getIndexType(
V->getType()->getScalarType());
6204 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6207 Intrinsic::masked_gather) {
6211 Intrinsic::masked_scatter);
6226 Ptr, TLInfo,
nullptr,
6227 [&](
Value *
V) { removeAllAssertingVHReferences(
V); });
6238 if (
I->hasNUsesOrMore(3))
6241 for (
User *U :
I->users()) {
6243 if (!Extract || Extract->getNumIndices() != 1)
6246 unsigned Index = Extract->getIndices()[0];
6248 MulExtract = Extract;
6249 else if (Index == 1)
6250 OverflowExtract = Extract;
6277bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *
I,
bool IsSigned,
6278 ModifyDT &ModifiedDT) {
6285 ExtractValueInst *MulExtract =
nullptr, *OverflowExtract =
nullptr;
6290 InsertedInsts.insert(
I);
6301 OverflowEntryBB->
takeName(
I->getParent());
6307 NoOverflowBB->
moveAfter(OverflowEntryBB);
6315 Value *LoLHS = Builder.CreateTrunc(
LHS, LegalTy,
"lo.lhs");
6316 Value *HiLHS = Builder.CreateLShr(
LHS, VTHalfBitWidth,
"lhs.lsr");
6317 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy,
"hi.lhs");
6320 Value *LoRHS = Builder.CreateTrunc(
RHS, LegalTy,
"lo.rhs");
6321 Value *HiRHS = Builder.CreateLShr(
RHS, VTHalfBitWidth,
"rhs.lsr");
6322 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy,
"hi.rhs");
6324 Value *IsAnyBitTrue;
6327 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1,
"sign.lo.lhs");
6329 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1,
"sign.lo.rhs");
6330 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6331 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6332 Value *
Or = Builder.CreateOr(XorLHS, XorRHS,
"or.lhs.rhs");
6333 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE,
Or,
6334 ConstantInt::getNullValue(
Or->getType()));
6336 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6337 ConstantInt::getNullValue(LegalTy));
6338 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6339 ConstantInt::getNullValue(LegalTy));
6340 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS,
"or.lhs.rhs");
6342 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6345 Builder.SetInsertPoint(NoOverflowBB);
6346 Value *ExtLoLHS, *ExtLoRHS;
6348 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty,
"lo.lhs.ext");
6349 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty,
"lo.rhs.ext");
6351 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty,
"lo.lhs.ext");
6352 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty,
"lo.rhs.ext");
6355 Value *
Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS,
"mul.overflow.no");
6360 OverflowResBB->
setName(
"overflow.res");
6363 Builder.CreateBr(OverflowResBB);
6371 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6373 Builder.CreatePHI(IntegerType::getInt1Ty(
I->getContext()), 2);
6385 if (OverflowExtract) {
6386 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6387 OverflowExtract->eraseFromParent();
6392 I->removeFromParent();
6394 I->insertInto(OverflowBB, OverflowBB->
end());
6395 Builder.SetInsertPoint(OverflowBB->
end());
6397 Value *OverflowFlag = Builder.CreateExtractValue(
I, {1},
"overflow.flag");
6398 Builder.CreateBr(OverflowResBB);
6402 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6404 DTU->
applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6405 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6406 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6407 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6408 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6410 ModifiedDT = ModifyDT::ModifyBBDT;
6416bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6417 bool MadeChange =
false;
6419 const TargetRegisterInfo *
TRI =
6424 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6430 OpInfo.isIndirect) {
6432 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->
getType(), ~0u);
6481 if (!
TLI.isZExtFree(NarrowTy, LargeTy))
6495bool CodeGenPrepare::tryToPromoteExts(
6496 TypePromotionTransaction &TPT,
const SmallVectorImpl<Instruction *> &Exts,
6497 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6498 unsigned CreatedInstsCost) {
6499 bool Promoted =
false;
6502 for (
auto *
I : Exts) {
6517 TypePromotionHelper::Action TPH =
6518 TypePromotionHelper::getAction(
I, InsertedInsts, *
TLI, PromotedInsts);
6527 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6528 TPT.getRestorationPoint();
6529 SmallVector<Instruction *, 4> NewExts;
6530 unsigned NewCreatedInstsCost = 0;
6533 Value *PromotedVal = TPH(
I, TPT, PromotedInsts, NewCreatedInstsCost,
6534 &NewExts,
nullptr, *
TLI);
6536 "TypePromotionHelper should have filtered out those cases");
6546 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6549 TotalCreatedInstsCost =
6550 std::max((
long long)0, (TotalCreatedInstsCost - ExtCost));
6551 if (!Opts.cgp_stress_ext_ld_promotion &&
6552 (TotalCreatedInstsCost > 1 ||
6554 (ExtCost == 0 && NewExts.
size() > 1))) {
6558 TPT.rollback(LastKnownGood);
6563 SmallVector<Instruction *, 2> NewlyMovedExts;
6564 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6565 bool NewPromoted =
false;
6566 for (
auto *ExtInst : NewlyMovedExts) {
6572 !(Opts.cgp_stress_ext_ld_promotion ||
6573 NewCreatedInstsCost <= ExtCost ||
6577 ProfitablyMovedExts.
push_back(MovedExt);
6584 TPT.rollback(LastKnownGood);
6595bool CodeGenPrepare::mergeSExts(
Function &
F) {
6597 for (
auto &Entry : ValToSExtendedUses) {
6598 SExts &Insts =
Entry.second;
6600 for (Instruction *Inst : Insts) {
6604 bool inserted =
false;
6605 for (
auto &Pt : CurPts) {
6608 RemovedInsts.insert(Pt);
6609 Pt->removeFromParent();
6620 RemovedInsts.insert(Inst);
6627 CurPts.push_back(Inst);
6669bool CodeGenPrepare::splitLargeGEPOffsets() {
6671 for (
auto &Entry : LargeOffsetGEPMap) {
6673 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6674 &LargeOffsetGEPs =
Entry.second;
6675 auto compareGEPOffset =
6676 [&](
const std::pair<GetElementPtrInst *, int64_t> &
LHS,
6677 const std::pair<GetElementPtrInst *, int64_t> &
RHS) {
6678 if (
LHS.first ==
RHS.first)
6680 if (
LHS.second !=
RHS.second)
6681 return LHS.second <
RHS.second;
6682 return LargeOffsetGEPID[
LHS.first] < LargeOffsetGEPID[
RHS.first];
6685 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6688 if (LargeOffsetGEPs.
front().second == LargeOffsetGEPs.
back().second)
6690 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.
begin()->first;
6691 int64_t BaseOffset = LargeOffsetGEPs.
begin()->second;
6692 Value *NewBaseGEP =
nullptr;
6694 auto createNewBase = [&](int64_t BaseOffset,
Value *OldBase,
6695 GetElementPtrInst *
GEP) {
6696 LLVMContext &Ctx =
GEP->getContext();
6697 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
6699 PointerType::get(Ctx,
GEP->getType()->getPointerAddressSpace());
6711 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6714 NewBaseInsertPt = std::next(BaseI->getIterator());
6727 NewBaseGEP = OldBase;
6728 if (NewBaseGEP->
getType() != I8PtrTy)
6729 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6731 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex,
"splitgep");
6732 NewGEPBases.
insert(NewBaseGEP);
6738 LargeOffsetGEPs.
front().second, LargeOffsetGEPs.
back().second)) {
6739 BaseOffset = PreferBase;
6742 createNewBase(BaseOffset, OldBase, BaseGEP);
6745 auto *LargeOffsetGEP = LargeOffsetGEPs.
begin();
6746 while (LargeOffsetGEP != LargeOffsetGEPs.
end()) {
6747 GetElementPtrInst *
GEP = LargeOffsetGEP->first;
6748 int64_t
Offset = LargeOffsetGEP->second;
6749 if (
Offset != BaseOffset) {
6756 GEP->getResultElementType(),
6757 GEP->getAddressSpace())) {
6763 NewBaseGEP =
nullptr;
6768 Type *PtrIdxTy =
DL->getIndexType(
GEP->getType());
6773 createNewBase(BaseOffset, OldBase,
GEP);
6777 Value *NewGEP = NewBaseGEP;
6778 if (
Offset != BaseOffset) {
6781 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6785 LargeOffsetGEP = LargeOffsetGEPs.
erase(LargeOffsetGEP);
6786 GEP->eraseFromParent();
6793bool CodeGenPrepare::optimizePhiType(
6794 PHINode *
I, SmallPtrSetImpl<PHINode *> &Visited,
6795 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6800 Type *PhiTy =
I->getType();
6801 Type *ConvertTy =
nullptr;
6803 (!
I->getType()->isIntegerTy() && !
I->getType()->isFloatingPointTy()))
6806 SmallVector<Instruction *, 4> Worklist;
6808 SmallPtrSet<PHINode *, 4> PhiNodes;
6809 SmallPtrSet<ConstantData *, 4>
Constants;
6812 SmallPtrSet<Instruction *, 4> Defs;
6813 SmallPtrSet<Instruction *, 4>
Uses;
6819 bool AnyAnchored =
false;
6821 while (!Worklist.
empty()) {
6826 for (
Value *
V :
Phi->incoming_values()) {
6828 if (!PhiNodes.
count(OpPhi)) {
6829 if (!Visited.
insert(OpPhi).second)
6835 if (!OpLoad->isSimple())
6837 if (Defs.
insert(OpLoad).second)
6840 if (Defs.
insert(OpEx).second)
6844 ConvertTy = OpBC->getOperand(0)->getType();
6845 if (OpBC->getOperand(0)->getType() != ConvertTy)
6847 if (Defs.
insert(OpBC).second) {
6860 for (User *
V :
II->users()) {
6862 if (!PhiNodes.
count(OpPhi)) {
6863 if (Visited.
count(OpPhi))
6870 if (!OpStore->isSimple() || OpStore->getOperand(0) !=
II)
6872 Uses.insert(OpStore);
6875 ConvertTy = OpBC->getType();
6876 if (OpBC->getType() != ConvertTy)
6880 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
6887 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
6891 LLVM_DEBUG(
dbgs() <<
"Converting " << *
I <<
"\n and connected nodes to "
6892 << *ConvertTy <<
"\n");
6897 for (ConstantData *
C : Constants)
6899 for (Instruction *
D : Defs) {
6901 ValMap[
D] =
D->getOperand(0);
6905 ValMap[
D] =
new BitCastInst(
D, ConvertTy,
D->getName() +
".bc", insertPt);
6908 for (PHINode *Phi : PhiNodes)
6910 Phi->getName() +
".tc",
Phi->getIterator());
6912 for (PHINode *Phi : PhiNodes) {
6914 for (
int i = 0, e =
Phi->getNumIncomingValues(); i < e; i++)
6916 Phi->getIncomingBlock(i));
6920 for (Instruction *U :
Uses) {
6925 U->setOperand(0,
new BitCastInst(ValMap[
U->getOperand(0)], PhiTy,
"bc",
6935bool CodeGenPrepare::optimizePhiTypes(
Function &
F) {
6936 if (!Opts.cgp_optimize_phi_types)
6940 SmallPtrSet<PHINode *, 4> Visited;
6941 SmallPtrSet<Instruction *, 4> DeletedInstrs;
6945 for (
auto &Phi : BB.
phis())
6946 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
6949 for (
auto *
I : DeletedInstrs) {
6951 I->eraseFromParent();
6959bool CodeGenPrepare::canFormExtLd(
6960 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
6961 Instruction *&Inst,
bool HasPromoted) {
6962 for (
auto *MovedExtInst : MovedExts) {
6965 Inst = MovedExtInst;
7017bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7018 bool AllowPromotionWithoutCommonHeader =
false;
7023 *Inst, AllowPromotionWithoutCommonHeader);
7024 TypePromotionTransaction TPT(RemovedInsts);
7025 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7026 TPT.getRestorationPoint();
7028 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7031 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7034 LoadInst *LI =
nullptr;
7039 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7040 assert(LI && ExtFedByLoad &&
"Expect a valid load and extension");
7045 Inst = ExtFedByLoad;
7050 if (ATPConsiderable &&
7051 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7052 HasPromoted, TPT, SpeculativelyMovedExts))
7055 TPT.rollback(LastKnownGood);
7064bool CodeGenPrepare::performAddressTypePromotion(
7065 Instruction *&Inst,
bool AllowPromotionWithoutCommonHeader,
7066 bool HasPromoted, TypePromotionTransaction &TPT,
7067 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7068 bool Promoted =
false;
7069 SmallPtrSet<Instruction *, 1> UnhandledExts;
7070 bool AllSeenFirst =
true;
7071 for (
auto *
I : SpeculativelyMovedExts) {
7072 Value *HeadOfChain =
I->getOperand(0);
7073 auto AlreadySeen = SeenChainsForSExt.
find(HeadOfChain);
7076 if (AlreadySeen != SeenChainsForSExt.
end()) {
7077 if (AlreadySeen->second !=
nullptr)
7078 UnhandledExts.
insert(AlreadySeen->second);
7079 AllSeenFirst =
false;
7083 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7084 SpeculativelyMovedExts.size() == 1)) {
7088 for (
auto *
I : SpeculativelyMovedExts) {
7089 Value *HeadOfChain =
I->getOperand(0);
7090 SeenChainsForSExt[HeadOfChain] =
nullptr;
7091 ValToSExtendedUses[HeadOfChain].push_back(
I);
7094 Inst = SpeculativelyMovedExts.pop_back_val();
7099 for (
auto *
I : SpeculativelyMovedExts) {
7100 Value *HeadOfChain =
I->getOperand(0);
7101 SeenChainsForSExt[HeadOfChain] = Inst;
7106 if (!AllSeenFirst && !UnhandledExts.
empty())
7107 for (
auto *VisitedSExt : UnhandledExts) {
7108 if (RemovedInsts.count(VisitedSExt))
7110 TypePromotionTransaction TPT(RemovedInsts);
7112 SmallVector<Instruction *, 2> Chains;
7114 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7118 for (
auto *
I : Chains) {
7119 Value *HeadOfChain =
I->getOperand(0);
7121 SeenChainsForSExt[HeadOfChain] =
nullptr;
7122 ValToSExtendedUses[HeadOfChain].push_back(
I);
7128bool CodeGenPrepare::optimizeExtUses(Instruction *
I) {
7133 Value *Src =
I->getOperand(0);
7134 if (Src->hasOneUse())
7146 bool DefIsLiveOut =
false;
7147 for (Instruction *UI :
I->users()) {
7150 if (UserBB == DefBB)
7152 DefIsLiveOut =
true;
7159 for (User *U : Src->users()) {
7162 if (UserBB == DefBB)
7171 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7173 bool MadeChange =
false;
7179 if (UserBB == DefBB)
7183 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7185 if (!InsertedTrunc) {
7188 InsertedTrunc =
new TruncInst(
I, Src->getType(),
"");
7190 InsertedInsts.insert(InsertedTrunc);
7203 I->dropPoisonGeneratingFlags();
7259bool CodeGenPrepare::optimizeLoadExt(LoadInst *
Load) {
7260 if (!
Load->isSimple() || !
Load->getType()->isIntOrPtrTy())
7264 if (
Load->hasOneUse() && InsertedInsts.count(*
Load->user_begin()))
7269 SmallVector<Instruction *, 8> WorkList;
7270 SmallPtrSet<Instruction *, 16> Visited;
7271 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7272 SmallVector<Instruction *, 8> DropFlags;
7273 for (Instruction *U :
Load->users())
7285 while (!WorkList.
empty()) {
7289 if (!Visited.
insert(
I).second)
7294 for (Instruction *U :
Phi->users())
7299 switch (
I->getOpcode()) {
7300 case Instruction::And: {
7304 APInt AndBits = AndC->getValue();
7305 DemandBits |= AndBits;
7307 if (AndBits.
ugt(WidestAndBits))
7308 WidestAndBits = AndBits;
7309 if (AndBits == WidestAndBits &&
I->getOperand(0) ==
Load)
7314 case Instruction::Shl: {
7319 DemandBits.setLowBits(
BitWidth - ShiftAmt);
7324 case Instruction::Trunc: {
7327 DemandBits.setLowBits(TruncBitWidth);
7337 uint32_t ActiveBits = DemandBits.getActiveBits();
7349 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7350 WidestAndBits != DemandBits)
7353 LLVMContext &Ctx =
Load->getType()->getContext();
7354 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7365 Builder.CreateAnd(
Load, ConstantInt::get(Ctx, DemandBits)));
7368 InsertedInsts.insert(NewAnd);
7373 NewAnd->setOperand(0,
Load);
7376 for (
auto *
And : AndsToMaybeRemove)
7381 if (&*CurInstIterator ==
And)
7382 CurInstIterator = std::next(
And->getIterator());
7383 And->eraseFromParent();
7388 for (
auto *Inst : DropFlags)
7402 TTI->isExpensiveToSpeculativelyExecute(
I);
7410 if (!
TLI->isPredictableSelectExpensive())
7420 uint64_t Max = std::max(TrueWeight, FalseWeight);
7421 uint64_t Sum = TrueWeight + FalseWeight;
7424 if (Probability >
TTI->getPredictableBranchThreshold())
7434 if (!Cmp || !Cmp->hasOneUse())
7457 assert(DefSI->getCondition() ==
SI->getCondition() &&
7458 "The condition of DefSI does not match with SI");
7459 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7462 assert(
V &&
"Failed to get select true/false value");
7466bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7490 BinaryOperator::BinaryOps Opcode = Shift->
getOpcode();
7491 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->
getOperand(0), TVal);
7492 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->
getOperand(0), FVal);
7494 Value *NewSel = Builder.CreateSelect(
7495 Cond, NewTVal, NewFVal,
"",
7503bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7505 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7506 "Expected a funnel shift");
7530 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {
X,
Y, TVal});
7531 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {
X,
Y, FVal});
7532 Value *NewSel = Builder.CreateSelect(
7533 Cond, NewTVal, NewFVal,
"",
7543bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7544 if (!Opts.cgp_select2branch)
7548 if (!Opts.disable_select_optimize)
7555 It !=
SI->getParent()->
end(); ++It) {
7557 if (
I &&
SI->getCondition() ==
I->getCondition()) {
7564 SelectInst *LastSI = ASI.
back();
7567 CurInstIterator = std::next(LastSI->
getIterator());
7571 for (SelectInst *SI :
ArrayRef(ASI).drop_front())
7572 fixupDbgVariableRecordsOnInst(*SI);
7574 bool VectorCond = !
SI->getCondition()->getType()->isIntegerTy(1);
7577 if (VectorCond ||
SI->getMetadata(LLVMContext::MD_unpredictable))
7580 TargetLowering::SelectSupportKind SelectKind;
7581 if (
SI->getType()->isVectorTy())
7582 SelectKind = TargetLowering::ScalarCondVectorVal;
7584 SelectKind = TargetLowering::ScalarValSelect;
7621 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7622 for (SelectInst *SI : ASI) {
7634 SplitPt.setHeadBit(
true);
7637 auto *CondFr =
IB.CreateFreeze(
SI->getCondition(),
SI->getName() +
".frozen");
7642 UncondBrInst *TrueBranch =
nullptr;
7643 UncondBrInst *FalseBranch =
nullptr;
7644 if (TrueInstrs.
size() == 0) {
7649 }
else if (FalseInstrs.
size() == 0) {
7666 EndBlock->
setName(
"select.end");
7668 TrueBlock->
setName(
"select.true.sink");
7670 FalseBlock->
setName(FalseInstrs.
size() == 0 ?
"select.false"
7671 :
"select.false.sink");
7675 FreshBBs.
insert(TrueBlock);
7677 FreshBBs.
insert(FalseBlock);
7678 FreshBBs.
insert(EndBlock);
7683 static const unsigned MD[] = {
7684 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7685 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7690 for (Instruction *
I : TrueInstrs)
7692 for (Instruction *
I : FalseInstrs)
7699 if (TrueBlock ==
nullptr)
7700 TrueBlock = StartBlock;
7701 else if (FalseBlock ==
nullptr)
7702 FalseBlock = StartBlock;
7718 SI->eraseFromParent();
7720 ++NumSelectsExpanded;
7724 CurInstIterator = StartBlock->
end();
7731bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7743 "Expected a type of the same size!");
7749 Value *BC1 = Builder.CreateBitCast(
7751 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7752 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7756 SVI, TLInfo,
nullptr,
7757 [&](
Value *
V) { removeAllAssertingVHReferences(
V); });
7764 !
Op->isTerminator() && !
Op->isEHPad())
7770bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *
I) {
7785 for (Use *U :
reverse(OpsToSink)) {
7797 SetVector<Instruction *> MaybeDead;
7798 DenseMap<Instruction *, Instruction *> NewInstructions;
7799 for (Use *U : ToReplace) {
7808 FreshBBs.
insert(OpDef->getParent());
7811 NewInstructions[UI] = NI;
7816 InsertedInsts.insert(NI);
7822 if (
auto It = NewInstructions.
find(OldI); It != NewInstructions.
end())
7823 It->second->setOperand(
U->getOperandNo(), NI);
7830 for (
auto *
I : MaybeDead) {
7831 if (!
I->hasNUsesOrMore(1)) {
7833 I->eraseFromParent();
7840bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7846 unsigned RegWidth =
RegType.getSizeInBits();
7857 auto *NewType = Type::getIntNTy(
Context, RegWidth);
7866 ExtType = Instruction::SExt;
7869 if (Arg->hasSExtAttr())
7870 ExtType = Instruction::SExt;
7871 if (Arg->hasZExtAttr())
7872 ExtType = Instruction::ZExt;
7878 SI->setCondition(ExtInst);
7879 for (
auto Case :
SI->cases()) {
7880 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7881 APInt WideConst = (ExtType == Instruction::ZExt)
7882 ? NarrowConst.
zext(RegWidth)
7883 : NarrowConst.
sext(RegWidth);
7884 Case.setValue(ConstantInt::get(
Context, WideConst));
7890bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7897 Value *Condition =
SI->getCondition();
7906 for (
const SwitchInst::CaseHandle &Case :
SI->cases()) {
7907 ConstantInt *CaseValue = Case.getCaseValue();
7908 BasicBlock *CaseBB = Case.getCaseSuccessor();
7911 bool CheckedForSinglePred =
false;
7912 for (PHINode &
PHI : CaseBB->
phis()) {
7913 Type *PHIType =
PHI.getType();
7921 if (PHIType == ConditionType || TryZExt) {
7923 bool SkipCase =
false;
7924 Value *Replacement =
nullptr;
7925 for (
unsigned I = 0,
E =
PHI.getNumIncomingValues();
I !=
E;
I++) {
7926 Value *PHIValue =
PHI.getIncomingValue(
I);
7927 if (PHIValue != CaseValue) {
7936 if (
PHI.getIncomingBlock(
I) != SwitchBB)
7941 if (!CheckedForSinglePred) {
7942 CheckedForSinglePred =
true;
7943 if (
SI->findCaseDest(CaseBB) ==
nullptr) {
7949 if (Replacement ==
nullptr) {
7950 if (PHIValue == CaseValue) {
7951 Replacement = Condition;
7954 Replacement = Builder.CreateZExt(Condition, PHIType);
7957 PHI.setIncomingValue(
I, Replacement);
7968bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
7969 bool Changed = optimizeSwitchType(SI);
7970 Changed |= optimizeSwitchPhiConstants(SI);
7991class VectorPromoteHelper {
7993 const DataLayout &
DL;
7996 const TargetLowering &
TLI;
7999 const TargetTransformInfo &
TTI;
8005 SmallVector<Instruction *, 4> InstsToBePromoted;
8008 unsigned StoreExtractCombineCost;
8010 bool StressStoreExtract;
8019 if (InstsToBePromoted.
empty())
8021 return InstsToBePromoted.
back();
8027 unsigned getTransitionOriginalValueIdx()
const {
8029 "Other kind of transitions are not supported yet");
8036 unsigned getTransitionIdx()
const {
8038 "Other kind of transitions are not supported yet");
8046 Type *getTransitionType()
const {
8057 void promoteImpl(Instruction *ToBePromoted);
8061 bool isProfitableToPromote() {
8062 Value *ValIdx = Transition->
getOperand(getTransitionOriginalValueIdx());
8066 Type *PromotedType = getTransitionType();
8069 unsigned AS =
ST->getPointerAddressSpace();
8087 for (
const auto &Inst : InstsToBePromoted) {
8095 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8104 CostKind, Arg0Info, Arg1Info);
8107 dbgs() <<
"Estimated cost of computation to be promoted:\nScalar: "
8108 << ScalarCost <<
"\nVector: " << VectorCost <<
'\n');
8109 return ScalarCost > VectorCost;
8121 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8136 if (!
EC.isScalable()) {
8137 SmallVector<Constant *, 4> ConstVec;
8139 for (
unsigned Idx = 0;
Idx !=
EC.getKnownMinValue(); ++
Idx) {
8140 if (Idx == ExtractIdx)
8148 "Generate scalable vector for non-splat is unimplemented");
8153 static bool canCauseUndefinedBehavior(
const Instruction *Use,
8154 unsigned OperandIdx) {
8157 if (OperandIdx != 1)
8159 switch (
Use->getOpcode()) {
8162 case Instruction::SDiv:
8163 case Instruction::UDiv:
8164 case Instruction::SRem:
8165 case Instruction::URem:
8167 case Instruction::FDiv:
8168 case Instruction::FRem:
8169 return !
Use->hasNoNaNs();
8175 VectorPromoteHelper(
const DataLayout &
DL,
const TargetLowering &
TLI,
8176 const TargetTransformInfo &
TTI, Instruction *Transition,
8177 unsigned CombineCost,
bool StressStoreExtract)
8179 StoreExtractCombineCost(CombineCost),
8180 StressStoreExtract(StressStoreExtract) {
8181 assert(Transition &&
"Do not know how to promote null");
8185 bool canPromote(
const Instruction *ToBePromoted)
const {
8192 bool shouldPromote(
const Instruction *ToBePromoted)
const {
8197 for (
const Use &U : ToBePromoted->
operands()) {
8198 const Value *Val =
U.get();
8199 if (Val == getEndOfTransition()) {
8210 return StressStoreExtract ||
8221 void enqueueForPromotion(Instruction *ToBePromoted) {
8222 InstsToBePromoted.push_back(ToBePromoted);
8226 void recordCombineInstruction(Instruction *ToBeCombined) {
8228 CombineInst = ToBeCombined;
8238 if (InstsToBePromoted.empty() || !CombineInst)
8242 if (!StressStoreExtract && !isProfitableToPromote())
8246 for (
auto &ToBePromoted : InstsToBePromoted)
8247 promoteImpl(ToBePromoted);
8248 InstsToBePromoted.clear();
8255void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8265 "The type of the result of the transition does not match "
8270 Type *TransitionTy = getTransitionType();
8275 for (Use &U : ToBePromoted->
operands()) {
8277 Value *NewVal =
nullptr;
8278 if (Val == Transition)
8279 NewVal = Transition->
getOperand(getTransitionOriginalValueIdx());
8286 canCauseUndefinedBehavior(ToBePromoted,
U.getOperandNo()));
8290 ToBePromoted->
setOperand(
U.getOperandNo(), NewVal);
8293 Transition->
setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8299bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8300 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8301 if (!Opts.cgp_store_extract ||
8302 (!Opts.cgp_stress_store_extract &&
8315 LLVM_DEBUG(
dbgs() <<
"Found an interesting transition: " << *Inst <<
'\n');
8316 VectorPromoteHelper VPH(*
DL, *
TLI, *
TTI, Inst, CombineCost,
8317 Opts.cgp_stress_store_extract);
8324 if (ToBePromoted->
getParent() != Parent) {
8325 LLVM_DEBUG(
dbgs() <<
"Instruction to promote is in a different block ("
8327 <<
") than the transition (" << Parent->
getName()
8332 if (VPH.canCombine(ToBePromoted)) {
8334 <<
"will be combined with: " << *ToBePromoted <<
'\n');
8335 VPH.recordCombineInstruction(ToBePromoted);
8337 NumStoreExtractExposed +=
Changed;
8342 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8345 LLVM_DEBUG(
dbgs() <<
"Promoting is possible... Enqueue for promotion!\n");
8347 VPH.enqueueForPromotion(ToBePromoted);
8348 Inst = ToBePromoted;
8387 bool ForceSplitStore) {
8389 Type *StoreType =
SI.getValueOperand()->getType();
8398 if (!
DL.typeSizeEqualsStoreSize(StoreType) ||
8399 DL.getTypeSizeInBits(StoreType) == 0)
8402 unsigned HalfValBitSize =
DL.getTypeSizeInBits(StoreType) / 2;
8404 if (!
DL.typeSizeEqualsStoreSize(SplitStoreType))
8420 if (!
match(
SI.getValueOperand(),
8427 if (!
LValue->getType()->isIntegerTy() ||
8428 DL.getTypeSizeInBits(
LValue->getType()) > HalfValBitSize ||
8430 DL.getTypeSizeInBits(HValue->
getType()) > HalfValBitSize)
8441 if (!ForceSplitStore && !
TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8446 Builder.disableGEPCanonicalization();
8450 if (LBC && LBC->getParent() !=
SI.getParent())
8451 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8452 if (HBC && HBC->getParent() !=
SI.getParent())
8453 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8455 bool IsLE =
SI.getDataLayout().isLittleEndian();
8456 auto CreateSplitStore = [&](
Value *
V,
bool Upper) {
8457 V = Builder.CreateZExtOrBitCast(
V, SplitStoreType);
8458 Value *Addr =
SI.getPointerOperand();
8459 Align Alignment =
SI.getAlign();
8460 const bool IsOffsetStore = (IsLE &&
Upper) || (!IsLE && !
Upper);
8461 if (IsOffsetStore) {
8462 Addr = Builder.CreateGEP(
8463 SplitStoreType, Addr,
8471 Builder.CreateAlignedStore(
V, Addr, Alignment);
8474 CreateSplitStore(
LValue,
false);
8475 CreateSplitStore(HValue,
true);
8478 SI.eraseFromParent();
8563 if (auto *I = dyn_cast<Instruction>(Usr)) {
8564 if (I->getParent() != SrcBlock) {
8572 std::vector<GetElementPtrInst *> UGEPIs;
8575 for (Instruction *Usr : GEPIOp->
users()) {
8579 if (Usr->getParent() == SrcBlock)
8583 ConstantInt *UGEPIIdx;
8586 if (GEPIIdx->getType() != UGEPIIdx->
getType())
8594 if (UGEPIs.size() == 0)
8597 for (GetElementPtrInst *UGEPI : UGEPIs) {
8599 APInt NewIdx = UGEPIIdx->
getValue() - GEPIIdx->getValue();
8606 for (GetElementPtrInst *UGEPI : UGEPIs) {
8607 UGEPI->setOperand(0, GEPI);
8609 auto NewIdx = UGEPIIdx->
getValue() - GEPIIdx->getValue();
8610 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8611 UGEPI->setOperand(1, NewUGEPIIdx);
8613 auto SourceFlags = GEPI->getNoWrapFlags();
8616 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8618 if (NewIdx.
isNegative() && TargetFlags.hasNoUnsignedWrap())
8619 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8620 UGEPI->setNoWrapFlags(TargetFlags);
8626 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8628 "GEPIOp is used outside SrcBlock");
8645 if (!
TLI.preferZeroCompareBranch())
8652 Value *
X = Cmp->getOperand(0);
8653 if (!
X->hasUseList())
8658 for (
auto *U :
X->users()) {
8662 (UI->
getParent() != Branch->getParent() &&
8663 UI->
getParent() != Branch->getSuccessor(0) &&
8664 UI->
getParent() != Branch->getSuccessor(1)) ||
8665 (UI->
getParent() != Branch->getParent() &&
8666 !UI->
getParent()->getSinglePredecessor()))
8672 if (UI->
getParent() != Branch->getParent())
8676 ConstantInt::get(UI->
getType(), 0));
8678 LLVM_DEBUG(
dbgs() <<
" to compare on zero: " << *NewCmp <<
"\n");
8682 if (Cmp->isEquality() &&
8687 if (UI->
getParent() != Branch->getParent())
8690 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8691 ConstantInt::get(UI->
getType(), 0));
8693 LLVM_DEBUG(
dbgs() <<
" to compare on zero: " << *NewCmp <<
"\n");
8733 if (!L || !L->isInnermost())
8737 BasicBlock *PreHeader = L->getLoopPreheader();
8739 if (!PreHeader || !Latch || Phi->getParent() != Header ||
8740 Phi->getNumIncomingValues() != 2)
8744 Value *Start = Phi->getIncomingValueForBlock(PreHeader);
8745 Value *Step = Phi->getIncomingValueForBlock(Latch);
8752 Type *ITy = VTy->getElementType();
8753 if (
DL.getTypeStoreSize(ITy) !=
DL.getPointerSize())
8761 Value *LoopStride =
nullptr;
8767 const APInt *ShiftAmt =
nullptr;
8768 Value *PtrStride =
nullptr;
8772 (1ULL << ShiftAmt->
getZExtValue()) != EltCnt.getKnownMinValue())
8784 for (
User *U : Phi->users()) {
8796 if (!
GEP ||
GEP->getNumOperands() != 2)
8801 if (!L->isLoopInvariant(
Base))
8810 unsigned Size =
DL.getTypeAllocSize(
GEP->getSourceElementType());
8812 Value *StructSize = ConstantInt::get(ITy,
Size);
8814 Builder.CreateVectorSplat(VTy->getElementCount(), StructSize);
8815 Value *NewStart = Builder.CreateMul(Start, SizeSplat);
8816 NewStart = Builder.CreatePtrAdd(
Base, NewStart);
8820 Value *StructStride = Builder.CreateMul(PtrStride, StructSize);
8822 Builder.CreateVectorSplat(VTy->getElementCount(), StructStride);
8824 Builder.SetInsertPoint(Phi);
8825 PHINode *NewPhi = Builder.CreatePHI(
GEP->getType(), 2,
"vec.lsr.phi");
8827 StructStride = Builder.CreatePtrAdd(NewPhi, StructStride);
8834 Builder.SetInsertPoint(
GEP);
8835 GEP->replaceAllUsesWith(NewPhi);
8844bool CodeGenPrepare::optimizeInst(Instruction *
I, ModifyDT &ModifiedDT) {
8845 bool AnyChange =
false;
8846 AnyChange = fixupDbgVariableRecordsOnInst(*
I);
8850 if (InsertedInsts.count(
I))
8859 LargeOffsetGEPMap.erase(
P);
8861 P->eraseFromParent();
8869 if (
P->getType()->isScalableTy())
8898 I, LI->getLoopFor(
I->getParent()), *
TTI))
8906 TargetLowering::TypeExpandInteger) {
8910 I, LI->getLoopFor(
I->getParent()), *
TTI))
8913 bool MadeChange = optimizeExt(
I);
8914 return MadeChange | optimizeExtUses(
I);
8921 if (optimizeCmp(Cmp, ModifiedDT))
8925 if (optimizeURem(
I))
8929 LI->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
8930 bool Modified = optimizeLoadExt(LI);
8939 bool Modified = tryToSinkFreeOperands(
I);
8940 SI->setMetadata(LLVMContext::MD_invariant_group,
nullptr);
8941 unsigned AS =
SI->getPointerAddressSpace();
8942 Modified |= optimizeMemoryInst(
I,
SI->getOperand(1),
8943 SI->getOperand(0)->getType(), AS);
8948 unsigned AS = RMW->getPointerAddressSpace();
8949 return optimizeMemoryInst(
I, RMW->getPointerOperand(), RMW->getType(), AS);
8953 unsigned AS = CmpX->getPointerAddressSpace();
8954 return optimizeMemoryInst(
I, CmpX->getPointerOperand(),
8955 CmpX->getCompareOperand()->getType(), AS);
8960 if (BinOp && BinOp->
getOpcode() == Instruction::And &&
8961 Opts.cgp_andcmp_sinking &&
8966 if (BinOp && (BinOp->
getOpcode() == Instruction::AShr ||
8967 BinOp->
getOpcode() == Instruction::LShr)) {
8975 if (GEPI->hasAllZeroIndices()) {
8977 Instruction *
NC =
new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
8978 GEPI->getName(), GEPI->getIterator());
8979 NC->setDebugLoc(GEPI->getDebugLoc());
8982 GEPI, TLInfo,
nullptr,
8983 [&](
Value *
V) { removeAllAssertingVHReferences(
V); });
8985 optimizeInst(
NC, ModifiedDT);
9003 if (Const0 || Const1) {
9004 if (!Const0 || !Const1) {
9005 auto *
F =
new FreezeInst(Const0 ? Op1 : Op0,
"", CmpI->
getIterator());
9011 FI->eraseFromParent();
9019 if (
I->getType()->isVectorTy() &&
9023 if (tryToSinkFreeOperands(
I))
9026 switch (
I->getOpcode()) {
9027 case Instruction::Shl:
9028 case Instruction::LShr:
9029 case Instruction::AShr:
9031 case Instruction::Call:
9033 case Instruction::Select:
9035 case Instruction::ShuffleVector:
9037 case Instruction::Switch:
9039 case Instruction::ExtractElement:
9041 case Instruction::CondBr:
9050bool CodeGenPrepare::makeBitReverse(Instruction &
I) {
9051 if (!
I.getType()->isIntegerTy() ||
9056 SmallVector<Instruction *, 4> Insts;
9062 &
I, TLInfo,
nullptr,
9063 [&](
Value *
V) { removeAllAssertingVHReferences(
V); });
9070bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9072 bool MadeChange =
false;
9075 CurInstIterator = BB.
begin();
9076 ModifiedDT = ModifyDT::NotModifyDT;
9077 while (CurInstIterator != BB.
end()) {
9078 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9079 if (ModifiedDT != ModifyDT::NotModifyDT) {
9088 }
while (ModifiedDT == ModifyDT::ModifyInstDT);
9090 bool MadeBitReverse =
true;
9091 while (MadeBitReverse) {
9092 MadeBitReverse =
false;
9094 if (makeBitReverse(
I)) {
9095 MadeBitReverse = MadeChange =
true;
9100 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9105bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &
I) {
9106 bool AnyChange =
false;
9107 for (DbgVariableRecord &DVR :
filterDbgVars(
I.getDbgRecordRange()))
9108 AnyChange |= fixupDbgVariableRecord(DVR);
9114bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9115 if (DVR.
Type != DbgVariableRecord::LocationType::Value &&
9116 DVR.
Type != DbgVariableRecord::LocationType::Assign)
9120 bool AnyChange =
false;
9121 SmallDenseSet<Value *> LocationOps(DVR.
location_ops().begin(),
9123 for (
Value *Location : LocationOps) {
9124 WeakTrackingVH SunkAddrVH = SunkAddrs[
Location];
9153bool CodeGenPrepare::placeDbgValues(
Function &
F) {
9154 bool MadeChange =
false;
9155 DominatorTree &DT = getDT();
9157 auto DbgProcessor = [&](
auto *DbgItem,
Instruction *Position) {
9158 SmallVector<Instruction *, 4> VIs;
9159 for (
Value *
V : DbgItem->location_ops())
9167 for (Instruction *VI : VIs) {
9168 if (
VI->isTerminator())
9173 if (
isa<PHINode>(VI) &&
VI->getParent()->getTerminator()->isEHPad())
9184 if (VIs.size() > 1) {
9187 <<
"Unable to find valid location for Debug Value, undefing:\n"
9189 DbgItem->setKillLocation();
9194 << *DbgItem <<
' ' << *VI);
9201 for (BasicBlock &BB :
F) {
9207 if (DVR.
Type != DbgVariableRecord::LocationType::Value)
9209 DbgProcessor(&DVR, &Insn);
9220bool CodeGenPrepare::placePseudoProbes(
Function &
F) {
9221 bool MadeChange =
false;
9224 auto FirstInst =
Block.getFirstInsertionPt();
9229 while (
I !=
Block.end()) {
9231 II->moveBefore(FirstInst);
9261bool CodeGenPrepare::splitBranchCondition(
Function &
F) {
9265 bool MadeChange =
false;
9266 for (
auto &BB :
F) {
9279 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9287 Value *Cond1, *Cond2;
9290 Opc = Instruction::And;
9293 Opc = Instruction::Or;
9303 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9317 Br1->setCondition(Cond1);
9322 if (
Opc == Instruction::And)
9323 Br1->setSuccessor(0, TmpBB);
9325 Br1->setSuccessor(1, TmpBB);
9330 I->removeFromParent();
9331 I->insertBefore(Br2->getIterator());
9343 if (
Opc == Instruction::Or)
9347 TBB->replacePhiUsesWith(&BB, TmpBB);
9350 for (PHINode &PN : FBB->
phis()) {
9355 if (
Loop *L = LI->getLoopFor(&BB))
9356 L->addBasicBlockToLoop(TmpBB, *LI);
9360 DTU->
applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9361 {DominatorTree::Insert, TmpBB,
TBB},
9362 {DominatorTree::Insert, TmpBB, FBB},
9363 {DominatorTree::Delete, &BB,
TBB}});
9367 if (
Opc == Instruction::Or) {
9389 uint64_t NewTrueWeight = TrueWeight;
9390 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9394 NewTrueWeight = TrueWeight;
9395 NewFalseWeight = 2 * FalseWeight;
9420 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9421 uint64_t NewFalseWeight = FalseWeight;
9425 NewTrueWeight = 2 * TrueWeight;
9426 NewFalseWeight = FalseWeight;
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator * > &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value * > &OffsetV)
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once.
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes:
static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI, const DataLayout &DL)
Hoists bitcasts to the source block to reduce register pressure.
static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI, bool ForceSplitStore)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp)
Many architectures use the same instruction for both subtract and cmp.
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Use *, Type * > > &MemoryUses, SmallPtrSetImpl< Instruction * > &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan)
Recursively walk all the uses of I until we find a memory use.
static std::optional< std::pair< Instruction *, Constant * > > getIVIncrement(const PHINode *PN, const LoopInfo *LI)
If given PN is an inductive variable with value IVInc coming from the backedge, and on each iteration...
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI, bool EnableICmpEqToICmpSt)
For pattern like:
static bool strengthReduceVectorPhiUsers(PHINode *Phi, LoopInfo *LI)
static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands.
static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo, const CallInst *CI)
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract, ExtractValueInst *&OverflowExtract)
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, MapVector< GCRelocateInst *, SmallVector< GCRelocateInst *, 0 > > &RelocateInstMap)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS, Constant *&Step)
static bool isIVIncrement(const Value *V, const LoopInfo *LI)
static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI)
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
static bool isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut, Constant *&StepOut)
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
static bool despeculateCountZeros(IntrinsicInst *CountZeros, DomTreeUpdater *DTU, LoopInfo *LI, const TargetLowering *TLI, const DataLayout *DL, ModifyDT &ModifiedDT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
If counting leading or trailing zeros is an expensive operation and a zero input is defined,...
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, DominatorTree &DT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
Defines an IR pass for CodeGen Prepare.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
static Value * getCondition(Instruction *I)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
SmallVector< MachineOperand, 4 > Cond
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the PointerIntPair class.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
static DominatorTree getDomTree(Function &F)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
Remove Loads Into Fake Uses
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
static bool optimizeCallInst(CallInst *CI, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Constant * getConstantVector(MVT VT, ArrayRef< APInt > Bits, const APInt &Undefs, LLVMContext &C)
Class for arbitrary precision integers.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
uint64_t getZExtValue() const
Get zero extended value.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
bool isNegative() const
Determine sign of this APInt.
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
unsigned logBase2() const
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
int64_t getSExtValue() const
Get sign extended value.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
An instruction that atomically checks whether a specified value is in a memory location,...
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
Analysis pass providing the BasicBlockSectionsProfileReader.
LLVM_ABI bool isFunctionHot(StringRef FuncName) const
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
InstListType::const_iterator const_iterator
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis pass which computes BranchProbabilityInfo.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_ULE
unsigned less or equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Conditional Branch instruction.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
const APInt & getValue() const
Return the constant as an APInt value reference.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI void removeFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
static constexpr UpdateKind Insert
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
FunctionPass class - This class is used to implement most global optimizations.
const BasicBlock & getEntryBlock() const
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
void compute(FunctionT &F)
Compute the cycle info for a function.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool canIncreaseAlignment() const
Returns true if the alignment of the value can be unilaterally increased.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
Value * CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
static MVT getIntegerVT(unsigned BitWidth)
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
void clear()
Completely clear the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
value_type pop_back_val()
VectorType * getType() const
Overload to return most specific vector type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool isSelectSupported(SelectSupportKind) const
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual MVT getPreferredSwitchConditionType(LLVMContext &Context, EVT ConditionVT) const
Returns preferred type for switch condition.
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
virtual bool shouldConsiderGEPOffsetSplit() const
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool optimizeVectorCrossLaneOperation(Instruction *I, Loop *L) const
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
const Use & getOperandUse(unsigned i) const
void setOperand(unsigned i, Value *Val)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
user_iterator user_begin()
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator_range< use_iterator > uses()
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
constexpr ScalarTy getFixedValue() const
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
StructType * getStructTypeOrNull() const
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
auto m_VScale()
Matches a call to llvm.vscale().
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
Splat_match< T > m_Splat(const T &SubPattern)
Match a vector splat.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true >, DisjointOr_match< LHS, RHS, true > > m_c_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint", with LHS and RHS commutable.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ CE
Windows NT (Windows on ARM)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
SmallVector< Node, 4 > NodeList
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
LLVM_ABI bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BranchProbabilityInfo *BPI=nullptr)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
APInt operator*(APInt a, uint64_t RHS)
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
bool operator!=(uint64_t V1, const APInt &V2)
constexpr from_range_t from_range
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
auto reverse(ContainerTy &&C)
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI FunctionPass * createCodeGenPrepareLegacyPass()
createCodeGenPrepareLegacyPass - Transform the code to expose more pattern matching during instructio...
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool pred_empty(const BasicBlock *BB)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::pair< Value *, FPClassTest > fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
DenseMap< const Value *, Value * > ValueToValueMap
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
bool isInteger() const
Return true if this is an integer or a vector integer type.
This contains information for each constraint that we are lowering.