LLVM 24.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
16#include "CodeGenOptions.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/IR/Argument.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/CFG.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/CycleInfo.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugInfo.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
61#include "llvm/IR/GlobalValue.h"
63#include "llvm/IR/IRBuilder.h"
64#include "llvm/IR/InlineAsm.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsAArch64.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/MDBuilder.h"
73#include "llvm/IR/Module.h"
74#include "llvm/IR/Operator.h"
77#include "llvm/IR/Statepoint.h"
78#include "llvm/IR/Type.h"
79#include "llvm/IR/Use.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
83#include "llvm/IR/ValueMap.h"
85#include "llvm/Pass.h"
91#include "llvm/Support/Debug.h"
101#include <algorithm>
102#include <cassert>
103#include <cstdint>
104#include <iterator>
105#include <limits>
106#include <memory>
107#include <optional>
108#include <utility>
109#include <vector>
110
111using namespace llvm;
112using namespace llvm::PatternMatch;
113
114#define DEBUG_TYPE "codegenprepare"
115
116STATISTIC(NumBlocksElim, "Number of blocks eliminated");
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 "
120 "sunken Cmps");
121STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
122 "of sunken Casts");
123STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
124 "computations were sunk");
125STATISTIC(NumMemoryInstsPhiCreated,
126 "Number of phis created when address "
127 "computations were sunk to memory instructions");
128STATISTIC(NumMemoryInstsSelectCreated,
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");
133STATISTIC(NumAndsAdded,
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");
140
141namespace {
142
143enum ExtType {
144 ZeroExtension, // Zero extension has been seen.
145 SignExtension, // Sign extension has been seen.
146 BothExtension // This extension type is used if we saw sext after
147 // ZeroExtension had been set, or if we saw zext after
148 // SignExtension had been set. It makes the type
149 // information of a promoted instruction invalid.
150};
151
152enum ModifyDT {
153 NotModifyDT, // Not Modify any DT.
154 ModifyBBDT, // Modify the Basic Block Dominator Tree.
155 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
156 // This usually means we move/delete/insert instruction
157 // in a Basic Block. So we should re-iterate instructions
158 // in such Basic Block.
159};
160
161using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
162using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
163using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
165using ValueToSExts = MapVector<Value *, SExts>;
166
167class TypePromotionTransaction;
168
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;
184
185 /// As we scan instructions optimizing them, this is the next instruction
186 /// to optimize. Transforms that can invalidate this should update it.
187 BasicBlock::iterator CurInstIterator;
188
189 /// Keeps track of non-local addresses that have been sunk into a block.
190 /// This allows us to avoid inserting duplicate code for blocks with
191 /// multiple load/stores of the same address. The usage of WeakTrackingVH
192 /// enables SunkAddrs to be treated as a cache whose entries can be
193 /// invalidated if a sunken address computation has been erased.
194 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
195
196 /// Keeps track of all instructions inserted for the current function.
197 SetOfInstrs InsertedInsts;
198
199 /// Keeps track of the type of the related instruction before their
200 /// promotion for the current function.
201 InstrToOrigTy PromotedInsts;
202
203 /// Keep track of instructions removed during promotion.
204 SetOfInstrs RemovedInsts;
205
206 /// Keep track of sext chains based on their initial value.
207 DenseMap<Value *, Instruction *> SeenChainsForSExt;
208
209 /// Keep track of GEPs accessing the same data structures such as structs or
210 /// arrays that are candidates to be split later because of their large
211 /// size.
212 MapVector<AssertingVH<Value>,
214 LargeOffsetGEPMap;
215
216 /// Keep track of new GEP base after splitting the GEPs having large offset.
217 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
218
219 /// Map serial numbers to Large offset GEPs.
220 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
221
222 /// Keep track of SExt promoted.
223 ValueToSExts ValToSExtendedUses;
224
225 /// True if the function has the OptSize attribute.
226 bool OptSize;
227
228 /// DataLayout for the Function being processed.
229 const DataLayout *DL = nullptr;
230
231public:
232 CodeGenPrepare(const TargetMachine *TM)
233 : Opts(cl::LibraryOptionsContext::get<CodeGenOptions>(
234 TM->Options.MCOptions.LibraryOptions)),
235 TM(TM) {}
236 /// If encounter huge function, we need to limit the build time.
237 bool IsHugeFunc = false;
238
239 /// FreshBBs is like worklist, it collected the updated BBs which need
240 /// to be optimized again.
241 /// Note: Consider building time in this pass, when a BB updated, we need
242 /// to insert such BB into FreshBBs for huge function.
243 SmallPtrSet<BasicBlock *, 32> FreshBBs;
244
245 void releaseMemory() {
246 // Clear per function information.
247 InsertedInsts.clear();
248 PromotedInsts.clear();
249 FreshBBs.clear();
250 }
251
253
254private:
255 template <typename F>
256 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
257 // Substituting can cause recursive simplifications, which can invalidate
258 // our iterator. Use a WeakTrackingVH to hold onto it in case this
259 // happens.
260 Value *CurValue = &*CurInstIterator;
261 WeakTrackingVH IterHandle(CurValue);
262
263 f();
264
265 // If the iterator instruction was recursively deleted, start over at the
266 // start of the block.
267 if (IterHandle != CurValue) {
268 CurInstIterator = BB->begin();
269 SunkAddrs.clear();
270 }
271 }
272
273 // Get the DominatorTree, updating it if necessary.
274 DominatorTree &getDT() { return DTU->getDomTree(); }
275
276 void removeAllAssertingVHReferences(Value *V);
277 bool eliminateAssumptions(Function &F);
278 bool eliminateFallThrough(Function &F);
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,
284 bool isPreheader);
285 bool makeBitReverse(Instruction &I);
286 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
287 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
288 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
289 unsigned AddrSpace);
290 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
291 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
292 ModifyDT &ModifiedDT);
293 bool optimizeInlineAsmInst(CallInst *CS);
294 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
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);
309 bool placeDbgValues(Function &F);
310 bool placePseudoProbes(Function &F);
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);
317 bool mergeSExts(Function &F);
318 bool splitLargeGEPOffsets();
319 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
320 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
321 bool optimizePhiTypes(Function &F);
322 bool performAddressTypePromotion(
323 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
324 bool HasPromoted, TypePromotionTransaction &TPT,
325 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
326 bool splitBranchCondition(Function &F);
327 bool simplifyOffsetableRelocate(GCStatepointInst &I);
328
329 bool tryToSinkFreeOperands(Instruction *I);
330 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
331 CmpInst *Cmp, Intrinsic::ID IID);
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);
337 void verifyBFIUpdates(Function &F);
338 bool _run(Function &F);
339};
340
341class CodeGenPrepareLegacyPass : public FunctionPass {
342public:
343 static char ID; // Pass identification, replacement for typeid
344
345 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
346
347 bool runOnFunction(Function &F) override;
348
349 StringRef getPassName() const override { return "CodeGen Prepare"; }
350
351 void getAnalysisUsage(AnalysisUsage &AU) const override {
352 // FIXME: When we can selectively preserve passes, preserve the domtree.
353 AU.addRequired<ProfileSummaryInfoWrapperPass>();
354 AU.addRequired<TargetLibraryInfoWrapperPass>();
355 AU.addRequired<TargetPassConfig>();
356 AU.addRequired<TargetTransformInfoWrapperPass>();
357 AU.addRequired<DominatorTreeWrapperPass>();
358 AU.addRequired<LoopInfoWrapperPass>();
359 AU.addRequired<BranchProbabilityInfoWrapperPass>();
360 AU.addRequired<BlockFrequencyInfoWrapperPass>();
361 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
362 }
363};
364
365} // end anonymous namespace
366
367char CodeGenPrepareLegacyPass::ID = 0;
368
369bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
370 if (skipFunction(F))
371 return false;
372 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
373 CodeGenPrepare CGP(TM);
374 CGP.DL = &F.getDataLayout();
375 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
376 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
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();
384 auto BBSPRWP =
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;
391
392 return CGP._run(F);
393}
394
395INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
396 "Optimize for code generation", false, false)
404INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
405 "Optimize for code generation", false, false)
406
408 return new CodeGenPrepareLegacyPass();
409}
410
413 CodeGenPrepare CGP(TM);
414
415 bool Changed = CGP.run(F, AM);
416 if (!Changed)
417 return PreservedAnalyses::all();
418
422 return PA;
423}
424
425bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
426 DL = &F.getDataLayout();
427 SubtargetInfo = TM->getSubtargetImpl(F);
428 TLI = SubtargetInfo->getTargetLowering();
429 TRI = SubtargetInfo->getRegisterInfo();
430 TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
432 LI = &AM.getResult<LoopAnalysis>(F);
435 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
436 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
437 if (!PSI)
438 reportFatalUsageError("this pass requires the profile-summary module "
439 "analysis to be available");
440 BBSectionsProfileReader =
443 DomTreeUpdater::UpdateStrategy::Lazy);
444 DTU = &DTUpdater;
445 return _run(F);
446}
447
448bool CodeGenPrepare::_run(Function &F) {
449 bool EverMadeChange = false;
450
451 OptSize = F.hasOptSize();
452 // Use the basic-block-sections profile to promote hot functions to .text.hot
453 // if requested.
454 if (Opts.bbsections_guided_section_prefix && BBSectionsProfileReader &&
455 BBSectionsProfileReader->isFunctionHot(F.getName())) {
456 (void)F.setSectionPrefix("hot");
457 } else if (Opts.profile_guided_section_prefix) {
458 // The hot attribute overwrites profile count based hotness while profile
459 // counts based hotness overwrite the cold attribute.
460 // This is a conservative behabvior.
461 if (F.hasFnAttribute(Attribute::Hot) ||
462 PSI->isFunctionHotInCallGraph(&F, *BFI))
463 (void)F.setSectionPrefix("hot");
464 // If PSI shows this function is not hot, we will placed the function
465 // into unlikely section if (1) PSI shows this is a cold function, or
466 // (2) the function has a attribute of cold.
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");
473 }
474
475 /// This optimization identifies DIV instructions that can be
476 /// profitably bypassed and carried out with a shorter, faster divide.
477 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
478 const DenseMap<unsigned int, unsigned int> &BypassWidths =
480 BasicBlock *BB = &*F.begin();
481 while (BB != nullptr) {
482 // bypassSlowDivision may create new BBs, but we don't want to reapply the
483 // optimization to those blocks.
484 BasicBlock *Next = BB->getNextNode();
485 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
486 EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI, BPI);
487 BB = Next;
488 }
489 }
490
491 // Get rid of @llvm.assume builtins before attempting to eliminate empty
492 // blocks, since there might be blocks that only contain @llvm.assume calls
493 // (plus arguments that we can get rid of).
494 EverMadeChange |= eliminateAssumptions(F);
495
496 auto resetLoopInfo = [this]() {
497 LI->releaseMemory();
498 LI->analyze(DTU->getDomTree());
499 };
500
501 // Eliminate blocks that contain only PHI nodes and an
502 // unconditional branch.
503 bool ResetLI = false;
504 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
505 if (ResetLI)
506 resetLoopInfo();
507
508 if (Opts.cgp_branch_opts)
509 EverMadeChange |= splitBranchCondition(F);
510
511 // Split some critical edges where one of the sources is an indirect branch,
512 // to help generate sane code for PHIs involving such edges.
513 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
514 BPI, BFI, DTU);
515 EverMadeChange |= Split;
516 if (Split)
517 resetLoopInfo();
518
519#ifndef NDEBUG
520 if (VerifyDomInfo)
521 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
522 "Incorrect DominatorTree updates in CGP");
523
524 if (VerifyLoopInfo)
525 LI->verify();
526#endif
527
528 // If we are optimzing huge function, we need to consider the build time.
529 // Because the basic algorithm's complex is near O(N!).
530 IsHugeFunc = F.size() > Opts.cgp_huge_func;
531
532 bool MadeChange = true;
533 bool FuncIterated = false;
534 while (MadeChange) {
535 MadeChange = false;
536
537 // This is required because optimizeBlock() calls getDT() inside the loop
538 // below, which flushes pending updates and may delete dead blocks, leading
539 // to iterator invalidation.
540 DTU->flush();
541
542 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
543 if (FuncIterated && !FreshBBs.contains(&BB))
544 continue;
545
546 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
547 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
548
549 MadeChange |= Changed;
550 if (IsHugeFunc) {
551 // If the BB is updated, it may still has chance to be optimized.
552 // This usually happen at sink optimization.
553 // For example:
554 //
555 // bb0:
556 // %and = and i32 %a, 4
557 // %cmp = icmp eq i32 %and, 0
558 //
559 // If the %cmp sink to other BB, the %and will has chance to sink.
560 if (Changed)
561 FreshBBs.insert(&BB);
562 else if (FuncIterated)
563 FreshBBs.erase(&BB);
564 } else {
565 // For small/normal functions, we restart BB iteration if the dominator
566 // tree of the Function was changed.
567 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
568 break;
569 }
570 }
571 // We have iterated all the BB in the (only work for huge) function.
572 FuncIterated = IsHugeFunc;
573
574 if (Opts.cgp_type_promotion_merge && !ValToSExtendedUses.empty())
575 MadeChange |= mergeSExts(F);
576 if (!LargeOffsetGEPMap.empty())
577 MadeChange |= splitLargeGEPOffsets();
578 MadeChange |= optimizePhiTypes(F);
579
580 if (MadeChange)
581 eliminateFallThrough(F);
582
583#ifndef NDEBUG
584 if (VerifyDomInfo)
585 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
586 "Incorrect DominatorTree updates in CGP");
587
588 if (VerifyLoopInfo)
589 LI->verify();
590#endif
591
592 // Really free removed instructions during promotion.
593 for (Instruction *I : RemovedInsts)
594 I->deleteValue();
595
596 EverMadeChange |= MadeChange;
597 SeenChainsForSExt.clear();
598 ValToSExtendedUses.clear();
599 RemovedInsts.clear();
600 LargeOffsetGEPMap.clear();
601 LargeOffsetGEPID.clear();
602 }
603
604 NewGEPBases.clear();
605 SunkAddrs.clear();
606
607 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
608 LI = nullptr;
609
610 if (Opts.cgp_branch_opts) {
611 MadeChange = false;
612 // Use a set vector to get deterministic iteration order. The order the
613 // blocks are removed may affect whether or not PHI nodes in successors
614 // are removed.
615 SmallSetVector<BasicBlock *, 8> WorkList;
616 for (BasicBlock &BB : F) {
618 MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
619 if (!MadeChange)
620 continue;
621
622 for (BasicBlock *Succ : Successors)
623 if (pred_empty(Succ))
624 WorkList.insert(Succ);
625 }
626
627 // Delete the dead blocks and any of their dead successors.
628 MadeChange |= !WorkList.empty();
629 while (!WorkList.empty()) {
630 BasicBlock *BB = WorkList.pop_back_val();
632
633 DeleteDeadBlock(BB, DTU);
634
635 for (BasicBlock *Succ : Successors)
636 if (pred_empty(Succ))
637 WorkList.insert(Succ);
638 }
639
640 // Flush pending DT updates in order to finalise deletion of dead blocks.
641 DTU->flush();
642
643 // Merge pairs of basic blocks with unconditional branches, connected by
644 // a single edge.
645 if (EverMadeChange || MadeChange)
646 MadeChange |= eliminateFallThrough(F);
647
648 EverMadeChange |= MadeChange;
649 }
650
651 if (Opts.cgp_gc_opts) {
653 for (BasicBlock &BB : F)
654 for (Instruction &I : BB)
655 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
656 Statepoints.push_back(SP);
657 for (auto &I : Statepoints)
658 EverMadeChange |= simplifyOffsetableRelocate(*I);
659 }
660
661 // Do this last to clean up use-before-def scenarios introduced by other
662 // preparatory transforms.
663 EverMadeChange |= placeDbgValues(F);
664 EverMadeChange |= placePseudoProbes(F);
665
666#ifndef NDEBUG
667 if (Opts.cgp_verify_bfi_updates)
668 verifyBFIUpdates(F);
669#endif
670
671 return EverMadeChange;
672}
673
674bool CodeGenPrepare::eliminateAssumptions(Function &F) {
675 bool MadeChange = false;
676 for (BasicBlock &BB : F) {
677 CurInstIterator = BB.begin();
678 while (CurInstIterator != BB.end()) {
679 Instruction *I = &*(CurInstIterator++);
680 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
681 MadeChange = true;
682 Value *Operand = Assume->getOperand(0);
683 Assume->eraseFromParent();
684
685 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
686 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
687 });
688 }
689 }
690 }
691 return MadeChange;
692}
693
694/// An instruction is about to be deleted, so remove all references to it in our
695/// GEP-tracking data strcutures.
696void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
697 LargeOffsetGEPMap.erase(V);
698 NewGEPBases.erase(V);
699
701 if (!GEP)
702 return;
703
704 LargeOffsetGEPID.erase(GEP);
705
706 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
707 if (VecI == LargeOffsetGEPMap.end())
708 return;
709
710 auto &GEPVector = VecI->second;
711 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
712
713 if (GEPVector.empty())
714 LargeOffsetGEPMap.erase(VecI);
715}
716
717// Verify BFI has been updated correctly by recomputing BFI and comparing them.
718[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
719 CycleInfo NewCI;
720 NewCI.compute(F);
721 BranchProbabilityInfo NewBPI(F, NewCI, TLInfo);
722 BlockFrequencyInfo NewBFI(F, NewBPI, NewCI);
723 NewBFI.verifyMatch(*BFI);
724}
725
726/// Merge basic blocks which are connected by a single edge, where one of the
727/// basic blocks has a single successor pointing to the other basic block,
728/// which has a single predecessor.
729bool CodeGenPrepare::eliminateFallThrough(Function &F) {
730 bool Changed = false;
731 SmallPtrSet<BasicBlock *, 8> Preds;
732 // Scan all of the blocks in the function, except for the entry block.
733 for (auto &Block : llvm::drop_begin(F)) {
734 auto *BB = &Block;
735 if (DTU->isBBPendingDeletion(BB))
736 continue;
737 // If the destination block has a single pred, then this is a trivial
738 // edge, just collapse it.
739 BasicBlock *SinglePred = BB->getSinglePredecessor();
740
741 // Don't merge if BB's address is taken.
742 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
743 continue;
744
745 if (isa<UncondBrInst>(SinglePred->getTerminator())) {
746 Changed = true;
747 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
748
749 // Merge BB into SinglePred and delete it.
750 MergeBlockIntoPredecessor(BB, DTU, LI);
751 Preds.insert(SinglePred);
752
753 if (IsHugeFunc) {
754 // Update FreshBBs to optimize the merged BB.
755 FreshBBs.insert(SinglePred);
756 FreshBBs.erase(BB);
757 }
758 }
759 }
760
761 // (Repeatedly) merging blocks into their predecessors can create redundant
762 // debug intrinsics.
763 for (auto *Pred : Preds)
764 if (!DTU->isBBPendingDeletion(Pred))
766
767 return Changed;
768}
769
770/// Find a destination block from BB if BB is mergeable empty block.
771BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
772 // If this block doesn't end with an uncond branch, ignore it.
773 UncondBrInst *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
774 if (!BI)
775 return nullptr;
776
777 // If the instruction before the branch (skipping debug info) isn't a phi
778 // node, then other stuff is happening here.
780 if (BBI != BB->begin()) {
781 --BBI;
782 if (!isa<PHINode>(BBI))
783 return nullptr;
784 }
785
786 // Do not break infinite loops.
787 BasicBlock *DestBB = BI->getSuccessor();
788 if (DestBB == BB)
789 return nullptr;
790
791 if (!canMergeBlocks(BB, DestBB))
792 DestBB = nullptr;
793
794 return DestBB;
795}
796
797/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
798/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
799/// edges in ways that are non-optimal for isel. Start by eliminating these
800/// blocks so we can split them the way we want them.
801bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
802 SmallPtrSet<BasicBlock *, 16> Preheaders;
803 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
804 while (!LoopList.empty()) {
805 Loop *L = LoopList.pop_back_val();
806 llvm::append_range(LoopList, *L);
807 if (BasicBlock *Preheader = L->getLoopPreheader())
808 Preheaders.insert(Preheader);
809 }
810
811 ResetLI = false;
812 bool MadeChange = false;
813 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
814 // Note that this intentionally skips the entry block.
815 for (auto &Block : llvm::drop_begin(F)) {
816 // Delete phi nodes that could block deleting other empty blocks.
817 if (Opts.cgp_delete_phis)
818 MadeChange |= DeleteDeadPHIs(&Block, TLInfo, nullptr, &KnownNonDeadPHIs);
819 }
820
821 for (auto &Block : llvm::drop_begin(F)) {
822 auto *BB = &Block;
823 if (DTU->isBBPendingDeletion(BB))
824 continue;
825 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
826 if (!DestBB ||
827 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
828 continue;
829
830 ResetLI |= eliminateMostlyEmptyBlock(BB);
831 MadeChange = true;
832 }
833 return MadeChange;
834}
835
836bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
837 BasicBlock *DestBB,
838 bool isPreheader) {
839 // Do not delete loop preheaders if doing so would create a critical edge.
840 // Loop preheaders can be good locations to spill registers. If the
841 // preheader is deleted and we create a critical edge, registers may be
842 // spilled in the loop body instead.
843 if (Opts.cgp_preheader_prot && isPreheader &&
844 !(BB->getSinglePredecessor() &&
846 return false;
847
848 // Skip merging if the block's successor is also a successor to any callbr
849 // that leads to this block.
850 // FIXME: Is this really needed? Is this a correctness issue?
851 for (BasicBlock *Pred : predecessors(BB)) {
852 if (isa<CallBrInst>(Pred->getTerminator()) &&
854 return false;
855 }
856
857 // Try to skip merging if the unique predecessor of BB is terminated by a
858 // switch or indirect branch instruction, and BB is used as an incoming block
859 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
860 // add COPY instructions in the predecessor of BB instead of BB (if it is not
861 // merged). Note that the critical edge created by merging such blocks wont be
862 // split in MachineSink because the jump table is not analyzable. By keeping
863 // such empty block (BB), ISel will place COPY instructions in BB, not in the
864 // predecessor of BB.
866 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
867 isa<IndirectBrInst>(Pred->getTerminator())))
868 return true;
869
870 if (BB->getTerminator() != &*BB->getFirstNonPHIOrPseudoProbe())
871 return true;
872
873 // We use a simple cost heuristic which determine skipping merging is
874 // profitable if the cost of skipping merging is less than the cost of
875 // merging : Cost(skipping merging) < Cost(merging BB), where the
876 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
877 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
878 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
879 // Freq(Pred) / Freq(BB) > 2.
880 // Note that if there are multiple empty blocks sharing the same incoming
881 // value for the PHIs in the DestBB, we consider them together. In such
882 // case, Cost(merging BB) will be the sum of their frequencies.
883
884 if (!isa<PHINode>(DestBB->begin()))
885 return true;
886
887 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
888
889 // Find all other incoming blocks from which incoming values of all PHIs in
890 // DestBB are the same as the ones from BB.
891 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
892 if (DestBBPred == BB)
893 continue;
894
895 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
896 return DestPN.getIncomingValueForBlock(BB) ==
897 DestPN.getIncomingValueForBlock(DestBBPred);
898 }))
899 SameIncomingValueBBs.insert(DestBBPred);
900 }
901
902 // See if all BB's incoming values are same as the value from Pred. In this
903 // case, no reason to skip merging because COPYs are expected to be place in
904 // Pred already.
905 if (SameIncomingValueBBs.count(Pred))
906 return true;
907
908 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
909 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
910
911 for (auto *SameValueBB : SameIncomingValueBBs)
912 if (SameValueBB->getUniquePredecessor() == Pred &&
913 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
914 BBFreq += BFI->getBlockFreq(SameValueBB);
915
916 std::optional<BlockFrequency> Limit =
917 BBFreq.mul(Opts.cgp_freq_ratio_to_skip_merge);
918 return !Limit || PredFreq <= *Limit;
919}
920
921/// Return true if we can merge BB into DestBB if there is a single
922/// unconditional branch between them, and BB contains no other non-phi
923/// instructions.
924bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
925 const BasicBlock *DestBB) const {
926 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
927 // the successor. If there are more complex condition (e.g. preheaders),
928 // don't mess around with them.
929 for (const PHINode &PN : BB->phis()) {
930 for (const User *U : PN.users()) {
931 const Instruction *UI = cast<Instruction>(U);
932 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
933 return false;
934 // If User is inside DestBB block and it is a PHINode then check
935 // incoming value. If incoming value is not from BB then this is
936 // a complex condition (e.g. preheaders) we want to avoid here.
937 if (UI->getParent() == DestBB) {
938 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
939 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
940 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
941 if (Insn && Insn->getParent() == BB &&
942 Insn->getParent() != UPN->getIncomingBlock(I))
943 return false;
944 }
945 }
946 }
947 }
948
949 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
950 // and DestBB may have conflicting incoming values for the block. If so, we
951 // can't merge the block.
952 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
953 if (!DestBBPN)
954 return true; // no conflict.
955
956 // Collect the preds of BB.
957 SmallPtrSet<const BasicBlock *, 16> BBPreds;
958 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
959 // It is faster to get preds from a PHI than with pred_iterator.
960 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
961 BBPreds.insert(BBPN->getIncomingBlock(i));
962 } else {
963 BBPreds.insert_range(predecessors(BB));
964 }
965
966 // Walk the preds of DestBB.
967 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
968 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
969 if (BBPreds.count(Pred)) { // Common predecessor?
970 for (const PHINode &PN : DestBB->phis()) {
971 const Value *V1 = PN.getIncomingValueForBlock(Pred);
972 const Value *V2 = PN.getIncomingValueForBlock(BB);
973
974 // If V2 is a phi node in BB, look up what the mapped value will be.
975 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
976 if (V2PN->getParent() == BB)
977 V2 = V2PN->getIncomingValueForBlock(Pred);
978
979 // If there is a conflict, bail out.
980 if (V1 != V2)
981 return false;
982 }
983 }
984 }
985
986 return true;
987}
988
989/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
990static void replaceAllUsesWith(Value *Old, Value *New,
992 bool IsHuge) {
993 auto *OldI = dyn_cast<Instruction>(Old);
994 if (OldI) {
995 for (Instruction::user_iterator UI = OldI->user_begin(),
996 E = OldI->user_end();
997 UI != E; ++UI) {
999 if (IsHuge)
1000 FreshBBs.insert(User->getParent());
1001 }
1002 }
1003 Old->replaceAllUsesWith(New);
1004}
1005
1006/// Eliminate a basic block that has only phi's and an unconditional branch in
1007/// it.
1008/// Indicate that the LoopInfo was modified only if it wasn't updated.
1009bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1010 UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
1011 BasicBlock *DestBB = BI->getSuccessor();
1012
1013 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1014 << *BB << *DestBB);
1015
1016 // If the destination block has a single pred, then this is a trivial edge,
1017 // just collapse it.
1018 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1019 if (SinglePred != DestBB) {
1020 assert(SinglePred == BB &&
1021 "Single predecessor not the same as predecessor");
1022 // Merge DestBB into SinglePred/BB and delete it.
1023 MergeBlockIntoPredecessor(DestBB, DTU, LI);
1024 // Note: BB(=SinglePred) will not be deleted on this path.
1025 // DestBB(=its single successor) is the one that was deleted.
1026 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1027
1028 if (IsHugeFunc) {
1029 // Update FreshBBs to optimize the merged BB.
1030 FreshBBs.insert(SinglePred);
1031 FreshBBs.erase(DestBB);
1032 }
1033 return false;
1034 }
1035 }
1036
1037 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1038 // to handle the new incoming edges it is about to have.
1039 for (PHINode &PN : DestBB->phis()) {
1040 // Remove the incoming value for BB, and remember it.
1041 Value *InVal = PN.removeIncomingValue(BB, false);
1042
1043 // Two options: either the InVal is a phi node defined in BB or it is some
1044 // value that dominates BB.
1045 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1046 if (InValPhi && InValPhi->getParent() == BB) {
1047 // Add all of the input values of the input PHI as inputs of this phi.
1048 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1049 PN.addIncoming(InValPhi->getIncomingValue(i),
1050 InValPhi->getIncomingBlock(i));
1051 } else {
1052 // Otherwise, add one instance of the dominating value for each edge that
1053 // we will be adding.
1054 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1055 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1056 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1057 } else {
1058 for (BasicBlock *Pred : predecessors(BB))
1059 PN.addIncoming(InVal, Pred);
1060 }
1061 }
1062 }
1063
1064 // Preserve loop Metadata.
1065 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1066 for (auto *Pred : predecessors(BB))
1067 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1068 }
1069
1070 // The PHIs are now updated, change everything that refers to BB to use
1071 // DestBB and remove BB.
1073 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1074 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1075 predecessors(DestBB));
1076 for (auto *Pred : predecessors(BB)) {
1077 if (!PredOfDestBB.contains(Pred)) {
1078 if (SeenPreds.insert(Pred).second)
1079 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1080 }
1081 }
1082 SeenPreds.clear();
1083 for (auto *Pred : predecessors(BB)) {
1084 if (SeenPreds.insert(Pred).second)
1085 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1086 }
1087 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1088 BB->replaceAllUsesWith(DestBB);
1089 DTU->applyUpdates(DTUpdates);
1090 DTU->deleteBB(BB);
1091 ++NumBlocksElim;
1092
1093 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1094 return true;
1095}
1096
1097// Computes a map of base pointer relocation instructions to corresponding
1098// derived pointer relocation instructions given a vector of all relocate calls
1100 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1102 &RelocateInstMap) {
1103 // Collect information in two maps: one primarily for locating the base object
1104 // while filling the second map; the second map is the final structure holding
1105 // a mapping between Base and corresponding Derived relocate calls
1107 for (auto *ThisRelocate : AllRelocateCalls) {
1108 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1109 ThisRelocate->getDerivedPtrIndex());
1110 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1111 }
1112 for (auto &Item : RelocateIdxMap) {
1113 std::pair<unsigned, unsigned> Key = Item.first;
1114 if (Key.first == Key.second)
1115 // Base relocation: nothing to insert
1116 continue;
1117
1118 GCRelocateInst *I = Item.second;
1119 auto BaseKey = std::make_pair(Key.first, Key.first);
1120
1121 // We're iterating over RelocateIdxMap so we cannot modify it.
1122 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1123 if (MaybeBase == RelocateIdxMap.end())
1124 // TODO: We might want to insert a new base object relocate and gep off
1125 // that, if there are enough derived object relocates.
1126 continue;
1127
1128 RelocateInstMap[MaybeBase->second].push_back(I);
1129 }
1130}
1131
1132// Accepts a GEP and extracts the operands into a vector provided they're all
1133// small integer constants
1135 SmallVectorImpl<Value *> &OffsetV) {
1136 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1137 // Only accept small constant integer operands
1138 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1139 if (!Op || Op->getZExtValue() > 20)
1140 return false;
1141 }
1142
1143 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1144 OffsetV.push_back(GEP->getOperand(i));
1145 return true;
1146}
1147
1148// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1149// replace, computes a replacement, and affects it.
1150static bool
1152 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1153 bool MadeChange = false;
1154 // We must ensure the relocation of derived pointer is defined after
1155 // relocation of base pointer. If we find a relocation corresponding to base
1156 // defined earlier than relocation of base then we move relocation of base
1157 // right before found relocation. We consider only relocation in the same
1158 // basic block as relocation of base. Relocations from other basic block will
1159 // be skipped by optimization and we do not care about them.
1160 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1161 &*R != RelocatedBase; ++R)
1162 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1163 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1164 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1165 RelocatedBase->moveBefore(RI->getIterator());
1166 MadeChange = true;
1167 break;
1168 }
1169
1170 for (GCRelocateInst *ToReplace : Targets) {
1171 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1172 "Not relocating a derived object of the original base object");
1173 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1174 // A duplicate relocate call. TODO: coalesce duplicates.
1175 continue;
1176 }
1177
1178 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1179 // Base and derived relocates are in different basic blocks.
1180 // In this case transform is only valid when base dominates derived
1181 // relocate. However it would be too expensive to check dominance
1182 // for each such relocate, so we skip the whole transformation.
1183 continue;
1184 }
1185
1186 Value *Base = ToReplace->getBasePtr();
1187 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1188 if (!Derived || Derived->getPointerOperand() != Base)
1189 continue;
1190
1192 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1193 continue;
1194
1195 // Create a Builder and replace the target callsite with a gep
1196 assert(RelocatedBase->getNextNode() &&
1197 "Should always have one since it's not a terminator");
1198
1199 // Insert after RelocatedBase
1200 IRBuilder<> Builder(RelocatedBase->getNextNode());
1201 Builder.disableGEPCanonicalization();
1202 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1203
1204 Value *Replacement = Builder.CreateGEP(Derived->getSourceElementType(),
1205 RelocatedBase, ArrayRef(OffsetV));
1206 Replacement->takeName(ToReplace);
1207 ToReplace->replaceAllUsesWith(Replacement);
1208 ToReplace->eraseFromParent();
1209
1210 MadeChange = true;
1211 }
1212 return MadeChange;
1213}
1214
1215// Turns this:
1216//
1217// %base = ...
1218// %ptr = gep %base + 15
1219// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1220// %base' = relocate(%tok, i32 4, i32 4)
1221// %ptr' = relocate(%tok, i32 4, i32 5)
1222// %val = load %ptr'
1223//
1224// into this:
1225//
1226// %base = ...
1227// %ptr = gep %base + 15
1228// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1229// %base' = gc.relocate(%tok, i32 4, i32 4)
1230// %ptr' = gep %base' + 15
1231// %val = load %ptr'
1232bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1233 bool MadeChange = false;
1234 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1235 for (auto *U : I.users())
1236 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1237 // Collect all the relocate calls associated with a statepoint
1238 AllRelocateCalls.push_back(Relocate);
1239
1240 // We need at least one base pointer relocation + one derived pointer
1241 // relocation to mangle
1242 if (AllRelocateCalls.size() < 2)
1243 return false;
1244
1245 // RelocateInstMap is a mapping from the base relocate instruction to the
1246 // corresponding derived relocate instructions
1247 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1248 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1249 if (RelocateInstMap.empty())
1250 return false;
1251
1252 for (auto &Item : RelocateInstMap)
1253 // Item.first is the RelocatedBase to offset against
1254 // Item.second is the vector of Targets to replace
1255 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1256 return MadeChange;
1257}
1258
1259/// Sink the specified cast instruction into its user blocks.
1260static bool SinkCast(CastInst *CI) {
1261 BasicBlock *DefBB = CI->getParent();
1262
1263 /// InsertedCasts - Only insert a cast in each block once.
1265
1266 bool MadeChange = false;
1267 for (Instruction::user_iterator UI = CI->user_begin(), E = CI->user_end();
1268 UI != E;) {
1269 Use &TheUse = UI.getUse();
1271
1272 // Figure out which BB this cast is used in. For PHI's this is the
1273 // appropriate predecessor block.
1274 BasicBlock *UserBB = User->getParent();
1275 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1276 UserBB = PN->getIncomingBlock(TheUse);
1277 }
1278
1279 // Preincrement use iterator so we don't invalidate it.
1280 ++UI;
1281
1282 // The first insertion point of a block containing an EH pad is after the
1283 // pad. If the pad is the user, we cannot sink the cast past the pad.
1284 if (User->isEHPad())
1285 continue;
1286
1287 // If the block selected to receive the cast is an EH pad that does not
1288 // allow non-PHI instructions before the terminator, we can't sink the
1289 // cast.
1290 if (UserBB->getTerminator()->isEHPad())
1291 continue;
1292
1293 // If this user is in the same block as the cast, don't change the cast.
1294 if (UserBB == DefBB)
1295 continue;
1296
1297 // If we have already inserted a cast into this block, use it.
1298 CastInst *&InsertedCast = InsertedCasts[UserBB];
1299
1300 if (!InsertedCast) {
1301 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1302 assert(InsertPt != UserBB->end());
1303 InsertedCast = cast<CastInst>(CI->clone());
1304 InsertedCast->insertBefore(*UserBB, InsertPt);
1305 }
1306
1307 // Replace a use of the cast with a use of the new cast.
1308 TheUse = InsertedCast;
1309 MadeChange = true;
1310 ++NumCastUses;
1311 }
1312
1313 // If we removed all uses, nuke the cast.
1314 if (CI->use_empty()) {
1315 salvageDebugInfo(*CI);
1316 CI->eraseFromParent();
1317 MadeChange = true;
1318 }
1319
1320 return MadeChange;
1321}
1322
1323/// Hoists bitcasts to the source block to reduce register pressure
1325 const DataLayout &DL) {
1326 auto *SrcInst = dyn_cast<Instruction>(BCI->getOperand(0));
1327 if (!SrcInst || SrcInst->getParent() == BCI->getParent() ||
1328 SrcInst->isTerminator())
1329 return false;
1330
1331 Type *DestTy = BCI->getType();
1332 Type *SrcTy = SrcInst->getType();
1333 EVT SrcVT = TLI.getValueType(DL, SrcTy);
1334 EVT DestVT = TLI.getValueType(DL, DestTy);
1335
1336 // Bail out on scalable vectors and illegal destination types
1337 if (SrcVT.isScalableVector() || DestVT.isScalableVector())
1338 return false;
1339
1340 // Only hoist if it reduces physical register count
1341 if (TLI.getNumRegisters(BCI->getContext(), SrcVT) <=
1342 TLI.getNumRegisters(BCI->getContext(), DestVT))
1343 return false;
1344
1345 // Block large or cross-domain scalars to prevent spills and broken atomics.
1346 bool IsCrossDomain = DestTy->isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1347
1348 // A scalar is large if it requires more than one native register.
1349 unsigned NativeWidth = DL.getPointerSizeInBits();
1350 bool IsLargeScalar =
1351 !DestTy->isVectorTy() &&
1352 DL.getTypeSizeInBits(DestTy).getFixedValue() > NativeWidth;
1353
1354 if (IsCrossDomain || IsLargeScalar)
1355 return false;
1356
1357 // Hoist the bitcast
1358 BasicBlock *SrcBB = SrcInst->getParent();
1359 auto InsertPt = isa<PHINode>(SrcInst) ? SrcBB->getFirstInsertionPt()
1360 : std::next(SrcInst->getIterator());
1361 BCI->moveBefore(*SrcBB, InsertPt);
1362
1363 return true;
1364}
1365
1366/// If the specified cast instruction is a noop copy (e.g. it's casting from
1367/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1368/// reduce the number of virtual registers that must be created and coalesced.
1369///
1370/// Return true if any changes are made.
1372 const DataLayout &DL) {
1373 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1374 // than sinking only nop casts, but is helpful on some platforms.
1375 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1376 if (!TLI.isFreeAddrSpaceCast(DL, ASC->getSrcAddressSpace(),
1377 ASC->getDestAddressSpace()))
1378 return false;
1379 }
1380
1381 // If this is a noop copy,
1382 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1383 EVT DstVT = TLI.getValueType(DL, CI->getType());
1384
1385 // This is an fp<->int conversion?
1386 if (SrcVT.isInteger() != DstVT.isInteger())
1387 return false;
1388
1389 // If this is an extension, it will be a zero or sign extension, which
1390 // isn't a noop.
1391 if (SrcVT.bitsLT(DstVT))
1392 return false;
1393
1394 // If these values will be promoted, find out what they will be promoted
1395 // to. This helps us consider truncates on PPC as noop copies when they
1396 // are.
1397 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1399 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1400 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1402 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1403
1404 // If, after promotion, these are the same types, this is a noop copy.
1405 if (SrcVT != DstVT)
1406 return false;
1407
1408 return SinkCast(CI);
1409}
1410
1411// Match a simple increment by constant operation. Note that if a sub is
1412// matched, the step is negated (as if the step had been canonicalized to
1413// an add, even though we leave the instruction alone.)
1414static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1415 Constant *&Step) {
1416 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1418 m_Instruction(LHS), m_Constant(Step)))))
1419 return true;
1420 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1422 m_Instruction(LHS), m_Constant(Step))))) {
1423 Step = ConstantExpr::getNeg(Step);
1424 return true;
1425 }
1426 return false;
1427}
1428
1429/// If given \p PN is an inductive variable with value IVInc coming from the
1430/// backedge, and on each iteration it gets increased by Step, return pair
1431/// <IVInc, Step>. Otherwise, return std::nullopt.
1432static std::optional<std::pair<Instruction *, Constant *>>
1433getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1434 const Loop *L = LI->getLoopFor(PN->getParent());
1435 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1436 return std::nullopt;
1437 auto *IVInc =
1438 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1439 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1440 return std::nullopt;
1441 Instruction *LHS = nullptr;
1442 Constant *Step = nullptr;
1443 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1444 return std::make_pair(IVInc, Step);
1445 return std::nullopt;
1446}
1447
1448static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1449 auto *I = dyn_cast<Instruction>(V);
1450 if (!I)
1451 return false;
1452 Instruction *LHS = nullptr;
1453 Constant *Step = nullptr;
1454 if (!matchIncrement(I, LHS, Step))
1455 return false;
1456 if (auto *PN = dyn_cast<PHINode>(LHS))
1457 if (auto IVInc = getIVIncrement(PN, LI))
1458 return IVInc->first == I;
1459 return false;
1460}
1461
1462bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1463 Value *Arg0, Value *Arg1,
1464 CmpInst *Cmp,
1465 Intrinsic::ID IID) {
1466 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1467 if (!isIVIncrement(BO, LI))
1468 return false;
1469 const Loop *L = LI->getLoopFor(BO->getParent());
1470 assert(L && "L should not be null after isIVIncrement()");
1471 // Do not risk on moving increment into a child loop.
1472 if (LI->getLoopFor(Cmp->getParent()) != L)
1473 return false;
1474
1475 // Finally, we need to ensure that the insert point will dominate all
1476 // existing uses of the increment.
1477
1478 auto &DT = getDT();
1479 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1480 // If we're moving up the dom tree, all uses are trivially dominated.
1481 // (This is the common case for code produced by LSR.)
1482 return true;
1483
1484 // Otherwise, special case the single use in the phi recurrence.
1485 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1486 };
1487 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1488 // We used to use a dominator tree here to allow multi-block optimization.
1489 // But that was problematic because:
1490 // 1. It could cause a perf regression by hoisting the math op into the
1491 // critical path.
1492 // 2. It could cause a perf regression by creating a value that was live
1493 // across multiple blocks and increasing register pressure.
1494 // 3. Use of a dominator tree could cause large compile-time regression.
1495 // This is because we recompute the DT on every change in the main CGP
1496 // run-loop. The recomputing is probably unnecessary in many cases, so if
1497 // that was fixed, using a DT here would be ok.
1498 //
1499 // There is one important particular case we still want to handle: if BO is
1500 // the IV increment. Important properties that make it profitable:
1501 // - We can speculate IV increment anywhere in the loop (as long as the
1502 // indvar Phi is its only user);
1503 // - Upon computing Cmp, we effectively compute something equivalent to the
1504 // IV increment (despite it loops differently in the IR). So moving it up
1505 // to the cmp point does not really increase register pressure.
1506 return false;
1507 }
1508
1509 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1510 if (BO->getOpcode() == Instruction::Add &&
1511 IID == Intrinsic::usub_with_overflow) {
1512 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1514 }
1515
1516 // Insert at the first instruction of the pair.
1517 Instruction *InsertPt = nullptr;
1518 for (Instruction &Iter : *Cmp->getParent()) {
1519 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1520 // the overflow intrinsic are defined.
1521 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1522 InsertPt = &Iter;
1523 break;
1524 }
1525 }
1526 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1527
1528 IRBuilder<> Builder(InsertPt);
1529 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1530 if (BO->getOpcode() != Instruction::Xor) {
1531 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1532 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1533 } else
1534 assert(BO->hasOneUse() &&
1535 "Patterns with XOr should use the BO only in the compare");
1536 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1537 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1538 Cmp->eraseFromParent();
1539 BO->eraseFromParent();
1540 return true;
1541}
1542
1543/// Match special-case patterns that check for unsigned add overflow.
1545 BinaryOperator *&Add) {
1546 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1547 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1548 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1549
1550 // We are not expecting non-canonical/degenerate code. Just bail out.
1551 if (isa<Constant>(A))
1552 return false;
1553
1554 ICmpInst::Predicate Pred = Cmp->getPredicate();
1555 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1556 B = ConstantInt::get(B->getType(), 1);
1557 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1558 B = Constant::getAllOnesValue(B->getType());
1559 else
1560 return false;
1561
1562 // Check the users of the variable operand of the compare looking for an add
1563 // with the adjusted constant.
1564 for (User *U : A->users()) {
1565 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1567 return true;
1568 }
1569 }
1570 return false;
1571}
1572
1573/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1574/// intrinsic. Return true if any changes were made.
1575bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1576 ModifyDT &ModifiedDT) {
1577 bool EdgeCase = false;
1578 Value *A, *B;
1579 BinaryOperator *Add;
1580 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1582 return false;
1583 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1584 A = Add->getOperand(0);
1585 B = Add->getOperand(1);
1586 EdgeCase = true;
1587 }
1588
1590 TLI->getValueType(*DL, Add->getType()),
1591 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1592 return false;
1593
1594 // We don't want to move around uses of condition values this late, so we
1595 // check if it is legal to create the call to the intrinsic in the basic
1596 // block containing the icmp.
1597 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1598 return false;
1599
1600 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1601 Intrinsic::uadd_with_overflow))
1602 return false;
1603
1604 // Reset callers - do not crash by iterating over a dead instruction.
1605 ModifiedDT = ModifyDT::ModifyInstDT;
1606 return true;
1607}
1608
1609bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1610 ModifyDT &ModifiedDT) {
1611 // We are not expecting non-canonical/degenerate code. Just bail out.
1612 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1613 if (isa<Constant>(A) && isa<Constant>(B))
1614 return false;
1615
1616 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1617 ICmpInst::Predicate Pred = Cmp->getPredicate();
1618 if (Pred == ICmpInst::ICMP_UGT) {
1619 std::swap(A, B);
1620 Pred = ICmpInst::ICMP_ULT;
1621 }
1622 // Convert special-case: (A == 0) is the same as (A u< 1).
1623 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1624 B = ConstantInt::get(B->getType(), 1);
1625 Pred = ICmpInst::ICMP_ULT;
1626 }
1627 // Convert special-case: (A != 0) is the same as (0 u< A).
1628 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1629 std::swap(A, B);
1630 Pred = ICmpInst::ICMP_ULT;
1631 }
1632 if (Pred != ICmpInst::ICMP_ULT)
1633 return false;
1634
1635 // Walk the users of a variable operand of a compare looking for a subtract or
1636 // add with that same operand. Also match the 2nd operand of the compare to
1637 // the add/sub, but that may be a negated constant operand of an add.
1638 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1639 BinaryOperator *Sub = nullptr;
1640 for (User *U : CmpVariableOperand->users()) {
1641 // A - B, A u< B --> usubo(A, B)
1642 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1644 break;
1645 }
1646
1647 // A + (-C), A u< C (canonicalized form of (sub A, C))
1648 const APInt *CmpC, *AddC;
1649 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1650 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1652 break;
1653 }
1654 }
1655 if (!Sub)
1656 return false;
1657
1659 TLI->getValueType(*DL, Sub->getType()),
1660 Sub->hasNUsesOrMore(1)))
1661 return false;
1662
1663 // We don't want to move around uses of condition values this late, so we
1664 // check if it is legal to create the call to the intrinsic in the basic
1665 // block containing the icmp.
1666 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1667 return false;
1668
1669 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1670 Cmp, Intrinsic::usub_with_overflow))
1671 return false;
1672
1673 // Reset callers - do not crash by iterating over a dead instruction.
1674 ModifiedDT = ModifyDT::ModifyInstDT;
1675 return true;
1676}
1677
1678// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1679// The same transformation exists in DAG combiner, but we repeat it here because
1680// DAG builder can break the pattern by moving icmp into a successor block.
1681bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1682 CmpPredicate Pred;
1683 Value *X;
1684 const APInt *C;
1685
1686 // (icmp (ctpop x), c)
1688 return false;
1689
1690 // We're only interested in "is power of 2 [or zero]" patterns.
1691 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(Pred) && *C == 1;
1692 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1693 (Pred == CmpInst::ICMP_UGT && *C == 1);
1694 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1695 return false;
1696
1697 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1698 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1699 // and otherwise expand ctpop into a few simple instructions.
1700 Type *OpTy = X->getType();
1701 if (TLI->isCtpopFast(TLI->getValueType(*DL, OpTy))) {
1702 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1703 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *DL))
1704 return false;
1705
1706 // ctpop(x) == 1 -> ctpop(x) u< 2
1707 // ctpop(x) != 1 -> ctpop(x) u> 1
1708 if (Pred == ICmpInst::ICMP_EQ) {
1709 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1710 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1711 } else {
1712 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1713 }
1714 return true;
1715 }
1716
1717 Value *NewCmp;
1718 if (IsPowerOf2OrZeroTest ||
1719 (IsStrictlyPowerOf2Test && isKnownNonZero(Cmp->getOperand(0), *DL))) {
1720 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1721 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1722 IRBuilder<> Builder(Cmp);
1723 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1724 Value *And = Builder.CreateAnd(X, Sub);
1725 CmpInst::Predicate NewPred =
1728 : CmpInst::ICMP_NE;
1729 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(OpTy));
1730 } else {
1731 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1732 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1733 IRBuilder<> Builder(Cmp);
1734 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1735 Value *Xor = Builder.CreateXor(X, Sub);
1736 CmpInst::Predicate NewPred =
1738 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1739 }
1740
1741 Cmp->replaceAllUsesWith(NewCmp);
1743 return true;
1744}
1745
1746/// Sink the given CmpInst into user blocks to reduce the number of virtual
1747/// registers that must be created and coalesced. This is a clear win except on
1748/// targets with multiple condition code registers (PowerPC), where it might
1749/// lose; some adjustment may be wanted there.
1750///
1751/// Return true if any changes are made.
1753 const DataLayout &DL) {
1754 if (TLI.hasMultipleConditionRegisters(EVT::getEVT(Cmp->getType())))
1755 return false;
1756
1757 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1758 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1759 return false;
1760
1761 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1762 return isa<PHINode>(U) ||
1763 cast<Instruction>(U)->getParent() == Cmp->getParent();
1764 });
1765
1766 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1767 // another BB.
1768 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1769 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1770 DL.getLargestLegalIntTypeSizeInBits())
1771 return false;
1772
1773 // Only insert a cmp in each block once.
1775
1776 bool MadeChange = false;
1777 for (Instruction::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1778 UI != E;) {
1779 Use &TheUse = UI.getUse();
1781
1782 // Preincrement use iterator so we don't invalidate it.
1783 ++UI;
1784
1785 // Don't bother for PHI nodes.
1786 if (isa<PHINode>(User))
1787 continue;
1788
1789 // Figure out which BB this cmp is used in.
1790 BasicBlock *UserBB = User->getParent();
1791 BasicBlock *DefBB = Cmp->getParent();
1792
1793 // If this user is in the same block as the cmp, don't change the cmp.
1794 if (UserBB == DefBB)
1795 continue;
1796
1797 // If we have already inserted a cmp into this block, use it.
1798 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1799
1800 if (!InsertedCmp) {
1801 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1802 assert(InsertPt != UserBB->end());
1803 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1804 Cmp->getOperand(0), Cmp->getOperand(1), "");
1805 InsertedCmp->insertBefore(*UserBB, InsertPt);
1806 // Propagate the debug info.
1807 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1808 }
1809
1810 // Replace a use of the cmp with a use of the new cmp.
1811 TheUse = InsertedCmp;
1812 MadeChange = true;
1813 ++NumCmpUses;
1814 }
1815
1816 // If we removed all uses, nuke the cmp.
1817 if (Cmp->use_empty()) {
1818 Cmp->eraseFromParent();
1819 MadeChange = true;
1820 }
1821
1822 return MadeChange;
1823}
1824
1825/// For pattern like:
1826///
1827/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1828/// ...
1829/// DomBB:
1830/// ...
1831/// br DomCond, TrueBB, CmpBB
1832/// CmpBB: (with DomBB being the single predecessor)
1833/// ...
1834/// Cmp = icmp eq CmpOp0, CmpOp1
1835/// ...
1836///
1837/// It would use two comparison on targets that lowering of icmp sgt/slt is
1838/// different from lowering of icmp eq (PowerPC). This function try to convert
1839/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1840/// After that, DomCond and Cmp can use the same comparison so reduce one
1841/// comparison.
1842///
1843/// Return true if any changes are made.
1845 bool EnableICmpEqToICmpSt) {
1846 if (!EnableICmpEqToICmpSt && TLI.isEqualityCmpFoldedWithSignedCmp())
1847 return false;
1848
1849 ICmpInst::Predicate Pred = Cmp->getPredicate();
1850 if (Pred != ICmpInst::ICMP_EQ)
1851 return false;
1852
1853 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
1854 // icmp slt/sgt would introduce more redundant LLVM IR.
1855 for (User *U : Cmp->users()) {
1856 if (isa<CondBrInst>(U))
1857 continue;
1858 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1859 continue;
1860 return false;
1861 }
1862
1863 // This is a cheap/incomplete check for dominance - just match a single
1864 // predecessor with a conditional branch.
1865 BasicBlock *CmpBB = Cmp->getParent();
1866 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1867 if (!DomBB)
1868 return false;
1869
1870 // We want to ensure that the only way control gets to the comparison of
1871 // interest is that a less/greater than comparison on the same operands is
1872 // false.
1873 Value *DomCond;
1874 BasicBlock *TrueBB, *FalseBB;
1875 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1876 return false;
1877 if (CmpBB != FalseBB)
1878 return false;
1879
1880 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1881 CmpPredicate DomPred;
1882 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1883 return false;
1884 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1885 return false;
1886
1887 // Convert the equality comparison to the opposite of the dominating
1888 // comparison and swap the direction for all branch/select users.
1889 // We have conceptually converted:
1890 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1891 // to
1892 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1893 // And similarly for branches.
1894 for (User *U : Cmp->users()) {
1895 if (auto *BI = dyn_cast<CondBrInst>(U)) {
1896 BI->swapSuccessors();
1897 continue;
1898 }
1899 if (auto *SI = dyn_cast<SelectInst>(U)) {
1900 // Swap operands
1901 SI->swapValues();
1902 SI->swapProfMetadata();
1903 continue;
1904 }
1905 llvm_unreachable("Must be a branch or a select");
1906 }
1907 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1908 return true;
1909}
1910
1911/// Many architectures use the same instruction for both subtract and cmp. Try
1912/// to swap cmp operands to match subtract operations to allow for CSE.
1914 Value *Op0 = Cmp->getOperand(0);
1915 Value *Op1 = Cmp->getOperand(1);
1916 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
1917 isa<Constant>(Op1) || Op0 == Op1)
1918 return false;
1919
1920 // If a subtract already has the same operands as a compare, swapping would be
1921 // bad. If a subtract has the same operands as a compare but in reverse order,
1922 // then swapping is good.
1923 int GoodToSwap = 0;
1924 unsigned NumInspected = 0;
1925 for (const User *U : Op0->users()) {
1926 // Avoid walking many users.
1927 if (++NumInspected > 128)
1928 return false;
1929 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
1930 GoodToSwap++;
1931 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
1932 GoodToSwap--;
1933 }
1934
1935 if (GoodToSwap > 0) {
1936 Cmp->swapOperands();
1937 return true;
1938 }
1939 return false;
1940}
1941
1943 const DataLayout &DL) {
1944 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
1945 if (!FCmp)
1946 return false;
1947
1948 // Don't fold if the target offers free fabs and the predicate is legal.
1949 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
1950 if (TLI.isFAbsFree(VT) &&
1951 TLI.isCondCodeLegal(getFCmpCondCode(FCmp->getPredicate()),
1952 VT.getSimpleVT()))
1953 return false;
1954
1955 // Reverse the canonicalization if it is a FP class test
1956 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
1957 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
1958 };
1959 auto [ClassVal, ClassTest] =
1960 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1961 FCmp->getOperand(0), FCmp->getOperand(1));
1962 if (!ClassVal)
1963 return false;
1964
1965 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
1966 return false;
1967
1968 IRBuilder<> Builder(Cmp);
1969 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
1970 Cmp->replaceAllUsesWith(IsFPClass);
1972 return true;
1973}
1974
1976 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
1977 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
1978 Value *Incr, *RemAmt;
1979 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
1980 if (!match(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
1981 return false;
1982
1983 Value *AddInst, *AddOffset;
1984 // Find out loop increment PHI.
1985 PHINode *PN = dyn_cast<PHINode>(Incr);
1986 if (PN != nullptr) {
1987 AddInst = nullptr;
1988 AddOffset = nullptr;
1989 } else {
1990 // Search through a NUW add on top of the loop increment.
1991 if (!match(Incr, m_c_NUWAdd(m_Phi(PN), m_Value(AddOffset))))
1992 return false;
1993 AddInst = Incr;
1994 }
1995
1996 if (!PN)
1997 return false;
1998
1999 // This isn't strictly necessary, what we really need is one increment and any
2000 // amount of initial values all being the same.
2001 if (PN->getNumIncomingValues() != 2)
2002 return false;
2003
2004 // Only trivially analyzable loops.
2005 Loop *L = LI->getLoopFor(PN->getParent());
2006 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2007 return false;
2008
2009 // Req that the remainder is in the loop
2010 if (!L->contains(Rem))
2011 return false;
2012
2013 // Only works if the remainder amount is a loop invaraint
2014 if (!L->isLoopInvariant(RemAmt))
2015 return false;
2016
2017 // Only works if the AddOffset is a loop invaraint
2018 if (AddOffset && !L->isLoopInvariant(AddOffset))
2019 return false;
2020
2021 // Is the PHI a loop increment?
2022 auto LoopIncrInfo = getIVIncrement(PN, LI);
2023 if (!LoopIncrInfo)
2024 return false;
2025
2026 // We need remainder_amount % increment_amount to be zero. Increment of one
2027 // satisfies that without any special logic and is overwhelmingly the common
2028 // case.
2029 if (!match(LoopIncrInfo->second, m_One()))
2030 return false;
2031
2032 // Need the increment to not overflow.
2033 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), m_Value())))
2034 return false;
2035
2036 // Set output variables.
2037 RemAmtOut = RemAmt;
2038 LoopIncrPNOut = PN;
2039 AddInstOut = AddInst;
2040 AddOffsetOut = AddOffset;
2041
2042 return true;
2043}
2044
2045// Try to transform:
2046//
2047// for(i = Start; i < End; ++i)
2048// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2049//
2050// ->
2051//
2052// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2053// for(i = Start; i < End; ++i, ++rem)
2054// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2056 const LoopInfo *LI,
2058 bool IsHuge) {
2059 Value *AddOffset, *RemAmt, *AddInst;
2060 PHINode *LoopIncrPN;
2061 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2062 AddOffset, LoopIncrPN))
2063 return false;
2064
2065 // Only non-constant remainder as the extra IV is probably not profitable
2066 // in that case.
2067 //
2068 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2069 // we can rule out register pressure and ensure this `urem` is executed each
2070 // iteration, its probably profitable to handle the const case as well.
2071 //
2072 // Potential TODO(2): Should we have a check for how "nested" this remainder
2073 // operation is? The new code runs every iteration so if the remainder is
2074 // guarded behind unlikely conditions this might not be worth it.
2075 if (match(RemAmt, m_ImmConstant()))
2076 return false;
2077
2078 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2079 Value *Start = LoopIncrPN->getIncomingValueForBlock(L->getLoopPreheader());
2080 // If we have add create initial value for remainder.
2081 // The logic here is:
2082 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2083 //
2084 // Only proceed if the expression simplifies (otherwise we can't fully
2085 // optimize out the urem).
2086 if (AddInst) {
2087 assert(AddOffset && "We found an add but missing values");
2088 // Without dom-condition/assumption cache we aren't likely to get much out
2089 // of a context instruction.
2090 Start = simplifyAddInst(Start, AddOffset,
2091 match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2092 /*IsNUW=*/true, *DL);
2093 if (!Start)
2094 return false;
2095 }
2096
2097 // If we can't fully optimize out the `rem`, skip this transform.
2098 Start = simplifyURemInst(Start, RemAmt, *DL);
2099 if (!Start)
2100 return false;
2101
2102 // Create new remainder with induction variable.
2103 Type *Ty = Rem->getType();
2104 IRBuilder<> Builder(LoopIncrPN);
2105 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2106
2107 Builder.SetInsertPoint(cast<Instruction>(
2108 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2109 // `(add (urem x, y), 1)` is always nuw.
2110 Value *RemAdd = Builder.CreateNUWAdd(NewRem, ConstantInt::get(Ty, 1));
2111 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2112 Value *RemSel =
2113 Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2114 if (auto *SI = dyn_cast<SelectInst>(RemSel))
2116
2117 NewRem->addIncoming(Start, L->getLoopPreheader());
2118 NewRem->addIncoming(RemSel, L->getLoopLatch());
2119
2120 // Insert all touched BBs.
2121 FreshBBs.insert(LoopIncrPN->getParent());
2122 FreshBBs.insert(L->getLoopLatch());
2123 FreshBBs.insert(Rem->getParent());
2124 if (AddInst)
2125 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2126 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2127 Rem->eraseFromParent();
2128 if (AddInst && AddInst->use_empty())
2129 cast<Instruction>(AddInst)->eraseFromParent();
2130 return true;
2131}
2132
2133bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2134 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHugeFunc))
2135 return true;
2136 return false;
2137}
2138
2139bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2140 if (sinkCmpExpression(Cmp, *TLI, *DL))
2141 return true;
2142
2143 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2144 return true;
2145
2146 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2147 return true;
2148
2149 if (unfoldPowerOf2Test(Cmp))
2150 return true;
2151
2152 if (foldICmpWithDominatingICmp(Cmp, *TLI, Opts.cgp_icmp_eq2icmp_st))
2153 return true;
2154
2156 return true;
2157
2158 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
2159 return true;
2160
2161 return false;
2162}
2163
2164/// Duplicate and sink the given 'and' instruction into user blocks where it is
2165/// used in a compare to allow isel to generate better code for targets where
2166/// this operation can be combined.
2167///
2168/// Return true if any changes are made.
2170 SetOfInstrs &InsertedInsts) {
2171 // Double-check that we're not trying to optimize an instruction that was
2172 // already optimized by some other part of this pass.
2173 assert(!InsertedInsts.count(AndI) &&
2174 "Attempting to optimize already optimized and instruction");
2175 (void)InsertedInsts;
2176
2177 // Nothing to do for single use in same basic block.
2178 if (AndI->hasOneUse() &&
2179 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
2180 return false;
2181
2182 // Try to avoid cases where sinking/duplicating is likely to increase register
2183 // pressure.
2184 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2185 !isa<ConstantInt>(AndI->getOperand(1)) &&
2186 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2187 return false;
2188
2189 for (auto *U : AndI->users()) {
2191
2192 // Only sink 'and' feeding icmp with 0.
2193 if (!isa<ICmpInst>(User))
2194 return false;
2195
2196 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2197 if (!CmpC || !CmpC->isZero())
2198 return false;
2199 }
2200
2201 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2202 return false;
2203
2204 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2205 LLVM_DEBUG(AndI->getParent()->dump());
2206
2207 // Push the 'and' into the same block as the icmp 0. There should only be
2208 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2209 // others, so we don't need to keep track of which BBs we insert into.
2210 for (Instruction::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2211 UI != E;) {
2212 Use &TheUse = UI.getUse();
2214
2215 // Preincrement use iterator so we don't invalidate it.
2216 ++UI;
2217
2218 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2219
2220 // Keep the 'and' in the same place if the use is already in the same block.
2221 Instruction *InsertPt =
2222 User->getParent() == AndI->getParent() ? AndI : User;
2223 Instruction *InsertedAnd = BinaryOperator::Create(
2224 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2225 InsertPt->getIterator());
2226 // Propagate the debug info.
2227 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2228
2229 // Replace a use of the 'and' with a use of the new 'and'.
2230 TheUse = InsertedAnd;
2231 ++NumAndUses;
2232 LLVM_DEBUG(User->getParent()->dump());
2233 }
2234
2235 // We removed all uses, nuke the and.
2236 AndI->eraseFromParent();
2237 return true;
2238}
2239
2240/// Check if the candidates could be combined with a shift instruction, which
2241/// includes:
2242/// 1. Truncate instruction
2243/// 2. And instruction and the imm is a mask of the low bits:
2244/// imm & (imm+1) == 0
2246 if (!isa<TruncInst>(User)) {
2247 if (User->getOpcode() != Instruction::And ||
2249 return false;
2250
2251 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2252
2253 if ((Cimm & (Cimm + 1)).getBoolValue())
2254 return false;
2255 }
2256 return true;
2257}
2258
2259/// Sink both shift and truncate instruction to the use of truncate's BB.
2260static bool
2263 const TargetLowering &TLI, const DataLayout &DL) {
2264 BasicBlock *UserBB = User->getParent();
2266 auto *TruncI = cast<TruncInst>(User);
2267 bool MadeChange = false;
2268
2269 for (Instruction::user_iterator TruncUI = TruncI->user_begin(),
2270 TruncE = TruncI->user_end();
2271 TruncUI != TruncE;) {
2272
2273 Use &TruncTheUse = TruncUI.getUse();
2274 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2275 // Preincrement use iterator so we don't invalidate it.
2276
2277 ++TruncUI;
2278
2279 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2280 if (!ISDOpcode)
2281 continue;
2282
2283 // If the use is actually a legal node, there will not be an
2284 // implicit truncate.
2285 // FIXME: always querying the result type is just an
2286 // approximation; some nodes' legality is determined by the
2287 // operand or other means. There's no good way to find out though.
2288 if (TLI.isOperationLegalOrCustom(
2289 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2290 continue;
2291
2292 // Don't bother for PHI nodes.
2293 if (isa<PHINode>(TruncUser))
2294 continue;
2295
2296 BasicBlock *TruncUserBB = TruncUser->getParent();
2297
2298 if (UserBB == TruncUserBB)
2299 continue;
2300
2301 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2302 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2303
2304 if (!InsertedShift && !InsertedTrunc) {
2305 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2306 assert(InsertPt != TruncUserBB->end());
2307 // Sink the shift
2308 if (ShiftI->getOpcode() == Instruction::AShr)
2309 InsertedShift =
2310 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2311 else
2312 InsertedShift =
2313 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2314 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2315 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2316
2317 // Sink the trunc
2318 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2319 TruncInsertPt++;
2320 // It will go ahead of any debug-info.
2321 TruncInsertPt.setHeadBit(true);
2322 assert(TruncInsertPt != TruncUserBB->end());
2323
2324 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2325 TruncI->getType(), "");
2326 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2327 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2328
2329 MadeChange = true;
2330
2331 TruncTheUse = InsertedTrunc;
2332 }
2333 }
2334 return MadeChange;
2335}
2336
2337/// Sink the shift *right* instruction into user blocks if the uses could
2338/// potentially be combined with this shift instruction and generate BitExtract
2339/// instruction. It will only be applied if the architecture supports BitExtract
2340/// instruction. Here is an example:
2341/// BB1:
2342/// %x.extract.shift = lshr i64 %arg1, 32
2343/// BB2:
2344/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2345/// ==>
2346///
2347/// BB2:
2348/// %x.extract.shift.1 = lshr i64 %arg1, 32
2349/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2350///
2351/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2352/// instruction.
2353/// Return true if any changes are made.
2355 const TargetLowering &TLI,
2356 const DataLayout &DL) {
2357 BasicBlock *DefBB = ShiftI->getParent();
2358
2359 /// Only insert instructions in each block once.
2361
2362 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2363
2364 bool MadeChange = false;
2365 for (Instruction::user_iterator UI = ShiftI->user_begin(),
2366 E = ShiftI->user_end();
2367 UI != E;) {
2368 Use &TheUse = UI.getUse();
2370 // Preincrement use iterator so we don't invalidate it.
2371 ++UI;
2372
2373 // Don't bother for PHI nodes.
2374 if (isa<PHINode>(User))
2375 continue;
2376
2378 continue;
2379
2380 BasicBlock *UserBB = User->getParent();
2381
2382 if (UserBB == DefBB) {
2383 // If the shift and truncate instruction are in the same BB. The use of
2384 // the truncate(TruncUse) may still introduce another truncate if not
2385 // legal. In this case, we would like to sink both shift and truncate
2386 // instruction to the BB of TruncUse.
2387 // for example:
2388 // BB1:
2389 // i64 shift.result = lshr i64 opnd, imm
2390 // trunc.result = trunc shift.result to i16
2391 //
2392 // BB2:
2393 // ----> We will have an implicit truncate here if the architecture does
2394 // not have i16 compare.
2395 // cmp i16 trunc.result, opnd2
2396 //
2397 if (isa<TruncInst>(User) &&
2398 shiftIsLegal
2399 // If the type of the truncate is legal, no truncate will be
2400 // introduced in other basic blocks.
2401 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2402 MadeChange =
2403 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2404
2405 continue;
2406 }
2407 // If we have already inserted a shift into this block, use it.
2408 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2409
2410 if (!InsertedShift) {
2411 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2412 assert(InsertPt != UserBB->end());
2413
2414 if (ShiftI->getOpcode() == Instruction::AShr)
2415 InsertedShift =
2416 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2417 else
2418 InsertedShift =
2419 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2420 InsertedShift->insertBefore(*UserBB, InsertPt);
2421 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2422
2423 MadeChange = true;
2424 }
2425
2426 // Replace a use of the shift with a use of the new shift.
2427 TheUse = InsertedShift;
2428 }
2429
2430 // If we removed all uses, or there are none, nuke the shift.
2431 if (ShiftI->use_empty()) {
2432 salvageDebugInfo(*ShiftI);
2433 ShiftI->eraseFromParent();
2434 MadeChange = true;
2435 }
2436
2437 return MadeChange;
2438}
2439
2440/// If counting leading or trailing zeros is an expensive operation and a zero
2441/// input is defined, add a check for zero to avoid calling the intrinsic.
2442///
2443/// We want to transform:
2444/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2445///
2446/// into:
2447/// entry:
2448/// %cmpz = icmp eq i64 %A, 0
2449/// br i1 %cmpz, label %cond.end, label %cond.false
2450/// cond.false:
2451/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2452/// br label %cond.end
2453/// cond.end:
2454/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2455///
2456/// If the transform is performed, return true and set ModifiedDT to true.
2457static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2458 DomTreeUpdater *DTU, LoopInfo *LI,
2459 const TargetLowering *TLI,
2460 const DataLayout *DL, ModifyDT &ModifiedDT,
2462 bool IsHugeFunc) {
2463 // If a zero input is undefined, it doesn't make sense to despeculate that.
2464 if (match(CountZeros->getOperand(1), m_One()))
2465 return false;
2466
2467 // If it's cheap to speculate, there's nothing to do.
2468 Type *Ty = CountZeros->getType();
2469 auto IntrinsicID = CountZeros->getIntrinsicID();
2470 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2471 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2472 return false;
2473
2474 // Only handle scalar cases. Anything else requires too much work.
2475 unsigned SizeInBits = Ty->getScalarSizeInBits();
2476 if (Ty->isVectorTy())
2477 return false;
2478
2479 // Bail if the value is never zero.
2480 Use &Op = CountZeros->getOperandUse(0);
2481 if (isKnownNonZero(Op, *DL))
2482 return false;
2483
2484 // The intrinsic will be sunk behind a compare against zero and branch.
2485 BasicBlock *StartBlock = CountZeros->getParent();
2486 BasicBlock *CallBlock = SplitBlock(StartBlock, CountZeros, DTU, LI,
2487 /* MSSAU */ nullptr, "cond.false");
2488 if (IsHugeFunc)
2489 FreshBBs.insert(CallBlock);
2490
2491 // Create another block after the count zero intrinsic. A PHI will be added
2492 // in this block to select the result of the intrinsic or the bit-width
2493 // constant if the input to the intrinsic is zero.
2494 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
2495 // Any debug-info after CountZeros should not be included.
2496 SplitPt.setHeadBit(true);
2497 BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, DTU, LI,
2498 /* MSSAU */ nullptr, "cond.end");
2499 if (IsHugeFunc)
2500 FreshBBs.insert(EndBlock);
2501
2502 // Set up a builder to create a compare, conditional branch, and PHI.
2503 IRBuilder<> Builder(StartBlock->getTerminator());
2504 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2505
2506 // Replace the unconditional branch that was created by the first split with
2507 // a compare against zero and a conditional branch.
2509 // Avoid introducing branch on poison. This also replaces the ctz operand.
2511 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2512 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2513 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2514 StartBlock->getTerminator()->eraseFromParent();
2515 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
2516
2517 // Create a PHI in the end block to select either the output of the intrinsic
2518 // or the bit width of the operand.
2519 Builder.SetInsertPoint(EndBlock->begin());
2520 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2521 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2522 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2523 PN->addIncoming(BitWidth, StartBlock);
2524 PN->addIncoming(CountZeros, CallBlock);
2525
2526 // We are explicitly handling the zero case, so we can set the intrinsic's
2527 // undefined zero argument to 'true'. This will also prevent reprocessing the
2528 // intrinsic; we only despeculate when a zero input is defined.
2529 CountZeros->setArgOperand(1, Builder.getTrue());
2530 ModifiedDT = ModifyDT::ModifyBBDT;
2531 return true;
2532}
2533
2534bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2535 BasicBlock *BB = CI->getParent();
2536
2537 // Sink address computing for memory operands into the block.
2538 if (CI->isInlineAsm() && optimizeInlineAsmInst(CI))
2539 return true;
2540
2541 // Align the pointer arguments to this call if the target thinks it's a good
2542 // idea
2543 unsigned MinSize;
2544 Align PrefAlign;
2545 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2546 for (auto &Arg : CI->args()) {
2547 // We want to align both objects whose address is used directly and
2548 // objects whose address is used in casts and GEPs, though it only makes
2549 // sense for GEPs if the offset is a multiple of the desired alignment and
2550 // if size - offset meets the size threshold.
2551 if (!Arg->getType()->isPointerTy())
2552 continue;
2553 APInt Offset(DL->getIndexSizeInBits(
2554 cast<PointerType>(Arg->getType())->getAddressSpace()),
2555 0);
2556 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2557 uint64_t Offset2 = Offset.getLimitedValue();
2558 if (!isAligned(PrefAlign, Offset2))
2559 continue;
2560 AllocaInst *AI;
2561 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2562 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*DL);
2563 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2564 AI->setAlignment(PrefAlign);
2565 }
2566 // Global variables can only be aligned if they are defined in this
2567 // object (i.e. they are uniquely initialized in this object), and
2568 // over-aligning global variables that have an explicit section is
2569 // forbidden.
2570 GlobalVariable *GV;
2571 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2572 GV->getPointerAlignment(*DL) < PrefAlign &&
2573 GV->getGlobalSize(*DL) >= MinSize + Offset2)
2574 GV->setAlignment(PrefAlign);
2575 }
2576 }
2577 // If this is a memcpy (or similar) then we may be able to improve the
2578 // alignment.
2579 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2580 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2581 MaybeAlign MIDestAlign = MI->getDestAlign();
2582 if (!MIDestAlign || DestAlign > *MIDestAlign)
2583 MI->setDestAlignment(DestAlign);
2584 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2585 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2586 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2587 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2588 MTI->setSourceAlignment(SrcAlign);
2589 }
2590 }
2591
2592 // If we have a cold call site, try to sink addressing computation into the
2593 // cold block. This interacts with our handling for loads and stores to
2594 // ensure that we can fold all uses of a potential addressing computation
2595 // into their uses. TODO: generalize this to work over profiling data
2596 if (CI->hasFnAttr(Attribute::Cold) &&
2597 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2598 for (auto &Arg : CI->args()) {
2599 if (!Arg->getType()->isPointerTy())
2600 continue;
2601 unsigned AS = Arg->getType()->getPointerAddressSpace();
2602 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2603 return true;
2604 }
2605
2606 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2607 if (II) {
2608 switch (II->getIntrinsicID()) {
2609 default:
2610 break;
2611 case Intrinsic::assume:
2612 llvm_unreachable("llvm.assume should have been removed already");
2613 case Intrinsic::allow_runtime_check:
2614 case Intrinsic::allow_ubsan_check:
2615 case Intrinsic::experimental_widenable_condition: {
2616 // Give up on future widening opportunities so that we can fold away dead
2617 // paths and merge blocks before going into block-local instruction
2618 // selection.
2619 if (II->use_empty()) {
2620 II->eraseFromParent();
2621 return true;
2622 }
2623 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2624 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2625 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2626 });
2627 return true;
2628 }
2629 case Intrinsic::objectsize:
2630 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2631 case Intrinsic::is_constant:
2632 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2633 case Intrinsic::aarch64_stlxr:
2634 case Intrinsic::aarch64_stxr: {
2635 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2636 if (!ExtVal || !ExtVal->hasOneUse() ||
2637 ExtVal->getParent() == CI->getParent())
2638 return false;
2639 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2640 ExtVal->moveBefore(CI->getIterator());
2641 // Mark this instruction as "inserted by CGP", so that other
2642 // optimizations don't touch it.
2643 InsertedInsts.insert(ExtVal);
2644 return true;
2645 }
2646
2647 case Intrinsic::launder_invariant_group: {
2648 Value *ArgVal = II->getArgOperand(0);
2649 auto it = LargeOffsetGEPMap.find(II);
2650 if (it != LargeOffsetGEPMap.end()) {
2651 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2652 // Make sure not to have to deal with iterator invalidation
2653 // after possibly adding ArgVal to LargeOffsetGEPMap.
2654 auto GEPs = std::move(it->second);
2655 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2656 LargeOffsetGEPMap.erase(II);
2657 }
2658
2659 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2660 II->eraseFromParent();
2661 return true;
2662 }
2663 case Intrinsic::cttz:
2664 case Intrinsic::ctlz:
2665 // If counting zeros is expensive, try to avoid it.
2666 return despeculateCountZeros(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2667 IsHugeFunc);
2668 case Intrinsic::fshl:
2669 case Intrinsic::fshr:
2670 return optimizeFunnelShift(II);
2671 case Intrinsic::masked_gather:
2672 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2673 case Intrinsic::masked_scatter:
2674 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2675 case Intrinsic::masked_load:
2676 // Treat v1X masked load as load X type.
2677 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2678 if (VT->getNumElements() == 1) {
2679 Value *PtrVal = II->getArgOperand(0);
2680 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2681 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2682 return true;
2683 }
2684 }
2685 return false;
2686 case Intrinsic::masked_store:
2687 // Treat v1X masked store as store X type.
2688 if (auto *VT =
2689 dyn_cast<FixedVectorType>(II->getArgOperand(0)->getType())) {
2690 if (VT->getNumElements() == 1) {
2691 Value *PtrVal = II->getArgOperand(1);
2692 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2693 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2694 return true;
2695 }
2696 }
2697 return false;
2698 case Intrinsic::umul_with_overflow:
2699 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2700 case Intrinsic::smul_with_overflow:
2701 return optimizeMulWithOverflow(II, /*IsSigned=*/true, ModifiedDT);
2702 }
2703
2704 SmallVector<Value *, 2> PtrOps;
2705 Type *AccessTy;
2706 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2707 while (!PtrOps.empty()) {
2708 Value *PtrVal = PtrOps.pop_back_val();
2709 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2710 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2711 return true;
2712 }
2713 }
2714
2715 // From here on out we're working with named functions.
2716 auto *Callee = CI->getCalledFunction();
2717 if (!Callee)
2718 return false;
2719
2720 // Lower all default uses of _chk calls. This is very similar
2721 // to what InstCombineCalls does, but here we are only lowering calls
2722 // to fortified library functions (e.g. __memcpy_chk) that have the default
2723 // "don't know" as the objectsize. Anything else should be left alone.
2724 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2725 IRBuilder<> Builder(CI);
2726 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2727 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2728 CI->eraseFromParent();
2729 return true;
2730 }
2731
2732 // SCCP may have propagated, among other things, C++ static variables across
2733 // calls. If this happens to be the case, we may want to undo it in order to
2734 // avoid redundant pointer computation of the constant, as the function method
2735 // returning the constant needs to be executed anyways.
2736 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2737 if (!F->getReturnType()->isPointerTy())
2738 return nullptr;
2739
2740 GlobalVariable *UniformValue = nullptr;
2741 for (auto &BB : *F) {
2742 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
2743 if (auto *V = dyn_cast<GlobalVariable>(RI->getReturnValue())) {
2744 if (!UniformValue)
2745 UniformValue = V;
2746 else if (V != UniformValue)
2747 return nullptr;
2748 } else {
2749 return nullptr;
2750 }
2751 }
2752 }
2753
2754 return UniformValue;
2755 };
2756
2757 if (Callee->hasExactDefinition()) {
2758 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2759 bool MadeChange = false;
2760 for (Use &U : make_early_inc_range(RV->uses())) {
2761 auto *I = dyn_cast<Instruction>(U.getUser());
2762 if (!I || I->getParent() != CI->getParent()) {
2763 // Limit to the same basic block to avoid extending the call-site live
2764 // range, which otherwise could increase register pressure.
2765 continue;
2766 }
2767 if (CI->comesBefore(I)) {
2768 U.set(CI);
2769 MadeChange = true;
2770 }
2771 }
2772
2773 return MadeChange;
2774 }
2775 }
2776
2777 return false;
2778}
2779
2781 const CallInst *CI) {
2782 assert(CI && CI->use_empty());
2783
2784 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2785 switch (II->getIntrinsicID()) {
2786 case Intrinsic::memset:
2787 case Intrinsic::memcpy:
2788 case Intrinsic::memmove:
2789 return true;
2790 default:
2791 return false;
2792 }
2793
2794 Function *Callee = CI->getCalledFunction();
2795 if (Callee && TLInfo)
2796 switch (TLInfo->getLibFunc(*Callee)) {
2797 case LibFunc_strcpy:
2798 case LibFunc_strncpy:
2799 case LibFunc_strcat:
2800 case LibFunc_strncat:
2801 return true;
2802 default:
2803 return false;
2804 }
2805
2806 return false;
2807}
2808
2809/// Look for opportunities to duplicate return instructions to the predecessor
2810/// to enable tail call optimizations. The case it is currently looking for is
2811/// the following one. Known intrinsics or library function that may be tail
2812/// called are taken into account as well.
2813/// @code
2814/// bb0:
2815/// %tmp0 = tail call i32 @f0()
2816/// br label %return
2817/// bb1:
2818/// %tmp1 = tail call i32 @f1()
2819/// br label %return
2820/// bb2:
2821/// %tmp2 = tail call i32 @f2()
2822/// br label %return
2823/// return:
2824/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2825/// ret i32 %retval
2826/// @endcode
2827///
2828/// =>
2829///
2830/// @code
2831/// bb0:
2832/// %tmp0 = tail call i32 @f0()
2833/// ret i32 %tmp0
2834/// bb1:
2835/// %tmp1 = tail call i32 @f1()
2836/// ret i32 %tmp1
2837/// bb2:
2838/// %tmp2 = tail call i32 @f2()
2839/// ret i32 %tmp2
2840/// @endcode
2841bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2842 ModifyDT &ModifiedDT) {
2843 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2844 if (!RetI)
2845 return false;
2846
2847 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2848
2849 PHINode *PN = nullptr;
2850 ExtractValueInst *EVI = nullptr;
2851 BitCastInst *BCI = nullptr;
2852 Value *V = RetI->getReturnValue();
2853 if (V) {
2854 BCI = dyn_cast<BitCastInst>(V);
2855 if (BCI)
2856 V = BCI->getOperand(0);
2857
2859 if (EVI) {
2860 V = EVI->getOperand(0);
2861 if (!llvm::all_of(EVI->indices(), equal_to(0)))
2862 return false;
2863 }
2864
2865 PN = dyn_cast<PHINode>(V);
2866 }
2867
2868 if (PN && PN->getParent() != BB)
2869 return false;
2870
2872
2873 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
2874 if (auto *II = dyn_cast<IntrinsicInst>(Inst);
2875 II && II->getIntrinsicID() == Intrinsic::fake_use) {
2876 // Record the instruction so it can be preserved when the exit block is
2877 // removed. Do not preserve the fake use that uses the result of the
2878 // PHI instruction.
2879 // Do not copy fake uses that use the result of a PHI node.
2880 // FIXME: If we do want to copy the fake use into the return blocks, we
2881 // have to figure out which of the PHI node operands to use for each
2882 // copy.
2883 if (!isa<PHINode>(II->getOperand(0))) {
2884 FakeUses.push_back(II);
2885 }
2886 return true;
2887 }
2888
2889 return false;
2890 };
2891
2892 // Make sure there are no instructions between the first instruction
2893 // and return.
2895 // Skip over pseudo-probes and the bitcast.
2896 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
2897 match(&*BI, m_Intrinsic<Intrinsic::lifetime_end>()) || isFakeUse(&*BI))
2898 BI = std::next(BI);
2899 if (&*BI != RetI)
2900 return false;
2901
2902 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2903 // call.
2904 auto MayBePermittedAsTailCall = [&](const auto *CI) {
2905 return TLI->mayBeEmittedAsTailCall(CI) &&
2906 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
2907 };
2908
2909 SmallVector<BasicBlock *, 4> TailCallBBs;
2910 // Record the call instructions so we can insert any fake uses
2911 // that need to be preserved before them.
2913 if (PN) {
2914 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2915 // Look through bitcasts.
2916 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2917 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2918 BasicBlock *PredBB = PN->getIncomingBlock(I);
2919 // Make sure the phi value is indeed produced by the tail call.
2920 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2921 MayBePermittedAsTailCall(CI)) {
2922 TailCallBBs.push_back(PredBB);
2923 CallInsts.push_back(CI);
2924 } else {
2925 // Consider the cases in which the phi value is indirectly produced by
2926 // the tail call, for example when encountering memset(), memmove(),
2927 // strcpy(), whose return value may have been optimized out. In such
2928 // cases, the value needs to be the first function argument.
2929 //
2930 // bb0:
2931 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
2932 // br label %return
2933 // return:
2934 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
2935 if (PredBB && PredBB->getSingleSuccessor() == BB)
2937 PredBB->getTerminator()->getPrevNode());
2938
2939 if (CI && CI->use_empty() &&
2940 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2941 IncomingVal == CI->getArgOperand(0) &&
2942 MayBePermittedAsTailCall(CI)) {
2943 TailCallBBs.push_back(PredBB);
2944 CallInsts.push_back(CI);
2945 }
2946 }
2947 }
2948 } else {
2949 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2950 for (BasicBlock *Pred : predecessors(BB)) {
2951 if (!VisitedBBs.insert(Pred).second)
2952 continue;
2953 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
2954 CallInst *CI = dyn_cast<CallInst>(I);
2955 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
2956 // Either we return void or the return value must be the first
2957 // argument of a known intrinsic or library function.
2958 if (!V || isa<UndefValue>(V) ||
2959 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2960 V == CI->getArgOperand(0))) {
2961 TailCallBBs.push_back(Pred);
2962 CallInsts.push_back(CI);
2963 }
2964 }
2965 }
2966 }
2967 }
2968
2969 bool Changed = false;
2970 for (auto const &TailCallBB : TailCallBBs) {
2971 // Make sure the call instruction is followed by an unconditional branch to
2972 // the return block.
2973 UncondBrInst *BI = dyn_cast<UncondBrInst>(TailCallBB->getTerminator());
2974 if (!BI || BI->getSuccessor() != BB)
2975 continue;
2976
2977 // Duplicate the return into TailCallBB.
2978 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
2979 assert(!Opts.cgp_verify_bfi_updates ||
2980 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
2981 BFI->setBlockFreq(BB,
2982 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
2983 ModifiedDT = ModifyDT::ModifyBBDT;
2984 Changed = true;
2985 ++NumRetsDup;
2986 }
2987
2988 // If we eliminated all predecessors of the block, delete the block now.
2989 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
2990 // Copy the fake uses found in the original return block to all blocks
2991 // that contain tail calls.
2992 for (auto *CI : CallInsts) {
2993 for (auto const *FakeUse : FakeUses) {
2994 auto *ClonedInst = FakeUse->clone();
2995 ClonedInst->insertBefore(CI->getIterator());
2996 }
2997 }
2998 DTU->deleteBB(BB);
2999 }
3000
3001 return Changed;
3002}
3003
3004//===----------------------------------------------------------------------===//
3005// Memory Optimization
3006//===----------------------------------------------------------------------===//
3007
3008namespace {
3009
3010/// This is an extended version of TargetLowering::AddrMode
3011/// which holds actual Value*'s for register values.
3012struct ExtAddrMode : public TargetLowering::AddrMode {
3013 Value *BaseReg = nullptr;
3014 Value *ScaledReg = nullptr;
3015 Value *OriginalValue = nullptr;
3016 bool InBounds = true;
3017
3018 enum FieldName {
3019 NoField = 0x00,
3020 BaseRegField = 0x01,
3021 BaseGVField = 0x02,
3022 BaseOffsField = 0x04,
3023 ScaledRegField = 0x08,
3024 ScaleField = 0x10,
3025 MultipleFields = 0xff
3026 };
3027
3028 ExtAddrMode() = default;
3029
3030 void print(raw_ostream &OS) const;
3031 void dump() const;
3032
3033 // Replace From in ExtAddrMode with To.
3034 // E.g., SExt insts may be promoted and deleted. We should replace them with
3035 // the promoted values.
3036 void replaceWith(Value *From, Value *To) {
3037 if (ScaledReg == From)
3038 ScaledReg = To;
3039 }
3040
3041 FieldName compare(const ExtAddrMode &other) {
3042 // First check that the types are the same on each field, as differing types
3043 // is something we can't cope with later on.
3044 if (BaseReg && other.BaseReg &&
3045 BaseReg->getType() != other.BaseReg->getType())
3046 return MultipleFields;
3047 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3048 return MultipleFields;
3049 if (ScaledReg && other.ScaledReg &&
3050 ScaledReg->getType() != other.ScaledReg->getType())
3051 return MultipleFields;
3052
3053 // Conservatively reject 'inbounds' mismatches.
3054 if (InBounds != other.InBounds)
3055 return MultipleFields;
3056
3057 // Check each field to see if it differs.
3058 unsigned Result = NoField;
3059 if (BaseReg != other.BaseReg)
3060 Result |= BaseRegField;
3061 if (BaseGV != other.BaseGV)
3062 Result |= BaseGVField;
3063 if (BaseOffs != other.BaseOffs)
3064 Result |= BaseOffsField;
3065 if (ScaledReg != other.ScaledReg)
3066 Result |= ScaledRegField;
3067 // Don't count 0 as being a different scale, because that actually means
3068 // unscaled (which will already be counted by having no ScaledReg).
3069 if (Scale && other.Scale && Scale != other.Scale)
3070 Result |= ScaleField;
3071
3072 if (llvm::popcount(Result) > 1)
3073 return MultipleFields;
3074 else
3075 return static_cast<FieldName>(Result);
3076 }
3077
3078 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3079 // with no offset.
3080 bool isTrivial() {
3081 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3082 // trivial if at most one of these terms is nonzero, except that BaseGV and
3083 // BaseReg both being zero actually means a null pointer value, which we
3084 // consider to be 'non-zero' here.
3085 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3086 }
3087
3088 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3089 switch (Field) {
3090 default:
3091 return nullptr;
3092 case BaseRegField:
3093 return BaseReg;
3094 case BaseGVField:
3095 return BaseGV;
3096 case ScaledRegField:
3097 return ScaledReg;
3098 case BaseOffsField:
3099 return ConstantInt::getSigned(IntPtrTy, BaseOffs);
3100 }
3101 }
3102
3103 void SetCombinedField(FieldName Field, Value *V,
3104 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3105 switch (Field) {
3106 default:
3107 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3108 break;
3109 case ExtAddrMode::BaseRegField:
3110 BaseReg = V;
3111 break;
3112 case ExtAddrMode::BaseGVField:
3113 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3114 // in the BaseReg field.
3115 assert(BaseReg == nullptr);
3116 BaseReg = V;
3117 BaseGV = nullptr;
3118 break;
3119 case ExtAddrMode::ScaledRegField:
3120 ScaledReg = V;
3121 // If we have a mix of scaled and unscaled addrmodes then we want scale
3122 // to be the scale and not zero.
3123 if (!Scale)
3124 for (const ExtAddrMode &AM : AddrModes)
3125 if (AM.Scale) {
3126 Scale = AM.Scale;
3127 break;
3128 }
3129 break;
3130 case ExtAddrMode::BaseOffsField:
3131 // The offset is no longer a constant, so it goes in ScaledReg with a
3132 // scale of 1.
3133 assert(ScaledReg == nullptr);
3134 ScaledReg = V;
3135 Scale = 1;
3136 BaseOffs = 0;
3137 break;
3138 }
3139 }
3140};
3141
3142#ifndef NDEBUG
3143static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3144 AM.print(OS);
3145 return OS;
3146}
3147#endif
3148
3149#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3150void ExtAddrMode::print(raw_ostream &OS) const {
3151 bool NeedPlus = false;
3152 OS << "[";
3153 if (InBounds)
3154 OS << "inbounds ";
3155 if (BaseGV) {
3156 OS << "GV:";
3157 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3158 NeedPlus = true;
3159 }
3160
3161 if (BaseOffs) {
3162 OS << (NeedPlus ? " + " : "") << BaseOffs;
3163 NeedPlus = true;
3164 }
3165
3166 if (BaseReg) {
3167 OS << (NeedPlus ? " + " : "") << "Base:";
3168 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3169 NeedPlus = true;
3170 }
3171 if (Scale) {
3172 OS << (NeedPlus ? " + " : "") << Scale << "*";
3173 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3174 }
3175
3176 OS << ']';
3177}
3178
3179LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3180 print(dbgs());
3181 dbgs() << '\n';
3182}
3183#endif
3184
3185} // end anonymous namespace
3186
3187namespace {
3188
3189/// This class provides transaction based operation on the IR.
3190/// Every change made through this class is recorded in the internal state and
3191/// can be undone (rollback) until commit is called.
3192/// CGP does not check if instructions could be speculatively executed when
3193/// moved. Preserving the original location would pessimize the debugging
3194/// experience, as well as negatively impact the quality of sample PGO.
3195class TypePromotionTransaction {
3196 /// This represents the common interface of the individual transaction.
3197 /// Each class implements the logic for doing one specific modification on
3198 /// the IR via the TypePromotionTransaction.
3199 class TypePromotionAction {
3200 protected:
3201 /// The Instruction modified.
3202 Instruction *Inst;
3203
3204 public:
3205 /// Constructor of the action.
3206 /// The constructor performs the related action on the IR.
3207 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3208
3209 virtual ~TypePromotionAction() = default;
3210
3211 /// Undo the modification done by this action.
3212 /// When this method is called, the IR must be in the same state as it was
3213 /// before this action was applied.
3214 /// \pre Undoing the action works if and only if the IR is in the exact same
3215 /// state as it was directly after this action was applied.
3216 virtual void undo() = 0;
3217
3218 /// Advocate every change made by this action.
3219 /// When the results on the IR of the action are to be kept, it is important
3220 /// to call this function, otherwise hidden information may be kept forever.
3221 virtual void commit() {
3222 // Nothing to be done, this action is not doing anything.
3223 }
3224 };
3225
3226 /// Utility to remember the position of an instruction.
3227 class InsertionHandler {
3228 /// Position of an instruction.
3229 /// Either an instruction:
3230 /// - Is the first in a basic block: BB is used.
3231 /// - Has a previous instruction: PrevInst is used.
3232 struct {
3233 BasicBlock::iterator PrevInst;
3234 BasicBlock *BB;
3235 } Point;
3236 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3237
3238 /// Remember whether or not the instruction had a previous instruction.
3239 bool HasPrevInstruction;
3240
3241 public:
3242 /// Record the position of \p Inst.
3243 InsertionHandler(Instruction *Inst) {
3244 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3245 BasicBlock *BB = Inst->getParent();
3246
3247 // Record where we would have to re-insert the instruction in the sequence
3248 // of DbgRecords, if we ended up reinserting.
3249 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3250
3251 if (HasPrevInstruction) {
3252 Point.PrevInst = std::prev(Inst->getIterator());
3253 } else {
3254 Point.BB = BB;
3255 }
3256 }
3257
3258 /// Insert \p Inst at the recorded position.
3259 void insert(Instruction *Inst) {
3260 if (HasPrevInstruction) {
3261 if (Inst->getParent())
3262 Inst->removeFromParent();
3263 Inst->insertAfter(Point.PrevInst);
3264 } else {
3265 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3266 if (Inst->getParent())
3267 Inst->moveBefore(*Point.BB, Position);
3268 else
3269 Inst->insertBefore(*Point.BB, Position);
3270 }
3271
3272 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3273 }
3274 };
3275
3276 /// Set the operand of an instruction with a new value.
3277 class OperandSetter : public TypePromotionAction {
3278 /// Original operand of the instruction.
3279 Value *Origin;
3280
3281 /// Index of the modified instruction.
3282 unsigned Idx;
3283
3284 public:
3285 /// Set \p Idx operand of \p Inst with \p NewVal.
3286 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3287 : TypePromotionAction(Inst), Idx(Idx) {
3288 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3289 << "for:" << *Inst << "\n"
3290 << "with:" << *NewVal << "\n");
3291 Origin = Inst->getOperand(Idx);
3292 Inst->setOperand(Idx, NewVal);
3293 }
3294
3295 /// Restore the original value of the instruction.
3296 void undo() override {
3297 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3298 << "for: " << *Inst << "\n"
3299 << "with: " << *Origin << "\n");
3300 Inst->setOperand(Idx, Origin);
3301 }
3302 };
3303
3304 /// Hide the operands of an instruction.
3305 /// Do as if this instruction was not using any of its operands.
3306 class OperandsHider : public TypePromotionAction {
3307 /// The list of original operands.
3308 SmallVector<Value *, 4> OriginalValues;
3309
3310 public:
3311 /// Remove \p Inst from the uses of the operands of \p Inst.
3312 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3313 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3314 unsigned NumOpnds = Inst->getNumOperands();
3315 OriginalValues.reserve(NumOpnds);
3316 for (unsigned It = 0; It < NumOpnds; ++It) {
3317 // Save the current operand.
3318 Value *Val = Inst->getOperand(It);
3319 OriginalValues.push_back(Val);
3320 // Set a dummy one.
3321 // We could use OperandSetter here, but that would imply an overhead
3322 // that we are not willing to pay.
3323 Inst->setOperand(It, PoisonValue::get(Val->getType()));
3324 }
3325 }
3326
3327 /// Restore the original list of uses.
3328 void undo() override {
3329 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3330 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3331 Inst->setOperand(It, OriginalValues[It]);
3332 }
3333 };
3334
3335 /// Build a truncate instruction.
3336 class TruncBuilder : public TypePromotionAction {
3337 Value *Val;
3338
3339 public:
3340 /// Build a truncate instruction of \p Opnd producing a \p Ty
3341 /// result.
3342 /// trunc Opnd to Ty.
3343 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3344 IRBuilder<> Builder(Opnd);
3345 Builder.SetCurrentDebugLocation(DebugLoc());
3346 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3347 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3348 }
3349
3350 /// Get the built value.
3351 Value *getBuiltValue() { return Val; }
3352
3353 /// Remove the built instruction.
3354 void undo() override {
3355 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3356 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3357 IVal->eraseFromParent();
3358 }
3359 };
3360
3361 /// Build a sign extension instruction.
3362 class SExtBuilder : public TypePromotionAction {
3363 Value *Val;
3364
3365 public:
3366 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3367 /// result.
3368 /// sext Opnd to Ty.
3369 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3370 : TypePromotionAction(InsertPt) {
3371 IRBuilder<> Builder(InsertPt);
3372 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3373 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3374 }
3375
3376 /// Get the built value.
3377 Value *getBuiltValue() { return Val; }
3378
3379 /// Remove the built instruction.
3380 void undo() override {
3381 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3382 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3383 IVal->eraseFromParent();
3384 }
3385 };
3386
3387 /// Build a zero extension instruction.
3388 class ZExtBuilder : public TypePromotionAction {
3389 Value *Val;
3390
3391 public:
3392 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3393 /// result.
3394 /// zext Opnd to Ty.
3395 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3396 : TypePromotionAction(InsertPt) {
3397 IRBuilder<> Builder(InsertPt);
3398 Builder.SetCurrentDebugLocation(DebugLoc());
3399 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3400 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3401 }
3402
3403 /// Get the built value.
3404 Value *getBuiltValue() { return Val; }
3405
3406 /// Remove the built instruction.
3407 void undo() override {
3408 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3409 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3410 IVal->eraseFromParent();
3411 }
3412 };
3413
3414 /// Mutate an instruction to another type.
3415 class TypeMutator : public TypePromotionAction {
3416 /// Record the original type.
3417 Type *OrigTy;
3418
3419 public:
3420 /// Mutate the type of \p Inst into \p NewTy.
3421 TypeMutator(Instruction *Inst, Type *NewTy)
3422 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3423 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3424 << "\n");
3425 Inst->mutateType(NewTy);
3426 }
3427
3428 /// Mutate the instruction back to its original type.
3429 void undo() override {
3430 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3431 << "\n");
3432 Inst->mutateType(OrigTy);
3433 }
3434 };
3435
3436 /// Replace the uses of an instruction by another instruction.
3437 class UsesReplacer : public TypePromotionAction {
3438 /// Helper structure to keep track of the replaced uses.
3439 struct InstructionAndIdx {
3440 /// The instruction using the instruction.
3441 Instruction *Inst;
3442
3443 /// The index where this instruction is used for Inst.
3444 unsigned Idx;
3445
3446 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3447 : Inst(Inst), Idx(Idx) {}
3448 };
3449
3450 /// Keep track of the original uses (pair Instruction, Index).
3452 /// Keep track of the debug users.
3453 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3454
3455 /// Keep track of the new value so that we can undo it by replacing
3456 /// instances of the new value with the original value.
3457 Value *New;
3458
3459 public:
3460 /// Replace all the use of \p Inst by \p New.
3461 UsesReplacer(Instruction *Inst, Value *New)
3462 : TypePromotionAction(Inst), New(New) {
3463 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3464 << "\n");
3465 // Record the original uses.
3466 for (Use &U : Inst->uses()) {
3467 Instruction *UserI = cast<Instruction>(U.getUser());
3468 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3469 }
3470 // Record the debug uses separately. They are not in the instruction's
3471 // use list, but they are replaced by RAUW.
3472 findDbgValues(Inst, DbgVariableRecords);
3473
3474 // Now, we can replace the uses.
3475 Inst->replaceAllUsesWith(New);
3476 }
3477
3478 /// Reassign the original uses of Inst to Inst.
3479 void undo() override {
3480 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3481 for (InstructionAndIdx &Use : OriginalUses)
3482 Use.Inst->setOperand(Use.Idx, Inst);
3483 // RAUW has replaced all original uses with references to the new value,
3484 // including the debug uses. Since we are undoing the replacements,
3485 // the original debug uses must also be reinstated to maintain the
3486 // correctness and utility of debug value records.
3487 for (DbgVariableRecord *DVR : DbgVariableRecords)
3488 DVR->replaceVariableLocationOp(New, Inst);
3489 }
3490 };
3491
3492 /// Remove an instruction from the IR.
3493 class InstructionRemover : public TypePromotionAction {
3494 /// Original position of the instruction.
3495 InsertionHandler Inserter;
3496
3497 /// Helper structure to hide all the link to the instruction. In other
3498 /// words, this helps to do as if the instruction was removed.
3499 OperandsHider Hider;
3500
3501 /// Keep track of the uses replaced, if any.
3502 UsesReplacer *Replacer = nullptr;
3503
3504 /// Keep track of instructions removed.
3505 SetOfInstrs &RemovedInsts;
3506
3507 public:
3508 /// Remove all reference of \p Inst and optionally replace all its
3509 /// uses with New.
3510 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3511 /// \pre If !Inst->use_empty(), then New != nullptr
3512 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3513 Value *New = nullptr)
3514 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3515 RemovedInsts(RemovedInsts) {
3516 if (New)
3517 Replacer = new UsesReplacer(Inst, New);
3518 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3519 RemovedInsts.insert(Inst);
3520 /// The instructions removed here will be freed after completing
3521 /// optimizeBlock() for all blocks as we need to keep track of the
3522 /// removed instructions during promotion.
3523 Inst->removeFromParent();
3524 }
3525
3526 ~InstructionRemover() override { delete Replacer; }
3527
3528 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3529 InstructionRemover(const InstructionRemover &other) = delete;
3530
3531 /// Resurrect the instruction and reassign it to the proper uses if
3532 /// new value was provided when build this action.
3533 void undo() override {
3534 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3535 Inserter.insert(Inst);
3536 if (Replacer)
3537 Replacer->undo();
3538 Hider.undo();
3539 RemovedInsts.erase(Inst);
3540 }
3541 };
3542
3543public:
3544 /// Restoration point.
3545 /// The restoration point is a pointer to an action instead of an iterator
3546 /// because the iterator may be invalidated but not the pointer.
3547 using ConstRestorationPt = const TypePromotionAction *;
3548
3549 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3550 : RemovedInsts(RemovedInsts) {}
3551
3552 /// Advocate every changes made in that transaction. Return true if any change
3553 /// happen.
3554 bool commit();
3555
3556 /// Undo all the changes made after the given point.
3557 void rollback(ConstRestorationPt Point);
3558
3559 /// Get the current restoration point.
3560 ConstRestorationPt getRestorationPoint() const;
3561
3562 /// \name API for IR modification with state keeping to support rollback.
3563 /// @{
3564 /// Same as Instruction::setOperand.
3565 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3566
3567 /// Same as Instruction::eraseFromParent.
3568 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3569
3570 /// Same as Value::replaceAllUsesWith.
3571 void replaceAllUsesWith(Instruction *Inst, Value *New);
3572
3573 /// Same as Value::mutateType.
3574 void mutateType(Instruction *Inst, Type *NewTy);
3575
3576 /// Same as IRBuilder::createTrunc.
3577 Value *createTrunc(Instruction *Opnd, Type *Ty);
3578
3579 /// Same as IRBuilder::createSExt.
3580 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3581
3582 /// Same as IRBuilder::createZExt.
3583 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3584
3585private:
3586 /// The ordered list of actions made so far.
3588
3589 SetOfInstrs &RemovedInsts;
3590};
3591
3592} // end anonymous namespace
3593
3594void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3595 Value *NewVal) {
3596 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3597 Inst, Idx, NewVal));
3598}
3599
3600void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3601 Value *NewVal) {
3602 Actions.push_back(
3603 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3604 Inst, RemovedInsts, NewVal));
3605}
3606
3607void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3608 Value *New) {
3609 Actions.push_back(
3610 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3611}
3612
3613void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3614 Actions.push_back(
3615 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3616}
3617
3618Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3619 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3620 Value *Val = Ptr->getBuiltValue();
3621 Actions.push_back(std::move(Ptr));
3622 return Val;
3623}
3624
3625Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3626 Type *Ty) {
3627 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3628 Value *Val = Ptr->getBuiltValue();
3629 Actions.push_back(std::move(Ptr));
3630 return Val;
3631}
3632
3633Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3634 Type *Ty) {
3635 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3636 Value *Val = Ptr->getBuiltValue();
3637 Actions.push_back(std::move(Ptr));
3638 return Val;
3639}
3640
3641TypePromotionTransaction::ConstRestorationPt
3642TypePromotionTransaction::getRestorationPoint() const {
3643 return !Actions.empty() ? Actions.back().get() : nullptr;
3644}
3645
3646bool TypePromotionTransaction::commit() {
3647 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3648 Action->commit();
3649 bool Modified = !Actions.empty();
3650 Actions.clear();
3651 return Modified;
3652}
3653
3654void TypePromotionTransaction::rollback(
3655 TypePromotionTransaction::ConstRestorationPt Point) {
3656 while (!Actions.empty() && Point != Actions.back().get()) {
3657 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3658 Curr->undo();
3659 }
3660}
3661
3662namespace {
3663
3664/// A helper class for matching addressing modes.
3665///
3666/// This encapsulates the logic for matching the target-legal addressing modes.
3667class AddressingModeMatcher {
3668 SmallVectorImpl<Instruction *> &AddrModeInsts;
3669 const TargetLowering &TLI;
3670 const TargetRegisterInfo &TRI;
3671 const DataLayout &DL;
3672 const LoopInfo &LI;
3673 const std::function<const DominatorTree &()> getDTFn;
3674
3675 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3676 /// the memory instruction that we're computing this address for.
3677 Type *AccessTy;
3678 unsigned AddrSpace;
3679 Instruction *MemoryInst;
3680
3681 /// This is the addressing mode that we're building up. This is
3682 /// part of the return value of this addressing mode matching stuff.
3683 ExtAddrMode &AddrMode;
3684
3685 /// The instructions inserted by other CodeGenPrepare optimizations.
3686 const SetOfInstrs &InsertedInsts;
3687
3688 /// A map from the instructions to their type before promotion.
3689 InstrToOrigTy &PromotedInsts;
3690
3691 /// The ongoing transaction where every action should be registered.
3692 TypePromotionTransaction &TPT;
3693
3694 // A GEP which has too large offset to be folded into the addressing mode.
3695 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3696
3697 /// This is set to true when we should not do profitability checks.
3698 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3699 bool IgnoreProfitability;
3700
3701 /// True if we are optimizing for size.
3702 bool OptSize = false;
3703
3704 ProfileSummaryInfo *PSI;
3705 BlockFrequencyInfo *BFI;
3706 const CodeGenOptions &Opts;
3707
3708 AddressingModeMatcher(
3709 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3710 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3711 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3712 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3713 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3714 TypePromotionTransaction &TPT,
3715 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3716 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3717 const CodeGenOptions &Opts)
3718 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), DL(MI->getDataLayout()), LI(LI),
3719 getDTFn(getDTFn), AccessTy(AT), AddrSpace(AS), MemoryInst(MI),
3720 AddrMode(AM), InsertedInsts(InsertedInsts),
3721 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP),
3722 OptSize(OptSize), PSI(PSI), BFI(BFI), Opts(Opts) {
3723 IgnoreProfitability = false;
3724 }
3725
3726public:
3727 /// Find the maximal addressing mode that a load/store of V can fold,
3728 /// give an access type of AccessTy. This returns a list of involved
3729 /// instructions in AddrModeInsts.
3730 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3731 /// optimizations.
3732 /// \p PromotedInsts maps the instructions to their type before promotion.
3733 /// \p The ongoing transaction where every action should be registered.
3734 static ExtAddrMode
3735 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3736 SmallVectorImpl<Instruction *> &AddrModeInsts,
3737 const TargetLowering &TLI, const LoopInfo &LI,
3738 const std::function<const DominatorTree &()> getDTFn,
3739 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3740 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3741 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3742 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3743 const CodeGenOptions &Opts) {
3744 ExtAddrMode Result;
3745
3746 bool Success = AddressingModeMatcher(
3747 AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS,
3748 MemoryInst, Result, InsertedInsts, PromotedInsts, TPT,
3749 LargeOffsetGEP, OptSize, PSI, BFI, Opts)
3750 .matchAddr(V, 0);
3751 (void)Success;
3752 assert(Success && "Couldn't select *anything*?");
3753 return Result;
3754 }
3755
3756private:
3757 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3758 bool matchAddr(Value *Addr, unsigned Depth);
3759 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3760 bool *MovedAway = nullptr);
3761 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3762 ExtAddrMode &AMBefore,
3763 ExtAddrMode &AMAfter);
3764 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3765 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3766 Value *PromotedOperand) const;
3767};
3768
3769class PhiNodeSet;
3770
3771/// An iterator for PhiNodeSet.
3772class PhiNodeSetIterator {
3773 PhiNodeSet *const Set;
3774 size_t CurrentIndex = 0;
3775
3776public:
3777 /// The constructor. Start should point to either a valid element, or be equal
3778 /// to the size of the underlying SmallVector of the PhiNodeSet.
3779 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3780 PHINode *operator*() const;
3781 PhiNodeSetIterator &operator++();
3782 bool operator==(const PhiNodeSetIterator &RHS) const;
3783 bool operator!=(const PhiNodeSetIterator &RHS) const;
3784};
3785
3786/// Keeps a set of PHINodes.
3787///
3788/// This is a minimal set implementation for a specific use case:
3789/// It is very fast when there are very few elements, but also provides good
3790/// performance when there are many. It is similar to SmallPtrSet, but also
3791/// provides iteration by insertion order, which is deterministic and stable
3792/// across runs. It is also similar to SmallSetVector, but provides removing
3793/// elements in O(1) time. This is achieved by not actually removing the element
3794/// from the underlying vector, so comes at the cost of using more memory, but
3795/// that is fine, since PhiNodeSets are used as short lived objects.
3796class PhiNodeSet {
3797 friend class PhiNodeSetIterator;
3798
3799 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3800 using iterator = PhiNodeSetIterator;
3801
3802 /// Keeps the elements in the order of their insertion in the underlying
3803 /// vector. To achieve constant time removal, it never deletes any element.
3805
3806 /// Keeps the elements in the underlying set implementation. This (and not the
3807 /// NodeList defined above) is the source of truth on whether an element
3808 /// is actually in the collection.
3809 MapType NodeMap;
3810
3811 /// Points to the first valid (not deleted) element when the set is not empty
3812 /// and the value is not zero. Equals to the size of the underlying vector
3813 /// when the set is empty. When the value is 0, as in the beginning, the
3814 /// first element may or may not be valid.
3815 size_t FirstValidElement = 0;
3816
3817public:
3818 /// Inserts a new element to the collection.
3819 /// \returns true if the element is actually added, i.e. was not in the
3820 /// collection before the operation.
3821 bool insert(PHINode *Ptr) {
3822 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3823 NodeList.push_back(Ptr);
3824 return true;
3825 }
3826 return false;
3827 }
3828
3829 /// Removes the element from the collection.
3830 /// \returns whether the element is actually removed, i.e. was in the
3831 /// collection before the operation.
3832 bool erase(PHINode *Ptr) {
3833 if (NodeMap.erase(Ptr)) {
3834 SkipRemovedElements(FirstValidElement);
3835 return true;
3836 }
3837 return false;
3838 }
3839
3840 /// Removes all elements and clears the collection.
3841 void clear() {
3842 NodeMap.clear();
3843 NodeList.clear();
3844 FirstValidElement = 0;
3845 }
3846
3847 /// \returns an iterator that will iterate the elements in the order of
3848 /// insertion.
3849 iterator begin() {
3850 if (FirstValidElement == 0)
3851 SkipRemovedElements(FirstValidElement);
3852 return PhiNodeSetIterator(this, FirstValidElement);
3853 }
3854
3855 /// \returns an iterator that points to the end of the collection.
3856 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3857
3858 /// Returns the number of elements in the collection.
3859 size_t size() const { return NodeMap.size(); }
3860
3861 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3862 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3863
3864private:
3865 /// Updates the CurrentIndex so that it will point to a valid element.
3866 ///
3867 /// If the element of NodeList at CurrentIndex is valid, it does not
3868 /// change it. If there are no more valid elements, it updates CurrentIndex
3869 /// to point to the end of the NodeList.
3870 void SkipRemovedElements(size_t &CurrentIndex) {
3871 while (CurrentIndex < NodeList.size()) {
3872 auto it = NodeMap.find(NodeList[CurrentIndex]);
3873 // If the element has been deleted and added again later, NodeMap will
3874 // point to a different index, so CurrentIndex will still be invalid.
3875 if (it != NodeMap.end() && it->second == CurrentIndex)
3876 break;
3877 ++CurrentIndex;
3878 }
3879 }
3880};
3881
3882PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3883 : Set(Set), CurrentIndex(Start) {}
3884
3885PHINode *PhiNodeSetIterator::operator*() const {
3886 assert(CurrentIndex < Set->NodeList.size() &&
3887 "PhiNodeSet access out of range");
3888 return Set->NodeList[CurrentIndex];
3889}
3890
3891PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3892 assert(CurrentIndex < Set->NodeList.size() &&
3893 "PhiNodeSet access out of range");
3894 ++CurrentIndex;
3895 Set->SkipRemovedElements(CurrentIndex);
3896 return *this;
3897}
3898
3899bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3900 return CurrentIndex == RHS.CurrentIndex;
3901}
3902
3903bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3904 return !((*this) == RHS);
3905}
3906
3907/// Keep track of simplification of Phi nodes.
3908/// Accept the set of all phi nodes and erase phi node from this set
3909/// if it is simplified.
3910class SimplificationTracker {
3911 DenseMap<Value *, Value *> Storage;
3912 // Tracks newly created Phi nodes. The elements are iterated by insertion
3913 // order.
3914 PhiNodeSet AllPhiNodes;
3915 // Tracks newly created Select nodes.
3916 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3917
3918public:
3919 Value *Get(Value *V) {
3920 do {
3921 auto SV = Storage.find(V);
3922 if (SV == Storage.end())
3923 return V;
3924 V = SV->second;
3925 } while (true);
3926 }
3927
3928 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3929
3930 void ReplacePhi(PHINode *From, PHINode *To) {
3931 Value *OldReplacement = Get(From);
3932 while (OldReplacement != From) {
3933 From = To;
3934 To = dyn_cast<PHINode>(OldReplacement);
3935 OldReplacement = Get(From);
3936 }
3937 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3938 Put(From, To);
3939 From->replaceAllUsesWith(To);
3940 AllPhiNodes.erase(From);
3941 From->eraseFromParent();
3942 }
3943
3944 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3945
3946 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3947
3948 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3949
3950 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3951
3952 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3953
3954 void destroyNewNodes(Type *CommonType) {
3955 // For safe erasing, replace the uses with dummy value first.
3956 auto *Dummy = PoisonValue::get(CommonType);
3957 for (auto *I : AllPhiNodes) {
3958 I->replaceAllUsesWith(Dummy);
3959 I->eraseFromParent();
3960 }
3961 AllPhiNodes.clear();
3962 for (auto *I : AllSelectNodes) {
3963 I->replaceAllUsesWith(Dummy);
3964 I->eraseFromParent();
3965 }
3966 AllSelectNodes.clear();
3967 }
3968};
3969
3970/// A helper class for combining addressing modes.
3971class AddressingModeCombiner {
3972 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3973 typedef std::pair<PHINode *, PHINode *> PHIPair;
3974
3975private:
3976 /// The addressing modes we've collected.
3978
3979 /// The field in which the AddrModes differ, when we have more than one.
3980 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3981
3982 /// Are the AddrModes that we have all just equal to their original values?
3983 bool AllAddrModesTrivial = true;
3984
3985 /// Common Type for all different fields in addressing modes.
3986 Type *CommonType = nullptr;
3987
3988 const DataLayout &DL;
3989 const CodeGenOptions &Opts;
3990
3991 /// Original Address.
3992 Value *Original;
3993
3994 /// Common value among addresses
3995 Value *CommonValue = nullptr;
3996
3997public:
3998 AddressingModeCombiner(const DataLayout &DL, const CodeGenOptions &Opts,
3999 Value *OriginalValue)
4000 : DL(DL), Opts(Opts), Original(OriginalValue) {}
4001
4002 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4003
4004 /// Get the combined AddrMode
4005 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4006
4007 /// Add a new AddrMode if it's compatible with the AddrModes we already
4008 /// have.
4009 /// \return True iff we succeeded in doing so.
4010 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4011 // Take note of if we have any non-trivial AddrModes, as we need to detect
4012 // when all AddrModes are trivial as then we would introduce a phi or select
4013 // which just duplicates what's already there.
4014 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4015
4016 // If this is the first addrmode then everything is fine.
4017 if (AddrModes.empty()) {
4018 AddrModes.emplace_back(NewAddrMode);
4019 return true;
4020 }
4021
4022 // Figure out how different this is from the other address modes, which we
4023 // can do just by comparing against the first one given that we only care
4024 // about the cumulative difference.
4025 ExtAddrMode::FieldName ThisDifferentField =
4026 AddrModes[0].compare(NewAddrMode);
4027 if (DifferentField == ExtAddrMode::NoField)
4028 DifferentField = ThisDifferentField;
4029 else if (DifferentField != ThisDifferentField)
4030 DifferentField = ExtAddrMode::MultipleFields;
4031
4032 // If NewAddrMode differs in more than one dimension we cannot handle it.
4033 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4034
4035 // If Scale Field is different then we reject.
4036 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4037
4038 // We also must reject the case when base offset is different and
4039 // scale reg is not null, we cannot handle this case due to merge of
4040 // different offsets will be used as ScaleReg.
4041 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4042 !NewAddrMode.ScaledReg);
4043
4044 // We also must reject the case when GV is different and BaseReg installed
4045 // due to we want to use base reg as a merge of GV values.
4046 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4047 !NewAddrMode.HasBaseReg);
4048
4049 // Even if NewAddMode is the same we still need to collect it due to
4050 // original value is different. And later we will need all original values
4051 // as anchors during finding the common Phi node.
4052 if (CanHandle)
4053 AddrModes.emplace_back(NewAddrMode);
4054 else
4055 AddrModes.clear();
4056
4057 return CanHandle;
4058 }
4059
4060 /// Combine the addressing modes we've collected into a single
4061 /// addressing mode.
4062 /// \return True iff we successfully combined them or we only had one so
4063 /// didn't need to combine them anyway.
4064 bool combineAddrModes() {
4065 // If we have no AddrModes then they can't be combined.
4066 if (AddrModes.size() == 0)
4067 return false;
4068
4069 // A single AddrMode can trivially be combined.
4070 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4071 return true;
4072
4073 // If the AddrModes we collected are all just equal to the value they are
4074 // derived from then combining them wouldn't do anything useful.
4075 if (AllAddrModesTrivial)
4076 return false;
4077
4078 if (!addrModeCombiningAllowed())
4079 return false;
4080
4081 // Build a map between <original value, basic block where we saw it> to
4082 // value of base register.
4083 // Bail out if there is no common type.
4084 FoldAddrToValueMapping Map;
4085 if (!initializeMap(Map))
4086 return false;
4087
4088 CommonValue = findCommon(Map);
4089 if (CommonValue)
4090 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4091 return CommonValue != nullptr;
4092 }
4093
4094private:
4095 /// `CommonValue` may be a placeholder inserted by us.
4096 /// If the placeholder is not used, we should remove this dead instruction.
4097 void eraseCommonValueIfDead() {
4098 if (CommonValue && CommonValue->use_empty())
4099 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
4100 CommonInst->eraseFromParent();
4101 }
4102
4103 /// Initialize Map with anchor values. For address seen
4104 /// we set the value of different field saw in this address.
4105 /// At the same time we find a common type for different field we will
4106 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4107 /// Return false if there is no common type found.
4108 bool initializeMap(FoldAddrToValueMapping &Map) {
4109 // Keep track of keys where the value is null. We will need to replace it
4110 // with constant null when we know the common type.
4111 SmallVector<Value *, 2> NullValue;
4112 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4113 for (auto &AM : AddrModes) {
4114 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
4115 if (DV) {
4116 auto *Type = DV->getType();
4117 if (CommonType && CommonType != Type)
4118 return false;
4119 CommonType = Type;
4120 Map[AM.OriginalValue] = DV;
4121 } else {
4122 NullValue.push_back(AM.OriginalValue);
4123 }
4124 }
4125 assert(CommonType && "At least one non-null value must be!");
4126 for (auto *V : NullValue)
4127 Map[V] = Constant::getNullValue(CommonType);
4128 return true;
4129 }
4130
4131 /// We have mapping between value A and other value B where B was a field in
4132 /// addressing mode represented by A. Also we have an original value C
4133 /// representing an address we start with. Traversing from C through phi and
4134 /// selects we ended up with A's in a map. This utility function tries to find
4135 /// a value V which is a field in addressing mode C and traversing through phi
4136 /// nodes and selects we will end up in corresponded values B in a map.
4137 /// The utility will create a new Phi/Selects if needed.
4138 // The simple example looks as follows:
4139 // BB1:
4140 // p1 = b1 + 40
4141 // br cond BB2, BB3
4142 // BB2:
4143 // p2 = b2 + 40
4144 // br BB3
4145 // BB3:
4146 // p = phi [p1, BB1], [p2, BB2]
4147 // v = load p
4148 // Map is
4149 // p1 -> b1
4150 // p2 -> b2
4151 // Request is
4152 // p -> ?
4153 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4154 Value *findCommon(FoldAddrToValueMapping &Map) {
4155 // Tracks the simplification of newly created phi nodes. The reason we use
4156 // this mapping is because we will add new created Phi nodes in AddrToBase.
4157 // Simplification of Phi nodes is recursive, so some Phi node may
4158 // be simplified after we added it to AddrToBase. In reality this
4159 // simplification is possible only if original phi/selects were not
4160 // simplified yet.
4161 // Using this mapping we can find the current value in AddrToBase.
4162 SimplificationTracker ST;
4163
4164 // First step, DFS to create PHI nodes for all intermediate blocks.
4165 // Also fill traverse order for the second step.
4166 SmallVector<Value *, 32> TraverseOrder;
4167 InsertPlaceholders(Map, TraverseOrder, ST);
4168
4169 // Second Step, fill new nodes by merged values and simplify if possible.
4170 FillPlaceholders(Map, TraverseOrder, ST);
4171
4172 if (!Opts.cgp_addr_sink_new_select && ST.countNewSelectNodes() > 0) {
4173 ST.destroyNewNodes(CommonType);
4174 return nullptr;
4175 }
4176
4177 // Now we'd like to match New Phi nodes to existed ones.
4178 unsigned PhiNotMatchedCount = 0;
4179 if (!MatchPhiSet(ST, Opts.cgp_addr_sink_new_phis, PhiNotMatchedCount)) {
4180 ST.destroyNewNodes(CommonType);
4181 return nullptr;
4182 }
4183
4184 auto *Result = ST.Get(Map.find(Original)->second);
4185 if (Result) {
4186 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4187 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4188 }
4189 return Result;
4190 }
4191
4192 /// Try to match PHI node to Candidate.
4193 /// Matcher tracks the matched Phi nodes.
4194 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4195 SmallSetVector<PHIPair, 8> &Matcher,
4196 PhiNodeSet &PhiNodesToMatch) {
4197 SmallVector<PHIPair, 8> WorkList;
4198 Matcher.insert({PHI, Candidate});
4199 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4200 MatchedPHIs.insert(PHI);
4201 WorkList.push_back({PHI, Candidate});
4202 SmallSet<PHIPair, 8> Visited;
4203 while (!WorkList.empty()) {
4204 auto Item = WorkList.pop_back_val();
4205 if (!Visited.insert(Item).second)
4206 continue;
4207 // We iterate over all incoming values to Phi to compare them.
4208 // If values are different and both of them Phi and the first one is a
4209 // Phi we added (subject to match) and both of them is in the same basic
4210 // block then we can match our pair if values match. So we state that
4211 // these values match and add it to work list to verify that.
4212 for (auto *B : Item.first->blocks()) {
4213 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4214 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4215 if (FirstValue == SecondValue)
4216 continue;
4217
4218 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4219 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4220
4221 // One of them is not Phi or
4222 // The first one is not Phi node from the set we'd like to match or
4223 // Phi nodes from different basic blocks then
4224 // we will not be able to match.
4225 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4226 FirstPhi->getParent() != SecondPhi->getParent())
4227 return false;
4228
4229 // If we already matched them then continue.
4230 if (Matcher.count({FirstPhi, SecondPhi}))
4231 continue;
4232 // So the values are different and does not match. So we need them to
4233 // match. (But we register no more than one match per PHI node, so that
4234 // we won't later try to replace them twice.)
4235 if (MatchedPHIs.insert(FirstPhi).second)
4236 Matcher.insert({FirstPhi, SecondPhi});
4237 // But me must check it.
4238 WorkList.push_back({FirstPhi, SecondPhi});
4239 }
4240 }
4241 return true;
4242 }
4243
4244 /// For the given set of PHI nodes (in the SimplificationTracker) try
4245 /// to find their equivalents.
4246 /// Returns false if this matching fails and creation of new Phi is disabled.
4247 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4248 unsigned &PhiNotMatchedCount) {
4249 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4250 // order, so the replacements (ReplacePhi) are also done in a deterministic
4251 // order.
4252 SmallSetVector<PHIPair, 8> Matched;
4253 SmallPtrSet<PHINode *, 8> WillNotMatch;
4254 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4255 while (PhiNodesToMatch.size()) {
4256 PHINode *PHI = *PhiNodesToMatch.begin();
4257
4258 // Add us, if no Phi nodes in the basic block we do not match.
4259 WillNotMatch.clear();
4260 WillNotMatch.insert(PHI);
4261
4262 // Traverse all Phis until we found equivalent or fail to do that.
4263 bool IsMatched = false;
4264 for (auto &P : PHI->getParent()->phis()) {
4265 // Skip new Phi nodes.
4266 if (PhiNodesToMatch.count(&P))
4267 continue;
4268 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4269 break;
4270 // If it does not match, collect all Phi nodes from matcher.
4271 // if we end up with no match, them all these Phi nodes will not match
4272 // later.
4273 WillNotMatch.insert_range(llvm::make_first_range(Matched));
4274 Matched.clear();
4275 }
4276 if (IsMatched) {
4277 // Replace all matched values and erase them.
4278 for (auto MV : Matched)
4279 ST.ReplacePhi(MV.first, MV.second);
4280 Matched.clear();
4281 continue;
4282 }
4283 // If we are not allowed to create new nodes then bail out.
4284 if (!AllowNewPhiNodes)
4285 return false;
4286 // Just remove all seen values in matcher. They will not match anything.
4287 PhiNotMatchedCount += WillNotMatch.size();
4288 for (auto *P : WillNotMatch)
4289 PhiNodesToMatch.erase(P);
4290 }
4291 return true;
4292 }
4293 /// Fill the placeholders with values from predecessors and simplify them.
4294 void FillPlaceholders(FoldAddrToValueMapping &Map,
4295 SmallVectorImpl<Value *> &TraverseOrder,
4296 SimplificationTracker &ST) {
4297 while (!TraverseOrder.empty()) {
4298 Value *Current = TraverseOrder.pop_back_val();
4299 assert(Map.contains(Current) && "No node to fill!!!");
4300 Value *V = Map[Current];
4301
4302 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4303 // CurrentValue also must be Select.
4304 auto *CurrentSelect = cast<SelectInst>(Current);
4305 auto *TrueValue = CurrentSelect->getTrueValue();
4306 assert(Map.contains(TrueValue) && "No True Value!");
4307 Select->setTrueValue(ST.Get(Map[TrueValue]));
4308 auto *FalseValue = CurrentSelect->getFalseValue();
4309 assert(Map.contains(FalseValue) && "No False Value!");
4310 Select->setFalseValue(ST.Get(Map[FalseValue]));
4311 } else {
4312 // Must be a Phi node then.
4313 auto *PHI = cast<PHINode>(V);
4314 // Fill the Phi node with values from predecessors.
4315 for (auto *B : predecessors(PHI->getParent())) {
4316 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4317 assert(Map.contains(PV) && "No predecessor Value!");
4318 PHI->addIncoming(ST.Get(Map[PV]), B);
4319 }
4320 }
4321 }
4322 }
4323
4324 /// Starting from original value recursively iterates over def-use chain up to
4325 /// known ending values represented in a map. For each traversed phi/select
4326 /// inserts a placeholder Phi or Select.
4327 /// Reports all new created Phi/Select nodes by adding them to set.
4328 /// Also reports and order in what values have been traversed.
4329 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4330 SmallVectorImpl<Value *> &TraverseOrder,
4331 SimplificationTracker &ST) {
4332 SmallVector<Value *, 32> Worklist;
4333 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4334 "Address must be a Phi or Select node");
4335 auto *Dummy = PoisonValue::get(CommonType);
4336 Worklist.push_back(Original);
4337 while (!Worklist.empty()) {
4338 Value *Current = Worklist.pop_back_val();
4339 // if it is already visited or it is an ending value then skip it.
4340 if (Map.contains(Current))
4341 continue;
4342 TraverseOrder.push_back(Current);
4343
4344 // CurrentValue must be a Phi node or select. All others must be covered
4345 // by anchors.
4346 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4347 // Is it OK to get metadata from OrigSelect?!
4348 // Create a Select placeholder with dummy value.
4349 SelectInst *Select =
4350 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4351 CurrentSelect->getName(),
4352 CurrentSelect->getIterator(), CurrentSelect);
4353 Map[Current] = Select;
4354 ST.insertNewSelect(Select);
4355 // We are interested in True and False values.
4356 Worklist.push_back(CurrentSelect->getTrueValue());
4357 Worklist.push_back(CurrentSelect->getFalseValue());
4358 } else {
4359 // It must be a Phi node then.
4360 PHINode *CurrentPhi = cast<PHINode>(Current);
4361 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4362 PHINode *PHI =
4363 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4364 Map[Current] = PHI;
4365 ST.insertNewPhi(PHI);
4366 append_range(Worklist, CurrentPhi->incoming_values());
4367 }
4368 }
4369 }
4370
4371 bool addrModeCombiningAllowed() {
4372 if (!Opts.cgp_complex_addr_modes)
4373 return false;
4374 switch (DifferentField) {
4375 default:
4376 return false;
4377 case ExtAddrMode::BaseRegField:
4378 return Opts.cgp_addr_sink_combine_base_reg;
4379 case ExtAddrMode::BaseGVField:
4380 return Opts.cgp_addr_sink_combine_base_gv;
4381 case ExtAddrMode::BaseOffsField:
4382 return Opts.cgp_addr_sink_combine_base_offs;
4383 case ExtAddrMode::ScaledRegField:
4384 return Opts.cgp_addr_sink_combine_scaled_reg;
4385 }
4386 }
4387};
4388} // end anonymous namespace
4389
4390/// Try adding ScaleReg*Scale to the current addressing mode.
4391/// Return true and update AddrMode if this addr mode is legal for the target,
4392/// false if not.
4393bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4394 unsigned Depth) {
4395 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4396 // mode. Just process that directly.
4397 if (Scale == 1)
4398 return matchAddr(ScaleReg, Depth);
4399
4400 // If the scale is 0, it takes nothing to add this.
4401 if (Scale == 0)
4402 return true;
4403
4404 // If we already have a scale of this value, we can add to it, otherwise, we
4405 // need an available scale field.
4406 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4407 return false;
4408
4409 ExtAddrMode TestAddrMode = AddrMode;
4410
4411 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4412 // [A+B + A*7] -> [B+A*8].
4413 TestAddrMode.Scale += Scale;
4414 TestAddrMode.ScaledReg = ScaleReg;
4415
4416 // If the new address isn't legal, bail out.
4417 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4418 return false;
4419
4420 // It was legal, so commit it.
4421 AddrMode = TestAddrMode;
4422
4423 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4424 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4425 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4426 // go any further: we can reuse it and cannot eliminate it.
4427 ConstantInt *CI = nullptr;
4428 Value *AddLHS = nullptr;
4429 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4430 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4431 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4432 TestAddrMode.InBounds = false;
4433 TestAddrMode.ScaledReg = AddLHS;
4434 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4435
4436 // If this addressing mode is legal, commit it and remember that we folded
4437 // this instruction.
4438 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4439 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4440 AddrMode = TestAddrMode;
4441 return true;
4442 }
4443 // Restore status quo.
4444 TestAddrMode = AddrMode;
4445 }
4446
4447 // If this is an add recurrence with a constant step, return the increment
4448 // instruction and the canonicalized step.
4449 auto GetConstantStep =
4450 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4451 auto *PN = dyn_cast<PHINode>(V);
4452 if (!PN)
4453 return std::nullopt;
4454 auto IVInc = getIVIncrement(PN, &LI);
4455 if (!IVInc)
4456 return std::nullopt;
4457 // TODO: The result of the intrinsics above is two-complement. However when
4458 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4459 // If it has nuw or nsw flags, we need to make sure that these flags are
4460 // inferrable at the point of memory instruction. Otherwise we are replacing
4461 // well-defined two-complement computation with poison. Currently, to avoid
4462 // potentially complex analysis needed to prove this, we reject such cases.
4463 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4464 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4465 return std::nullopt;
4466 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4467 return std::make_pair(IVInc->first, ConstantStep->getValue());
4468 return std::nullopt;
4469 };
4470
4471 // Try to account for the following special case:
4472 // 1. ScaleReg is an inductive variable;
4473 // 2. We use it with non-zero offset;
4474 // 3. IV's increment is available at the point of memory instruction.
4475 //
4476 // In this case, we may reuse the IV increment instead of the IV Phi to
4477 // achieve the following advantages:
4478 // 1. If IV step matches the offset, we will have no need in the offset;
4479 // 2. Even if they don't match, we will reduce the overlap of living IV
4480 // and IV increment, that will potentially lead to better register
4481 // assignment.
4482 if (AddrMode.BaseOffs) {
4483 if (auto IVStep = GetConstantStep(ScaleReg)) {
4484 Instruction *IVInc = IVStep->first;
4485 // The following assert is important to ensure a lack of infinite loops.
4486 // This transforms is (intentionally) the inverse of the one just above.
4487 // If they don't agree on the definition of an increment, we'd alternate
4488 // back and forth indefinitely.
4489 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4490 APInt Step = IVStep->second;
4491 APInt Offset = Step * AddrMode.Scale;
4492 if (Offset.isSignedIntN(64)) {
4493 TestAddrMode.InBounds = false;
4494 TestAddrMode.ScaledReg = IVInc;
4495 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4496 // If this addressing mode is legal, commit it..
4497 // (Note that we defer the (expensive) domtree base legality check
4498 // to the very last possible point.)
4499 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4500 getDTFn().dominates(IVInc, MemoryInst)) {
4501 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4502 AddrMode = TestAddrMode;
4503 return true;
4504 }
4505 // Restore status quo.
4506 TestAddrMode = AddrMode;
4507 }
4508 }
4509 }
4510
4511 // Otherwise, just return what we have.
4512 return true;
4513}
4514
4515/// This is a little filter, which returns true if an addressing computation
4516/// involving I might be folded into a load/store accessing it.
4517/// This doesn't need to be perfect, but needs to accept at least
4518/// the set of instructions that MatchOperationAddr can.
4520 switch (I->getOpcode()) {
4521 case Instruction::BitCast:
4522 case Instruction::AddrSpaceCast:
4523 // Don't touch identity bitcasts.
4524 if (I->getType() == I->getOperand(0)->getType())
4525 return false;
4526 return I->getType()->isIntOrPtrTy();
4527 case Instruction::PtrToInt:
4528 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4529 return true;
4530 case Instruction::IntToPtr:
4531 // We know the input is intptr_t, so this is foldable.
4532 return true;
4533 case Instruction::Add:
4534 return true;
4535 case Instruction::Or:
4536 return cast<PossiblyDisjointInst>(I)->isDisjoint();
4537 case Instruction::Mul:
4538 case Instruction::Shl:
4539 // Can only handle X*C and X << C.
4540 return isa<ConstantInt>(I->getOperand(1));
4541 case Instruction::GetElementPtr:
4542 return true;
4543 default:
4544 return false;
4545 }
4546}
4547
4548/// Check whether or not \p Val is a legal instruction for \p TLI.
4549/// \note \p Val is assumed to be the product of some type promotion.
4550/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4551/// to be legal, as the non-promoted value would have had the same state.
4553 const DataLayout &DL, Value *Val) {
4554 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4555 if (!PromotedInst)
4556 return false;
4557 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4558 // If the ISDOpcode is undefined, it was undefined before the promotion.
4559 if (!ISDOpcode)
4560 return true;
4561 // Otherwise, check if the promoted instruction is legal or not.
4562 return TLI.isOperationLegalOrCustom(
4563 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4564}
4565
4566namespace {
4567
4568/// Hepler class to perform type promotion.
4569class TypePromotionHelper {
4570 /// Utility function to add a promoted instruction \p ExtOpnd to
4571 /// \p PromotedInsts and record the type of extension we have seen.
4572 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4573 Instruction *ExtOpnd, bool IsSExt) {
4574 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4575 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4576 if (!Inserted) {
4577 // If the new extension is same as original, the information in
4578 // PromotedInsts[ExtOpnd] is still correct.
4579 if (It->second.getInt() == ExtTy)
4580 return;
4581
4582 // Now the new extension is different from old extension, we make
4583 // the type information invalid by setting extension type to
4584 // BothExtension.
4585 ExtTy = BothExtension;
4586 }
4587 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4588 }
4589
4590 /// Utility function to query the original type of instruction \p Opnd
4591 /// with a matched extension type. If the extension doesn't match, we
4592 /// cannot use the information we had on the original type.
4593 /// BothExtension doesn't match any extension type.
4594 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4595 Instruction *Opnd, bool IsSExt) {
4596 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4597 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4598 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4599 return It->second.getPointer();
4600 return nullptr;
4601 }
4602
4603 /// Utility function to check whether or not a sign or zero extension
4604 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4605 /// either using the operands of \p Inst or promoting \p Inst.
4606 /// The type of the extension is defined by \p IsSExt.
4607 /// In other words, check if:
4608 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4609 /// #1 Promotion applies:
4610 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4611 /// #2 Operand reuses:
4612 /// ext opnd1 to ConsideredExtType.
4613 /// \p PromotedInsts maps the instructions to their type before promotion.
4614 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4615 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4616
4617 /// Utility function to determine if \p OpIdx should be promoted when
4618 /// promoting \p Inst.
4619 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4620 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4621 }
4622
4623 /// Utility function to promote the operand of \p Ext when this
4624 /// operand is a promotable trunc or sext or zext.
4625 /// \p PromotedInsts maps the instructions to their type before promotion.
4626 /// \p CreatedInstsCost[out] contains the cost of all instructions
4627 /// created to promote the operand of Ext.
4628 /// Newly added extensions are inserted in \p Exts.
4629 /// Newly added truncates are inserted in \p Truncs.
4630 /// Should never be called directly.
4631 /// \return The promoted value which is used instead of Ext.
4632 static Value *promoteOperandForTruncAndAnyExt(
4633 Instruction *Ext, TypePromotionTransaction &TPT,
4634 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4635 SmallVectorImpl<Instruction *> *Exts,
4636 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4637
4638 /// Utility function to promote the operand of \p Ext when this
4639 /// operand is promotable and is not a supported trunc or sext.
4640 /// \p PromotedInsts maps the instructions to their type before promotion.
4641 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4642 /// created to promote the operand of Ext.
4643 /// Newly added extensions are inserted in \p Exts.
4644 /// Newly added truncates are inserted in \p Truncs.
4645 /// Should never be called directly.
4646 /// \return The promoted value which is used instead of Ext.
4647 static Value *promoteOperandForOther(Instruction *Ext,
4648 TypePromotionTransaction &TPT,
4649 InstrToOrigTy &PromotedInsts,
4650 unsigned &CreatedInstsCost,
4651 SmallVectorImpl<Instruction *> *Exts,
4652 SmallVectorImpl<Instruction *> *Truncs,
4653 const TargetLowering &TLI, bool IsSExt);
4654
4655 /// \see promoteOperandForOther.
4656 static Value *signExtendOperandForOther(
4657 Instruction *Ext, TypePromotionTransaction &TPT,
4658 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4659 SmallVectorImpl<Instruction *> *Exts,
4660 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4661 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4662 Exts, Truncs, TLI, true);
4663 }
4664
4665 /// \see promoteOperandForOther.
4666 static Value *zeroExtendOperandForOther(
4667 Instruction *Ext, TypePromotionTransaction &TPT,
4668 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4669 SmallVectorImpl<Instruction *> *Exts,
4670 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4671 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4672 Exts, Truncs, TLI, false);
4673 }
4674
4675public:
4676 /// Type for the utility function that promotes the operand of Ext.
4677 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4678 InstrToOrigTy &PromotedInsts,
4679 unsigned &CreatedInstsCost,
4680 SmallVectorImpl<Instruction *> *Exts,
4681 SmallVectorImpl<Instruction *> *Truncs,
4682 const TargetLowering &TLI);
4683
4684 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4685 /// action to promote the operand of \p Ext instead of using Ext.
4686 /// \return NULL if no promotable action is possible with the current
4687 /// sign extension.
4688 /// \p InsertedInsts keeps track of all the instructions inserted by the
4689 /// other CodeGenPrepare optimizations. This information is important
4690 /// because we do not want to promote these instructions as CodeGenPrepare
4691 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4692 /// \p PromotedInsts maps the instructions to their type before promotion.
4693 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4694 const TargetLowering &TLI,
4695 const InstrToOrigTy &PromotedInsts);
4696};
4697
4698} // end anonymous namespace
4699
4700bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4701 Type *ConsideredExtType,
4702 const InstrToOrigTy &PromotedInsts,
4703 bool IsSExt) {
4704 // The promotion helper does not know how to deal with vector types yet.
4705 // To be able to fix that, we would need to fix the places where we
4706 // statically extend, e.g., constants and such.
4707 if (Inst->getType()->isVectorTy())
4708 return false;
4709
4710 // We can always get through zext.
4711 if (isa<ZExtInst>(Inst))
4712 return true;
4713
4714 // sext(sext) is ok too.
4715 if (IsSExt && isa<SExtInst>(Inst))
4716 return true;
4717
4718 // We can get through binary operator, if it is legal. In other words, the
4719 // binary operator must have a nuw or nsw flag.
4720 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4721 if (isa<OverflowingBinaryOperator>(BinOp) &&
4722 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4723 (IsSExt && BinOp->hasNoSignedWrap())))
4724 return true;
4725
4726 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4727 if ((Inst->getOpcode() == Instruction::And ||
4728 Inst->getOpcode() == Instruction::Or))
4729 return true;
4730
4731 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4732 if (Inst->getOpcode() == Instruction::Xor) {
4733 // Make sure it is not a NOT.
4734 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4735 if (!Cst->getValue().isAllOnes())
4736 return true;
4737 }
4738
4739 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4740 // It may change a poisoned value into a regular value, like
4741 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4742 // poisoned value regular value
4743 // It should be OK since undef covers valid value.
4744 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4745 return true;
4746
4747 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4748 // It may change a poisoned value into a regular value, like
4749 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4750 // poisoned value regular value
4751 // It should be OK since undef covers valid value.
4752 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4753 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4754 if (ExtInst->hasOneUse()) {
4755 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4756 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4757 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4758 if (Cst &&
4759 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4760 return true;
4761 }
4762 }
4763 }
4764
4765 // Check if we can do the following simplification.
4766 // ext(trunc(opnd)) --> ext(opnd)
4767 if (!isa<TruncInst>(Inst))
4768 return false;
4769
4770 Value *OpndVal = Inst->getOperand(0);
4771 // Check if we can use this operand in the extension.
4772 // If the type is larger than the result type of the extension, we cannot.
4773 if (!OpndVal->getType()->isIntegerTy() ||
4774 OpndVal->getType()->getIntegerBitWidth() >
4775 ConsideredExtType->getIntegerBitWidth())
4776 return false;
4777
4778 // If the operand of the truncate is not an instruction, we will not have
4779 // any information on the dropped bits.
4780 // (Actually we could for constant but it is not worth the extra logic).
4781 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4782 if (!Opnd)
4783 return false;
4784
4785 // Check if the source of the type is narrow enough.
4786 // I.e., check that trunc just drops extended bits of the same kind of
4787 // the extension.
4788 // #1 get the type of the operand and check the kind of the extended bits.
4789 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4790 if (OpndType)
4791 ;
4792 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4793 OpndType = Opnd->getOperand(0)->getType();
4794 else
4795 return false;
4796
4797 // #2 check that the truncate just drops extended bits.
4798 return Inst->getType()->getIntegerBitWidth() >=
4799 OpndType->getIntegerBitWidth();
4800}
4801
4802TypePromotionHelper::Action TypePromotionHelper::getAction(
4803 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4804 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4805 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4806 "Unexpected instruction type");
4807 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4808 Type *ExtTy = Ext->getType();
4809 bool IsSExt = isa<SExtInst>(Ext);
4810 // If the operand of the extension is not an instruction, we cannot
4811 // get through.
4812 // If it, check we can get through.
4813 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4814 return nullptr;
4815
4816 // Do not promote if the operand has been added by codegenprepare.
4817 // Otherwise, it means we are undoing an optimization that is likely to be
4818 // redone, thus causing potential infinite loop.
4819 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4820 return nullptr;
4821
4822 // SExt or Trunc instructions.
4823 // Return the related handler.
4824 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4825 isa<ZExtInst>(ExtOpnd))
4826 return promoteOperandForTruncAndAnyExt;
4827
4828 // Regular instruction.
4829 // Abort early if we will have to insert non-free instructions.
4830 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4831 return nullptr;
4832 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4833}
4834
4835Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4836 Instruction *SExt, TypePromotionTransaction &TPT,
4837 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4838 SmallVectorImpl<Instruction *> *Exts,
4839 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4840 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4841 // get through it and this method should not be called.
4842 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4843 Value *ExtVal = SExt;
4844 bool HasMergedNonFreeExt = false;
4845 if (isa<ZExtInst>(SExtOpnd)) {
4846 // Replace s|zext(zext(opnd))
4847 // => zext(opnd).
4848 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4849 Value *ZExt =
4850 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4851 TPT.replaceAllUsesWith(SExt, ZExt);
4852 TPT.eraseInstruction(SExt);
4853 ExtVal = ZExt;
4854 } else {
4855 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4856 // => z|sext(opnd).
4857 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4858 }
4859 CreatedInstsCost = 0;
4860
4861 // Remove dead code.
4862 if (SExtOpnd->use_empty())
4863 TPT.eraseInstruction(SExtOpnd);
4864
4865 // Check if the extension is still needed.
4866 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4867 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4868 if (ExtInst) {
4869 if (Exts)
4870 Exts->push_back(ExtInst);
4871 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4872 }
4873 return ExtVal;
4874 }
4875
4876 // At this point we have: ext ty opnd to ty.
4877 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4878 Value *NextVal = ExtInst->getOperand(0);
4879 TPT.eraseInstruction(ExtInst, NextVal);
4880 return NextVal;
4881}
4882
4883Value *TypePromotionHelper::promoteOperandForOther(
4884 Instruction *Ext, TypePromotionTransaction &TPT,
4885 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4886 SmallVectorImpl<Instruction *> *Exts,
4887 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4888 bool IsSExt) {
4889 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4890 // get through it and this method should not be called.
4891 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4892 CreatedInstsCost = 0;
4893 if (!ExtOpnd->hasOneUse()) {
4894 // ExtOpnd will be promoted.
4895 // All its uses, but Ext, will need to use a truncated value of the
4896 // promoted version.
4897 // Create the truncate now.
4898 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4899 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4900 // Insert it just after the definition.
4901 ITrunc->moveAfter(ExtOpnd);
4902 if (Truncs)
4903 Truncs->push_back(ITrunc);
4904 }
4905
4906 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4907 // Restore the operand of Ext (which has been replaced by the previous call
4908 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4909 TPT.setOperand(Ext, 0, ExtOpnd);
4910 }
4911
4912 // Get through the Instruction:
4913 // 1. Update its type.
4914 // 2. Replace the uses of Ext by Inst.
4915 // 3. Extend each operand that needs to be extended.
4916
4917 // Remember the original type of the instruction before promotion.
4918 // This is useful to know that the high bits are sign extended bits.
4919 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4920 // Step #1.
4921 TPT.mutateType(ExtOpnd, Ext->getType());
4922 // Step #2.
4923 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4924 // Step #3.
4925 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4926 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4927 ++OpIdx) {
4928 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4929 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4930 !shouldExtOperand(ExtOpnd, OpIdx)) {
4931 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4932 continue;
4933 }
4934 // Check if we can statically extend the operand.
4935 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4936 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4937 LLVM_DEBUG(dbgs() << "Statically extend\n");
4938 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4939 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4940 : Cst->getValue().zext(BitWidth);
4941 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4942 continue;
4943 }
4944 // UndefValue are typed, so we have to statically sign extend them.
4945 if (isa<UndefValue>(Opnd)) {
4946 LLVM_DEBUG(dbgs() << "Statically extend\n");
4947 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4948 continue;
4949 }
4950
4951 // Otherwise we have to explicitly sign extend the operand.
4952 Value *ValForExtOpnd = IsSExt
4953 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
4954 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
4955 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4956 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
4957 if (!InstForExtOpnd)
4958 continue;
4959
4960 if (Exts)
4961 Exts->push_back(InstForExtOpnd);
4962
4963 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
4964 }
4965 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
4966 TPT.eraseInstruction(Ext);
4967 return ExtOpnd;
4968}
4969
4970/// Check whether or not promoting an instruction to a wider type is profitable.
4971/// \p NewCost gives the cost of extension instructions created by the
4972/// promotion.
4973/// \p OldCost gives the cost of extension instructions before the promotion
4974/// plus the number of instructions that have been
4975/// matched in the addressing mode the promotion.
4976/// \p PromotedOperand is the value that has been promoted.
4977/// \return True if the promotion is profitable, false otherwise.
4978bool AddressingModeMatcher::isPromotionProfitable(
4979 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4980 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4981 << '\n');
4982 // The cost of the new extensions is greater than the cost of the
4983 // old extension plus what we folded.
4984 // This is not profitable.
4985 if (NewCost > OldCost)
4986 return false;
4987 if (NewCost < OldCost)
4988 return true;
4989 // The promotion is neutral but it may help folding the sign extension in
4990 // loads for instance.
4991 // Check that we did not create an illegal instruction.
4992 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4993}
4994
4995/// Given an instruction or constant expr, see if we can fold the operation
4996/// into the addressing mode. If so, update the addressing mode and return
4997/// true, otherwise return false without modifying AddrMode.
4998/// If \p MovedAway is not NULL, it contains the information of whether or
4999/// not AddrInst has to be folded into the addressing mode on success.
5000/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5001/// because it has been moved away.
5002/// Thus AddrInst must not be added in the matched instructions.
5003/// This state can happen when AddrInst is a sext, since it may be moved away.
5004/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5005/// not be referenced anymore.
5006bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5007 unsigned Depth,
5008 bool *MovedAway) {
5009 // Avoid exponential behavior on extremely deep expression trees.
5010 if (Depth >= 5)
5011 return false;
5012
5013 // By default, all matched instructions stay in place.
5014 if (MovedAway)
5015 *MovedAway = false;
5016
5017 switch (Opcode) {
5018 case Instruction::PtrToInt:
5019 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5020 return matchAddr(AddrInst->getOperand(0), Depth);
5021 case Instruction::IntToPtr: {
5022 auto AS = AddrInst->getType()->getPointerAddressSpace();
5023 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5024 // This inttoptr is a no-op if the integer type is pointer sized.
5025 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5026 return matchAddr(AddrInst->getOperand(0), Depth);
5027 return false;
5028 }
5029 case Instruction::BitCast:
5030 // BitCast is always a noop, and we can handle it as long as it is
5031 // int->int or pointer->pointer (we don't want int<->fp or something).
5032 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5033 // Don't touch identity bitcasts. These were probably put here by LSR,
5034 // and we don't want to mess around with them. Assume it knows what it
5035 // is doing.
5036 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5037 return matchAddr(AddrInst->getOperand(0), Depth);
5038 return false;
5039 case Instruction::AddrSpaceCast: {
5040 unsigned SrcAS =
5041 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5042 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5043 if (TLI.getTargetMachine().isNoopAddrSpaceCast(DL, SrcAS, DestAS))
5044 return matchAddr(AddrInst->getOperand(0), Depth);
5045 return false;
5046 }
5047 case Instruction::Or:
5048 if (!cast<PossiblyDisjointInst>(AddrInst)->isDisjoint())
5049 return false;
5050 [[fallthrough]];
5051 case Instruction::Add: {
5052 // Check to see if we can merge in one operand, then the other. If so, we
5053 // win.
5054 ExtAddrMode BackupAddrMode = AddrMode;
5055 unsigned OldSize = AddrModeInsts.size();
5056 // Start a transaction at this point.
5057 // The LHS may match but not the RHS.
5058 // Therefore, we need a higher level restoration point to undo partially
5059 // matched operation.
5060 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5061 TPT.getRestorationPoint();
5062
5063 // Try to match an integer constant second to increase its chance of ending
5064 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5065 int First = 0, Second = 1;
5066 if (isa<ConstantInt>(AddrInst->getOperand(First))
5067 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5068 std::swap(First, Second);
5069 AddrMode.InBounds = false;
5070 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5071 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5072 return true;
5073
5074 // Restore the old addr mode info.
5075 AddrMode = BackupAddrMode;
5076 AddrModeInsts.resize(OldSize);
5077 TPT.rollback(LastKnownGood);
5078
5079 // Otherwise this was over-aggressive. Try merging operands in the opposite
5080 // order.
5081 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5082 matchAddr(AddrInst->getOperand(First), Depth + 1))
5083 return true;
5084
5085 // Otherwise we definitely can't merge the ADD in.
5086 AddrMode = BackupAddrMode;
5087 AddrModeInsts.resize(OldSize);
5088 TPT.rollback(LastKnownGood);
5089 break;
5090 }
5091 case Instruction::Mul:
5092 case Instruction::Shl: {
5093 // Can only handle X*C and X << C.
5094 AddrMode.InBounds = false;
5095 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5096 if (!RHS || RHS->getBitWidth() > 64)
5097 return false;
5098 int64_t Scale = Opcode == Instruction::Shl
5099 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5100 : RHS->getSExtValue();
5101
5102 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5103 }
5104 case Instruction::GetElementPtr: {
5105 // Scan the GEP. We check it if it contains constant offsets and at most
5106 // one variable offset.
5107 int VariableOperand = -1;
5108 unsigned VariableScale = 0;
5109
5110 int64_t ConstantOffset = 0;
5111 gep_type_iterator GTI = gep_type_begin(AddrInst);
5112 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5113 if (StructType *STy = GTI.getStructTypeOrNull()) {
5114 const StructLayout *SL = DL.getStructLayout(STy);
5115 unsigned Idx =
5116 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5117 ConstantOffset += SL->getElementOffset(Idx);
5118 } else {
5119 TypeSize TS = GTI.getSequentialElementStride(DL);
5120 if (TS.isNonZero()) {
5121 // The optimisations below currently only work for fixed offsets.
5122 if (TS.isScalable())
5123 return false;
5124 int64_t TypeSize = TS.getFixedValue();
5125 if (ConstantInt *CI =
5126 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5127 const APInt &CVal = CI->getValue();
5128 if (CVal.getSignificantBits() <= 64) {
5129 ConstantOffset += CVal.getSExtValue() * TypeSize;
5130 continue;
5131 }
5132 }
5133 // We only allow one variable index at the moment.
5134 if (VariableOperand != -1)
5135 return false;
5136
5137 // Remember the variable index.
5138 VariableOperand = i;
5139 VariableScale = TypeSize;
5140 }
5141 }
5142 }
5143
5144 // A common case is for the GEP to only do a constant offset. In this case,
5145 // just add it to the disp field and check validity.
5146 if (VariableOperand == -1) {
5147 AddrMode.BaseOffs += ConstantOffset;
5148 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5149 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5150 AddrMode.InBounds = false;
5151 return true;
5152 }
5153 AddrMode.BaseOffs -= ConstantOffset;
5154
5155 if (Opts.cgp_split_large_offset_gep && isa<GetElementPtrInst>(AddrInst) &&
5157 ConstantOffset != 0) {
5158 // Record GEPs with non-zero offsets as candidates for splitting in
5159 // the event that the offset cannot fit into the r+i addressing mode.
5160 // Simple and common case that only one GEP is used in calculating the
5161 // address for the memory access.
5162 Value *Base = AddrInst->getOperand(0);
5163 auto *BaseI = dyn_cast<Instruction>(Base);
5164 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5166 (BaseI && !isa<CastInst>(BaseI) &&
5167 !isa<GetElementPtrInst>(BaseI))) {
5168 // Make sure the parent block allows inserting non-PHI instructions
5169 // before the terminator.
5170 BasicBlock *Parent =
5171 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
5172 if (!Parent->getTerminator()->isEHPad())
5173 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5174 }
5175 }
5176
5177 return false;
5178 }
5179
5180 // Save the valid addressing mode in case we can't match.
5181 ExtAddrMode BackupAddrMode = AddrMode;
5182 unsigned OldSize = AddrModeInsts.size();
5183
5184 // See if the scale and offset amount is valid for this target.
5185 AddrMode.BaseOffs += ConstantOffset;
5186 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5187 AddrMode.InBounds = false;
5188
5189 // Match the base operand of the GEP.
5190 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5191 // If it couldn't be matched, just stuff the value in a register.
5192 if (AddrMode.HasBaseReg) {
5193 AddrMode = BackupAddrMode;
5194 AddrModeInsts.resize(OldSize);
5195 return false;
5196 }
5197 AddrMode.HasBaseReg = true;
5198 AddrMode.BaseReg = AddrInst->getOperand(0);
5199 }
5200
5201 // Match the remaining variable portion of the GEP.
5202 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5203 Depth)) {
5204 // If it couldn't be matched, try stuffing the base into a register
5205 // instead of matching it, and retrying the match of the scale.
5206 AddrMode = BackupAddrMode;
5207 AddrModeInsts.resize(OldSize);
5208 if (AddrMode.HasBaseReg)
5209 return false;
5210 AddrMode.HasBaseReg = true;
5211 AddrMode.BaseReg = AddrInst->getOperand(0);
5212 AddrMode.BaseOffs += ConstantOffset;
5213 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5214 VariableScale, Depth)) {
5215 // If even that didn't work, bail.
5216 AddrMode = BackupAddrMode;
5217 AddrModeInsts.resize(OldSize);
5218 return false;
5219 }
5220 }
5221
5222 return true;
5223 }
5224 case Instruction::SExt:
5225 case Instruction::ZExt: {
5226 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5227 if (!Ext)
5228 return false;
5229
5230 // Try to move this ext out of the way of the addressing mode.
5231 // Ask for a method for doing so.
5232 TypePromotionHelper::Action TPH =
5233 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5234 if (!TPH)
5235 return false;
5236
5237 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5238 TPT.getRestorationPoint();
5239 unsigned CreatedInstsCost = 0;
5240 unsigned ExtCost = !TLI.isExtFree(Ext);
5241 Value *PromotedOperand =
5242 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5243 // SExt has been moved away.
5244 // Thus either it will be rematched later in the recursive calls or it is
5245 // gone. Anyway, we must not fold it into the addressing mode at this point.
5246 // E.g.,
5247 // op = add opnd, 1
5248 // idx = ext op
5249 // addr = gep base, idx
5250 // is now:
5251 // promotedOpnd = ext opnd <- no match here
5252 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5253 // addr = gep base, op <- match
5254 if (MovedAway)
5255 *MovedAway = true;
5256
5257 assert(PromotedOperand &&
5258 "TypePromotionHelper should have filtered out those cases");
5259
5260 ExtAddrMode BackupAddrMode = AddrMode;
5261 unsigned OldSize = AddrModeInsts.size();
5262
5263 if (!matchAddr(PromotedOperand, Depth) ||
5264 // The total of the new cost is equal to the cost of the created
5265 // instructions.
5266 // The total of the old cost is equal to the cost of the extension plus
5267 // what we have saved in the addressing mode.
5268 !isPromotionProfitable(CreatedInstsCost,
5269 ExtCost + (AddrModeInsts.size() - OldSize),
5270 PromotedOperand)) {
5271 AddrMode = BackupAddrMode;
5272 AddrModeInsts.resize(OldSize);
5273 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5274 TPT.rollback(LastKnownGood);
5275 return false;
5276 }
5277
5278 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5279 AddrMode.replaceWith(Ext, PromotedOperand);
5280 return true;
5281 }
5282 case Instruction::Call:
5283 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5284 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5285 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5287 return matchAddr(AddrInst->getOperand(0), Depth);
5288 }
5289 }
5290 break;
5291 }
5292 return false;
5293}
5294
5295/// If we can, try to add the value of 'Addr' into the current addressing mode.
5296/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5297/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5298/// for the target.
5299///
5300bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5301 // Start a transaction at this point that we will rollback if the matching
5302 // fails.
5303 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5304 TPT.getRestorationPoint();
5305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5306 if (CI->getValue().isSignedIntN(64)) {
5307 // Check if the addition would result in a signed overflow.
5308 int64_t Result;
5309 bool Overflow =
5310 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5311 if (!Overflow) {
5312 // Fold in immediates if legal for the target.
5313 AddrMode.BaseOffs = Result;
5314 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5315 return true;
5316 AddrMode.BaseOffs -= CI->getSExtValue();
5317 }
5318 }
5319 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5320 // If this is a global variable, try to fold it into the addressing mode.
5321 if (!AddrMode.BaseGV) {
5322 AddrMode.BaseGV = GV;
5323 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5324 return true;
5325 AddrMode.BaseGV = nullptr;
5326 }
5327 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5328 ExtAddrMode BackupAddrMode = AddrMode;
5329 unsigned OldSize = AddrModeInsts.size();
5330
5331 // Check to see if it is possible to fold this operation.
5332 bool MovedAway = false;
5333 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5334 // This instruction may have been moved away. If so, there is nothing
5335 // to check here.
5336 if (MovedAway)
5337 return true;
5338 // Okay, it's possible to fold this. Check to see if it is actually
5339 // *profitable* to do so. We use a simple cost model to avoid increasing
5340 // register pressure too much.
5341 if (I->hasOneUse() ||
5342 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5343 AddrModeInsts.push_back(I);
5344 return true;
5345 }
5346
5347 // It isn't profitable to do this, roll back.
5348 AddrMode = BackupAddrMode;
5349 AddrModeInsts.resize(OldSize);
5350 TPT.rollback(LastKnownGood);
5351 }
5352 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5353 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5354 return true;
5355 TPT.rollback(LastKnownGood);
5356 } else if (isa<ConstantPointerNull>(Addr)) {
5357 // Null pointer gets folded without affecting the addressing mode.
5358 return true;
5359 }
5360
5361 // Worse case, the target should support [reg] addressing modes. :)
5362 if (!AddrMode.HasBaseReg) {
5363 AddrMode.HasBaseReg = true;
5364 AddrMode.BaseReg = Addr;
5365 // Still check for legality in case the target supports [imm] but not [i+r].
5366 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5367 return true;
5368 AddrMode.HasBaseReg = false;
5369 AddrMode.BaseReg = nullptr;
5370 }
5371
5372 // If the base register is already taken, see if we can do [r+r].
5373 if (AddrMode.Scale == 0) {
5374 AddrMode.Scale = 1;
5375 AddrMode.ScaledReg = Addr;
5376 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5377 return true;
5378 AddrMode.Scale = 0;
5379 AddrMode.ScaledReg = nullptr;
5380 }
5381 // Couldn't match.
5382 TPT.rollback(LastKnownGood);
5383 return false;
5384}
5385
5386/// Check to see if all uses of OpVal by the specified inline asm call are due
5387/// to memory operands. If so, return true, otherwise return false.
5389 const TargetLowering &TLI,
5390 const TargetRegisterInfo &TRI) {
5391 const Function *F = CI->getFunction();
5392 TargetLowering::AsmOperandInfoVector TargetConstraints =
5393 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5394
5395 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5396 // Compute the constraint code and ConstraintType to use.
5397 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5398
5399 // If this asm operand is our Value*, and if it isn't an indirect memory
5400 // operand, we can't fold it! TODO: Also handle C_Address?
5401 if (OpInfo.CallOperandVal == OpVal &&
5402 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5403 !OpInfo.isIndirect))
5404 return false;
5405 }
5406
5407 return true;
5408}
5409
5410/// Recursively walk all the uses of I until we find a memory use.
5411/// If we find an obviously non-foldable instruction, return true.
5412/// Add accessed addresses and types to MemoryUses.
5414 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5415 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5416 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5417 BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan) {
5418 // If we already considered this instruction, we're done.
5419 if (!ConsideredInsts.insert(I).second)
5420 return false;
5421
5422 // If this is an obviously unfoldable instruction, bail out.
5423 if (!MightBeFoldableInst(I))
5424 return true;
5425
5426 // Loop over all the uses, recursively processing them.
5427 for (Use &U : I->uses()) {
5428 // Conservatively return true if we're seeing a large number or a deep chain
5429 // of users. This avoids excessive compilation times in pathological cases.
5430 if (SeenInsts++ >= MaxUsersToScan)
5431 return true;
5432
5433 Instruction *UserI = cast<Instruction>(U.getUser());
5434 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5435 MemoryUses.push_back({&U, LI->getType()});
5436 continue;
5437 }
5438
5439 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5440 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5441 return true; // Storing addr, not into addr.
5442 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5443 continue;
5444 }
5445
5446 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5447 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5448 return true; // Storing addr, not into addr.
5449 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5450 continue;
5451 }
5452
5454 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5455 return true; // Storing addr, not into addr.
5456 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5457 continue;
5458 }
5459
5462 Type *AccessTy;
5463 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5464 return true;
5465
5466 if (!find(PtrOps, U.get()))
5467 return true;
5468
5469 MemoryUses.push_back({&U, AccessTy});
5470 continue;
5471 }
5472
5473 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5474 if (CI->hasFnAttr(Attribute::Cold)) {
5475 // If this is a cold call, we can sink the addressing calculation into
5476 // the cold path. See optimizeCallInst
5477 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5478 continue;
5479 }
5480
5481 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5482 if (!IA)
5483 return true;
5484
5485 // If this is a memory operand, we're cool, otherwise bail out.
5486 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5487 return true;
5488 continue;
5489 }
5490
5491 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5492 PSI, BFI, SeenInsts, MaxUsersToScan))
5493 return true;
5494 }
5495
5496 return false;
5497}
5498
5500 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5501 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5502 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned MaxUsersToScan) {
5503 unsigned SeenInsts = 0;
5504 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5505 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5506 PSI, BFI, SeenInsts, MaxUsersToScan);
5507}
5508
5509/// Return true if Val is already known to be live at the use site that we're
5510/// folding it into. If so, there is no cost to include it in the addressing
5511/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5512/// instruction already.
5513bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5514 Value *KnownLive1,
5515 Value *KnownLive2) {
5516 // If Val is either of the known-live values, we know it is live!
5517 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5518 return true;
5519
5520 // All values other than instructions and arguments (e.g. constants) are live.
5521 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5522 return true;
5523
5524 // If Val is a constant sized alloca in the entry block, it is live, this is
5525 // true because it is just a reference to the stack/frame pointer, which is
5526 // live for the whole function.
5527 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5528 if (AI->isStaticAlloca())
5529 return true;
5530
5531 // Check to see if this value is already used in the memory instruction's
5532 // block. If so, it's already live into the block at the very least, so we
5533 // can reasonably fold it.
5534 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5535}
5536
5537/// It is possible for the addressing mode of the machine to fold the specified
5538/// instruction into a load or store that ultimately uses it.
5539/// However, the specified instruction has multiple uses.
5540/// Given this, it may actually increase register pressure to fold it
5541/// into the load. For example, consider this code:
5542///
5543/// X = ...
5544/// Y = X+1
5545/// use(Y) -> nonload/store
5546/// Z = Y+1
5547/// load Z
5548///
5549/// In this case, Y has multiple uses, and can be folded into the load of Z
5550/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5551/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5552/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5553/// number of computations either.
5554///
5555/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5556/// X was live across 'load Z' for other reasons, we actually *would* want to
5557/// fold the addressing mode in the Z case. This would make Y die earlier.
5558bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5559 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5560 if (IgnoreProfitability)
5561 return true;
5562
5563 // AMBefore is the addressing mode before this instruction was folded into it,
5564 // and AMAfter is the addressing mode after the instruction was folded. Get
5565 // the set of registers referenced by AMAfter and subtract out those
5566 // referenced by AMBefore: this is the set of values which folding in this
5567 // address extends the lifetime of.
5568 //
5569 // Note that there are only two potential values being referenced here,
5570 // BaseReg and ScaleReg (global addresses are always available, as are any
5571 // folded immediates).
5572 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5573
5574 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5575 // lifetime wasn't extended by adding this instruction.
5576 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5577 BaseReg = nullptr;
5578 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5579 ScaledReg = nullptr;
5580
5581 // If folding this instruction (and it's subexprs) didn't extend any live
5582 // ranges, we're ok with it.
5583 if (!BaseReg && !ScaledReg)
5584 return true;
5585
5586 // If all uses of this instruction can have the address mode sunk into them,
5587 // we can remove the addressing mode and effectively trade one live register
5588 // for another (at worst.) In this context, folding an addressing mode into
5589 // the use is just a particularly nice way of sinking it.
5591 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI,
5592 Opts.cgp_max_address_users_to_scan))
5593 return false; // Has a non-memory, non-foldable use!
5594
5595 // Now that we know that all uses of this instruction are part of a chain of
5596 // computation involving only operations that could theoretically be folded
5597 // into a memory use, loop over each of these memory operation uses and see
5598 // if they could *actually* fold the instruction. The assumption is that
5599 // addressing modes are cheap and that duplicating the computation involved
5600 // many times is worthwhile, even on a fastpath. For sinking candidates
5601 // (i.e. cold call sites), this serves as a way to prevent excessive code
5602 // growth since most architectures have some reasonable small and fast way to
5603 // compute an effective address. (i.e LEA on x86)
5604 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5605 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5606 Value *Address = Pair.first->get();
5607 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5608 Type *AddressAccessTy = Pair.second;
5609 unsigned AS = Address->getType()->getPointerAddressSpace();
5610
5611 // Do a match against the root of this address, ignoring profitability. This
5612 // will tell us if the addressing mode for the memory operation will
5613 // *actually* cover the shared instruction.
5614 ExtAddrMode Result;
5615 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5616 0);
5617 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5618 TPT.getRestorationPoint();
5619 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5620 AddressAccessTy, AS, UserI, Result,
5621 InsertedInsts, PromotedInsts, TPT,
5622 LargeOffsetGEP, OptSize, PSI, BFI, Opts);
5623 Matcher.IgnoreProfitability = true;
5624 bool Success = Matcher.matchAddr(Address, 0);
5625 (void)Success;
5626 assert(Success && "Couldn't select *anything*?");
5627
5628 // The match was to check the profitability, the changes made are not
5629 // part of the original matcher. Therefore, they should be dropped
5630 // otherwise the original matcher will not present the right state.
5631 TPT.rollback(LastKnownGood);
5632
5633 // If the match didn't cover I, then it won't be shared by it.
5634 if (!is_contained(MatchedAddrModeInsts, I))
5635 return false;
5636
5637 MatchedAddrModeInsts.clear();
5638 }
5639
5640 return true;
5641}
5642
5643/// Return true if the specified values are defined in a
5644/// different basic block than BB.
5645static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5647 return I->getParent() != BB;
5648 return false;
5649}
5650
5651// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5652// is the first instruction that will use Addr. So we need to find the first
5653// user of Addr in current BB.
5655 Value *SunkAddr) {
5656 if (Addr->hasOneUse())
5657 return MemoryInst->getIterator();
5658
5659 // We already have a SunkAddr in current BB, but we may need to insert cast
5660 // instruction after it.
5661 if (SunkAddr) {
5662 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5663 return std::next(AddrInst->getIterator());
5664 }
5665
5666 // Find the first user of Addr in current BB.
5667 Instruction *Earliest = MemoryInst;
5668 for (User *U : Addr->users()) {
5669 Instruction *UserInst = dyn_cast<Instruction>(U);
5670 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5671 if (isa<PHINode>(UserInst))
5672 continue;
5673 if (UserInst->comesBefore(Earliest))
5674 Earliest = UserInst;
5675 }
5676 }
5677 return Earliest->getIterator();
5678}
5679
5680/// Sink addressing mode computation immediate before MemoryInst if doing so
5681/// can be done without increasing register pressure. The need for the
5682/// register pressure constraint means this can end up being an all or nothing
5683/// decision for all uses of the same addressing computation.
5684///
5685/// Load and Store Instructions often have addressing modes that can do
5686/// significant amounts of computation. As such, instruction selection will try
5687/// to get the load or store to do as much computation as possible for the
5688/// program. The problem is that isel can only see within a single block. As
5689/// such, we sink as much legal addressing mode work into the block as possible.
5690///
5691/// This method is used to optimize both load/store and inline asms with memory
5692/// operands. It's also used to sink addressing computations feeding into cold
5693/// call sites into their (cold) basic block.
5694///
5695/// The motivation for handling sinking into cold blocks is that doing so can
5696/// both enable other address mode sinking (by satisfying the register pressure
5697/// constraint above), and reduce register pressure globally (by removing the
5698/// addressing mode computation from the fast path entirely.).
5699bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5700 Type *AccessTy, unsigned AddrSpace) {
5701 Value *Repl = Addr;
5702
5703 // Try to collapse single-value PHI nodes. This is necessary to undo
5704 // unprofitable PRE transformations.
5705 SmallVector<Value *, 8> worklist;
5706 SmallPtrSet<Value *, 16> Visited;
5707 worklist.push_back(Addr);
5708
5709 // Use a worklist to iteratively look through PHI and select nodes, and
5710 // ensure that the addressing mode obtained from the non-PHI/select roots of
5711 // the graph are compatible.
5712 bool PhiOrSelectSeen = false;
5713 SmallVector<Instruction *, 16> AddrModeInsts;
5714 AddressingModeCombiner AddrModes(*DL, Opts, Addr);
5715 TypePromotionTransaction TPT(RemovedInsts);
5716 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5717 TPT.getRestorationPoint();
5718 while (!worklist.empty()) {
5719 Value *V = worklist.pop_back_val();
5720
5721 // We allow traversing cyclic Phi nodes.
5722 // In case of success after this loop we ensure that traversing through
5723 // Phi nodes ends up with all cases to compute address of the form
5724 // BaseGV + Base + Scale * Index + Offset
5725 // where Scale and Offset are constans and BaseGV, Base and Index
5726 // are exactly the same Values in all cases.
5727 // It means that BaseGV, Scale and Offset dominate our memory instruction
5728 // and have the same value as they had in address computation represented
5729 // as Phi. So we can safely sink address computation to memory instruction.
5730 if (!Visited.insert(V).second)
5731 continue;
5732
5733 // For a PHI node, push all of its incoming values.
5734 if (PHINode *P = dyn_cast<PHINode>(V)) {
5735 append_range(worklist, P->incoming_values());
5736 PhiOrSelectSeen = true;
5737 continue;
5738 }
5739 // Similar for select.
5740 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5741 worklist.push_back(SI->getFalseValue());
5742 worklist.push_back(SI->getTrueValue());
5743 PhiOrSelectSeen = true;
5744 continue;
5745 }
5746
5747 // For non-PHIs, determine the addressing mode being computed. Note that
5748 // the result may differ depending on what other uses our candidate
5749 // addressing instructions might have.
5750 AddrModeInsts.clear();
5751 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5752 0);
5753 // Defer the query (and possible computation of) the dom tree to point of
5754 // actual use. It's expected that most address matches don't actually need
5755 // the domtree.
5756 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5757 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5758 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5759 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5760 BFI, Opts);
5761
5762 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5763 if (GEP && !NewGEPBases.count(GEP)) {
5764 // If splitting the underlying data structure can reduce the offset of a
5765 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5766 // previously split data structures.
5767 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5768 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5769 }
5770
5771 NewAddrMode.OriginalValue = V;
5772 if (!AddrModes.addNewAddrMode(NewAddrMode))
5773 break;
5774 }
5775
5776 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5777 // or we have multiple but either couldn't combine them or combining them
5778 // wouldn't do anything useful, bail out now.
5779 if (!AddrModes.combineAddrModes()) {
5780 TPT.rollback(LastKnownGood);
5781 return false;
5782 }
5783 bool Modified = TPT.commit();
5784
5785 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5786 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5787
5788 // If all the instructions matched are already in this BB, don't do anything.
5789 // If we saw a Phi node then it is not local definitely, and if we saw a
5790 // select then we want to push the address calculation past it even if it's
5791 // already in this BB.
5792 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5793 return IsNonLocalValue(V, MemoryInst->getParent());
5794 })) {
5795 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5796 << "\n");
5797 return Modified;
5798 }
5799
5800 // Now that we determined the addressing expression we want to use and know
5801 // that we have to sink it into this block. Check to see if we have already
5802 // done this for some other load/store instr in this block. If so, reuse
5803 // the computation. Before attempting reuse, check if the address is valid
5804 // as it may have been erased.
5805
5806 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5807
5808 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5809 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5810 Type *IdxTy = DL->getIndexType(Addr->getType());
5811
5812 // The current BB may be optimized multiple times, we can't guarantee the
5813 // reuse of Addr happens later, call findInsertPos to find an appropriate
5814 // insert position.
5815 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5816
5817 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5818 if (!SunkAddr) {
5819 auto &DT = getDT();
5820 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
5821 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
5822 return Modified;
5823 }
5824
5825 IRBuilder<> Builder(InsertPos);
5826
5827 if (SunkAddr) {
5828 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5829 << " for " << *MemoryInst << "\n");
5830 if (SunkAddr->getType() != Addr->getType()) {
5831 if (SunkAddr->getType()->getPointerAddressSpace() !=
5832 Addr->getType()->getPointerAddressSpace() &&
5833 !DL->isNonIntegralPointerType(Addr->getType())) {
5834 // There are two reasons the address spaces might not match: a no-op
5835 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5836 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5837 // TODO: allow bitcast between different address space pointers with the
5838 // same size.
5839 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5840 SunkAddr =
5841 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5842 } else
5843 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5844 }
5845 } else if (valueOr(Opts.cgp_addr_sink_using_gep, true) ||
5846 (Opts.cgp_addr_sink_using_gep == BoolOrDefault::Default &&
5847 SubtargetInfo->addrSinkUsingGEPs())) {
5848 // By default, we use the GEP-based method when AA is used later. This
5849 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5850 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
5851 << " for " << *MemoryInst << "\n");
5852 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5853
5854 // First, find the pointer.
5855 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5856 ResultPtr = AddrMode.BaseReg;
5857 AddrMode.BaseReg = nullptr;
5858 }
5859
5860 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5861 // We can't add more than one pointer together, nor can we scale a
5862 // pointer (both of which seem meaningless).
5863 if (ResultPtr || AddrMode.Scale != 1)
5864 return Modified;
5865
5866 ResultPtr = AddrMode.ScaledReg;
5867 AddrMode.Scale = 0;
5868 }
5869
5870 // It is only safe to sign extend the BaseReg if we know that the math
5871 // required to create it did not overflow before we extend it. Since
5872 // the original IR value was tossed in favor of a constant back when
5873 // the AddrMode was created we need to bail out gracefully if widths
5874 // do not match instead of extending it.
5875 //
5876 // (See below for code to add the scale.)
5877 if (AddrMode.Scale) {
5878 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5879 if (cast<IntegerType>(IdxTy)->getBitWidth() >
5880 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5881 return Modified;
5882 }
5883
5884 GlobalValue *BaseGV = AddrMode.BaseGV;
5885 if (BaseGV != nullptr) {
5886 if (ResultPtr)
5887 return Modified;
5888
5889 if (BaseGV->isThreadLocal()) {
5890 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
5891 } else {
5892 ResultPtr = BaseGV;
5893 }
5894 }
5895
5896 // If the real base value actually came from an inttoptr, then the matcher
5897 // will look through it and provide only the integer value. In that case,
5898 // use it here.
5899 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5900 if (!ResultPtr && AddrMode.BaseReg) {
5901 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5902 "sunkaddr");
5903 AddrMode.BaseReg = nullptr;
5904 } else if (!ResultPtr && AddrMode.Scale == 1) {
5905 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5906 "sunkaddr");
5907 AddrMode.Scale = 0;
5908 }
5909 }
5910
5911 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
5912 !AddrMode.BaseOffs) {
5913 SunkAddr = Constant::getNullValue(Addr->getType());
5914 } else if (!ResultPtr) {
5915 return Modified;
5916 } else {
5917 Type *I8PtrTy =
5918 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
5919
5920 // Start with the base register. Do this first so that subsequent address
5921 // matching finds it last, which will prevent it from trying to match it
5922 // as the scaled value in case it happens to be a mul. That would be
5923 // problematic if we've sunk a different mul for the scale, because then
5924 // we'd end up sinking both muls.
5925 if (AddrMode.BaseReg) {
5926 Value *V = AddrMode.BaseReg;
5927 if (V->getType() != IdxTy)
5928 V = Builder.CreateIntCast(V, IdxTy, /*isSigned=*/true, "sunkaddr");
5929
5930 ResultIndex = V;
5931 }
5932
5933 // Add the scale value.
5934 if (AddrMode.Scale) {
5935 Value *V = AddrMode.ScaledReg;
5936 if (V->getType() == IdxTy) {
5937 // done.
5938 } else {
5940 cast<IntegerType>(V->getType())->getBitWidth() &&
5941 "We can't transform if ScaledReg is too narrow");
5942 V = Builder.CreateTrunc(V, IdxTy, "sunkaddr");
5943 }
5944
5945 if (AddrMode.Scale != 1)
5946 V = Builder.CreateMul(
5947 V, ConstantInt::getSigned(IdxTy, AddrMode.Scale), "sunkaddr");
5948 if (ResultIndex)
5949 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5950 else
5951 ResultIndex = V;
5952 }
5953
5954 // Add in the Base Offset if present.
5955 if (AddrMode.BaseOffs) {
5956 Value *V = ConstantInt::getSigned(IdxTy, AddrMode.BaseOffs);
5957 if (ResultIndex) {
5958 // We need to add this separately from the scale above to help with
5959 // SDAG consecutive load/store merging.
5960 if (ResultPtr->getType() != I8PtrTy)
5961 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5962 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
5963 AddrMode.InBounds);
5964 }
5965
5966 ResultIndex = V;
5967 }
5968
5969 if (!ResultIndex) {
5970 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
5971 // We know that we have a pointer without any offsets. If this pointer
5972 // originates from a different basic block than the current one, we
5973 // must be able to recreate it in the current basic block.
5974 // We do not support the recreation of any instructions yet.
5975 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
5976 return Modified;
5977 SunkAddr = ResultPtr;
5978 } else {
5979 if (ResultPtr->getType() != I8PtrTy)
5980 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5981 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
5982 AddrMode.InBounds);
5983 }
5984
5985 if (SunkAddr->getType() != Addr->getType()) {
5986 if (SunkAddr->getType()->getPointerAddressSpace() !=
5987 Addr->getType()->getPointerAddressSpace() &&
5988 !DL->isNonIntegralPointerType(Addr->getType())) {
5989 // There are two reasons the address spaces might not match: a no-op
5990 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5991 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5992 // TODO: allow bitcast between different address space pointers with
5993 // the same size.
5994 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5995 SunkAddr =
5996 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5997 } else
5998 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5999 }
6000 }
6001 } else {
6002 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6003 // non-integral pointers, so in that case bail out now.
6004 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6005 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6006 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
6007 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
6008 if (DL->isNonIntegralPointerType(Addr->getType()) ||
6009 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
6010 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
6011 (AddrMode.BaseGV &&
6012 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
6013 return Modified;
6014
6015 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6016 << " for " << *MemoryInst << "\n");
6017 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6018 Value *Result = nullptr;
6019
6020 // Start with the base register. Do this first so that subsequent address
6021 // matching finds it last, which will prevent it from trying to match it
6022 // as the scaled value in case it happens to be a mul. That would be
6023 // problematic if we've sunk a different mul for the scale, because then
6024 // we'd end up sinking both muls.
6025 if (AddrMode.BaseReg) {
6026 Value *V = AddrMode.BaseReg;
6027 if (V->getType()->isPointerTy())
6028 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6029 if (V->getType() != IntPtrTy)
6030 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
6031 Result = V;
6032 }
6033
6034 // Add the scale value.
6035 if (AddrMode.Scale) {
6036 Value *V = AddrMode.ScaledReg;
6037 if (V->getType() == IntPtrTy) {
6038 // done.
6039 } else if (V->getType()->isPointerTy()) {
6040 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
6041 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
6042 cast<IntegerType>(V->getType())->getBitWidth()) {
6043 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
6044 } else {
6045 // It is only safe to sign extend the BaseReg if we know that the math
6046 // required to create it did not overflow before we extend it. Since
6047 // the original IR value was tossed in favor of a constant back when
6048 // the AddrMode was created we need to bail out gracefully if widths
6049 // do not match instead of extending it.
6051 if (I && (Result != AddrMode.BaseReg))
6052 I->eraseFromParent();
6053 return Modified;
6054 }
6055 if (AddrMode.Scale != 1)
6056 V = Builder.CreateMul(
6057 V, ConstantInt::getSigned(IntPtrTy, AddrMode.Scale), "sunkaddr");
6058 if (Result)
6059 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6060 else
6061 Result = V;
6062 }
6063
6064 // Add in the BaseGV if present.
6065 GlobalValue *BaseGV = AddrMode.BaseGV;
6066 if (BaseGV != nullptr) {
6067 Value *BaseGVPtr;
6068 if (BaseGV->isThreadLocal()) {
6069 BaseGVPtr = Builder.CreateThreadLocalAddress(BaseGV);
6070 } else {
6071 BaseGVPtr = BaseGV;
6072 }
6073 Value *V = Builder.CreatePtrToInt(BaseGVPtr, IntPtrTy, "sunkaddr");
6074 if (Result)
6075 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6076 else
6077 Result = V;
6078 }
6079
6080 // Add in the Base Offset if present.
6081 if (AddrMode.BaseOffs) {
6083 if (Result)
6084 Result = Builder.CreateAdd(Result, V, "sunkaddr");
6085 else
6086 Result = V;
6087 }
6088
6089 if (!Result)
6090 SunkAddr = Constant::getNullValue(Addr->getType());
6091 else
6092 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
6093 }
6094
6095 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6096 // Store the newly computed address into the cache. In the case we reused a
6097 // value, this should be idempotent.
6098 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6099
6100 // If we have no uses, recursively delete the value and all dead instructions
6101 // using it.
6102 if (Repl->use_empty()) {
6103 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6104 RecursivelyDeleteTriviallyDeadInstructions(
6105 Repl, TLInfo, nullptr,
6106 [&](Value *V) { removeAllAssertingVHReferences(V); });
6107 });
6108 }
6109 ++NumMemoryInsts;
6110 return true;
6111}
6112
6113/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6114/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6115/// only handle a 2 operand GEP in the same basic block or a splat constant
6116/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6117/// index.
6118///
6119/// If the existing GEP has a vector base pointer that is splat, we can look
6120/// through the splat to find the scalar pointer. If we can't find a scalar
6121/// pointer there's nothing we can do.
6122///
6123/// If we have a GEP with more than 2 indices where the middle indices are all
6124/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6125///
6126/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6127/// followed by a GEP with an all zeroes vector index. This will enable
6128/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6129/// zero index.
6130bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6131 Value *Ptr) {
6132 Value *NewAddr;
6133
6134 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6135 // Don't optimize GEPs that don't have indices.
6136 if (!GEP->hasIndices())
6137 return false;
6138
6139 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6140 // FIXME: We should support this by sinking the GEP.
6141 if (MemoryInst->getParent() != GEP->getParent())
6142 return false;
6143
6144 SmallVector<Value *, 2> Ops(GEP->operands());
6145
6146 bool RewriteGEP = false;
6147
6148 if (Ops[0]->getType()->isVectorTy()) {
6149 Ops[0] = getSplatValue(Ops[0]);
6150 if (!Ops[0])
6151 return false;
6152 RewriteGEP = true;
6153 }
6154
6155 unsigned FinalIndex = Ops.size() - 1;
6156
6157 // Ensure all but the last index is 0.
6158 // FIXME: This isn't strictly required. All that's required is that they are
6159 // all scalars or splats.
6160 for (unsigned i = 1; i < FinalIndex; ++i) {
6161 auto *C = dyn_cast<Constant>(Ops[i]);
6162 if (!C)
6163 return false;
6164 if (isa<VectorType>(C->getType()))
6165 C = C->getSplatValue();
6166 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6167 if (!CI || !CI->isZero())
6168 return false;
6169 // Scalarize the index if needed.
6170 Ops[i] = CI;
6171 }
6172
6173 // Try to scalarize the final index.
6174 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6175 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6176 auto *C = dyn_cast<ConstantInt>(V);
6177 // Don't scalarize all zeros vector.
6178 if (!C || !C->isZero()) {
6179 Ops[FinalIndex] = V;
6180 RewriteGEP = true;
6181 }
6182 }
6183 }
6184
6185 // If we made any changes or the we have extra operands, we need to generate
6186 // new instructions.
6187 if (!RewriteGEP && Ops.size() == 2)
6188 return false;
6189
6190 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6191
6192 IRBuilder<> Builder(MemoryInst);
6193 Builder.disableGEPCanonicalization();
6194
6195 Type *SourceTy = GEP->getSourceElementType();
6196 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6197
6198 // If the final index isn't a vector, emit a scalar GEP containing all ops
6199 // and a vector GEP with all zeroes final index.
6200 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6201 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6202 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6203 auto *SecondTy = GetElementPtrInst::getIndexedType(
6204 SourceTy, ArrayRef(Ops).drop_front());
6205 NewAddr =
6206 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6207 } else {
6208 Value *Base = Ops[0];
6209 Value *Index = Ops[FinalIndex];
6210
6211 // Create a scalar GEP if there are more than 2 operands.
6212 if (Ops.size() != 2) {
6213 // Replace the last index with 0.
6214 Ops[FinalIndex] =
6215 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6216 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6218 SourceTy, ArrayRef(Ops).drop_front());
6219 }
6220
6221 // Now create the GEP with scalar pointer and vector index.
6222 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6223 }
6224 } else if (!isa<Constant>(Ptr)) {
6225 // Not a GEP, maybe its a splat and we can create a GEP to enable
6226 // SelectionDAGBuilder to use it as a uniform base.
6227 Value *V = getSplatValue(Ptr);
6228 if (!V)
6229 return false;
6230
6231 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6232
6233 IRBuilder<> Builder(MemoryInst);
6234 Builder.disableGEPCanonicalization();
6235
6236 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6237 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6238 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6239 Type *ScalarTy;
6240 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6241 Intrinsic::masked_gather) {
6242 ScalarTy = MemoryInst->getType()->getScalarType();
6243 } else {
6244 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6245 Intrinsic::masked_scatter);
6246 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6247 }
6248 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6249 } else {
6250 // Constant, SelectionDAGBuilder knows to check if its a splat.
6251 return false;
6252 }
6253
6254 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6255
6256 // If we have no uses, recursively delete the value and all dead instructions
6257 // using it.
6258 if (Ptr->use_empty())
6260 Ptr, TLInfo, nullptr,
6261 [&](Value *V) { removeAllAssertingVHReferences(V); });
6262
6263 return true;
6264}
6265
6266// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6267// Check the pattern we are interested in where there are maximum 2 uses
6268// of the intrinsic which are the extract instructions.
6270 ExtractValueInst *&OverflowExtract) {
6271 // Bail out if it's more than 2 users:
6272 if (I->hasNUsesOrMore(3))
6273 return false;
6274
6275 for (User *U : I->users()) {
6276 auto *Extract = dyn_cast<ExtractValueInst>(U);
6277 if (!Extract || Extract->getNumIndices() != 1)
6278 return false;
6279
6280 unsigned Index = Extract->getIndices()[0];
6281 if (Index == 0)
6282 MulExtract = Extract;
6283 else if (Index == 1)
6284 OverflowExtract = Extract;
6285 else
6286 return false;
6287 }
6288 return true;
6289}
6290
6291// Rewrite the mul_with_overflow intrinsic by checking if both of the
6292// operands' value ranges are within the legal type. If so, we can optimize the
6293// multiplication algorithm. This code is supposed to be written during the step
6294// of type legalization, but given that we need to reconstruct the IR which is
6295// not doable there, we do it here.
6296// The IR after the optimization will look like:
6297// entry:
6298// if signed:
6299// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6300// overflow_no
6301// else:
6302// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6303// overflow_no:
6304// overflow:
6305// overflow.res:
6306// \returns true if optimization was applied
6307// TODO: This optimization can be further improved to optimize branching on
6308// overflow where the 'overflow_no' BB can branch directly to the false
6309// successor of overflow, but that would add additional complexity so we leave
6310// it for future work.
6311bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6312 ModifyDT &ModifiedDT) {
6313 // Check if target supports this optimization.
6315 I->getContext(),
6316 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6317 return false;
6318
6319 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6320 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6321 return false;
6322
6323 // Keep track of the instruction to stop reoptimizing it again.
6324 InsertedInsts.insert(I);
6325
6326 Value *LHS = I->getOperand(0);
6327 Value *RHS = I->getOperand(1);
6328 Type *Ty = LHS->getType();
6329 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6330 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6331
6332 // New BBs:
6333 BasicBlock *OverflowEntryBB =
6334 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6335 OverflowEntryBB->takeName(I->getParent());
6336 // Keep the 'br' instruction that is generated as a result of the split to be
6337 // erased/replaced later.
6338 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6339 BasicBlock *NoOverflowBB =
6340 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6341 NoOverflowBB->moveAfter(OverflowEntryBB);
6342 BasicBlock *OverflowBB =
6343 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6344 OverflowBB->moveAfter(NoOverflowBB);
6345
6346 // BB overflow.entry:
6347 IRBuilder<> Builder(OverflowEntryBB);
6348 // Extract low and high halves of LHS:
6349 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6350 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6351 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6352
6353 // Extract low and high halves of RHS:
6354 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6355 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6356 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6357
6358 Value *IsAnyBitTrue;
6359 if (IsSigned) {
6360 Value *SignLoLHS =
6361 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6362 Value *SignLoRHS =
6363 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6364 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6365 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6366 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6367 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6368 ConstantInt::getNullValue(Or->getType()));
6369 } else {
6370 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6371 ConstantInt::getNullValue(LegalTy));
6372 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6373 ConstantInt::getNullValue(LegalTy));
6374 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6375 }
6376 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6377
6378 // BB overflow.no:
6379 Builder.SetInsertPoint(NoOverflowBB);
6380 Value *ExtLoLHS, *ExtLoRHS;
6381 if (IsSigned) {
6382 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6383 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6384 } else {
6385 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6386 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6387 }
6388
6389 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6390
6391 // Create the 'overflow.res' BB to merge the results of
6392 // the two paths:
6393 BasicBlock *OverflowResBB = I->getParent();
6394 OverflowResBB->setName("overflow.res");
6395
6396 // BB overflow.no: jump to overflow.res BB
6397 Builder.CreateBr(OverflowResBB);
6398 // No we don't need the old terminator in overflow.entry BB, erase it:
6399 OldTerminator->eraseFromParent();
6400
6401 // BB overflow.res:
6402 Builder.SetInsertPoint(OverflowResBB->getFirstInsertionPt());
6403 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6404 // replace the extract instructions.
6405 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6406 *OverflowFlagPHI =
6407 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6408
6409 // Add the incoming values from no.overflow BB and later from overflow BB.
6410 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6411 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6412 NoOverflowBB);
6413
6414 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6415 if (MulExtract) {
6416 MulExtract->replaceAllUsesWith(OverflowResPHI);
6417 MulExtract->eraseFromParent();
6418 }
6419 if (OverflowExtract) {
6420 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6421 OverflowExtract->eraseFromParent();
6422 }
6423
6424 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6425 // overflow BB
6426 I->removeFromParent();
6427 // BB overflow:
6428 I->insertInto(OverflowBB, OverflowBB->end());
6429 Builder.SetInsertPoint(OverflowBB->end());
6430 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6431 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6432 Builder.CreateBr(OverflowResBB);
6433
6434 // Add The Extracted values to the PHINodes in the overflow.res BB.
6435 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6436 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6437
6438 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6439 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6440 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6441 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6442 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6443
6444 ModifiedDT = ModifyDT::ModifyBBDT;
6445 return true;
6446}
6447
6448/// If there are any memory operands, use OptimizeMemoryInst to sink their
6449/// address computing into the block when possible / profitable.
6450bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6451 bool MadeChange = false;
6452
6453 const TargetRegisterInfo *TRI =
6455 TargetLowering::AsmOperandInfoVector TargetConstraints =
6456 TLI->ParseConstraints(*DL, TRI, *CS);
6457 unsigned ArgNo = 0;
6458 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6459 // Compute the constraint code and ConstraintType to use.
6461
6462 // TODO: Also handle C_Address?
6463 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6464 OpInfo.isIndirect) {
6465 Value *OpVal = CS->getArgOperand(ArgNo++);
6466 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6467 } else if (OpInfo.Type == InlineAsm::isInput)
6468 ArgNo++;
6469 }
6470
6471 return MadeChange;
6472}
6473
6474/// Check if all the uses of \p Val are equivalent (or free) zero or
6475/// sign extensions.
6476static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6477 assert(!Val->use_empty() && "Input must have at least one use");
6478 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6479 bool IsSExt = isa<SExtInst>(FirstUser);
6480 Type *ExtTy = FirstUser->getType();
6481 for (const User *U : Val->users()) {
6482 const Instruction *UI = cast<Instruction>(U);
6483 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6484 return false;
6485 Type *CurTy = UI->getType();
6486 // Same input and output types: Same instruction after CSE.
6487 if (CurTy == ExtTy)
6488 continue;
6489
6490 // If IsSExt is true, we are in this situation:
6491 // a = Val
6492 // b = sext ty1 a to ty2
6493 // c = sext ty1 a to ty3
6494 // Assuming ty2 is shorter than ty3, this could be turned into:
6495 // a = Val
6496 // b = sext ty1 a to ty2
6497 // c = sext ty2 b to ty3
6498 // However, the last sext is not free.
6499 if (IsSExt)
6500 return false;
6501
6502 // This is a ZExt, maybe this is free to extend from one type to another.
6503 // In that case, we would not account for a different use.
6504 Type *NarrowTy;
6505 Type *LargeTy;
6506 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6507 CurTy->getScalarType()->getIntegerBitWidth()) {
6508 NarrowTy = CurTy;
6509 LargeTy = ExtTy;
6510 } else {
6511 NarrowTy = ExtTy;
6512 LargeTy = CurTy;
6513 }
6514
6515 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6516 return false;
6517 }
6518 // All uses are the same or can be derived from one another for free.
6519 return true;
6520}
6521
6522/// Try to speculatively promote extensions in \p Exts and continue
6523/// promoting through newly promoted operands recursively as far as doing so is
6524/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6525/// When some promotion happened, \p TPT contains the proper state to revert
6526/// them.
6527///
6528/// \return true if some promotion happened, false otherwise.
6529bool CodeGenPrepare::tryToPromoteExts(
6530 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6531 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6532 unsigned CreatedInstsCost) {
6533 bool Promoted = false;
6534
6535 // Iterate over all the extensions to try to promote them.
6536 for (auto *I : Exts) {
6537 // Early check if we directly have ext(load).
6538 if (isa<LoadInst>(I->getOperand(0))) {
6539 ProfitablyMovedExts.push_back(I);
6540 continue;
6541 }
6542
6543 // Check whether or not we want to do any promotion. The reason we have
6544 // this check inside the for loop is to catch the case where an extension
6545 // is directly fed by a load because in such case the extension can be moved
6546 // up without any promotion on its operands.
6547 if (!TLI->enableExtLdPromotion() || !Opts.cgp_ext_ld_promotion)
6548 return false;
6549
6550 // Get the action to perform the promotion.
6551 TypePromotionHelper::Action TPH =
6552 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6553 // Check if we can promote.
6554 if (!TPH) {
6555 // Save the current extension as we cannot move up through its operand.
6556 ProfitablyMovedExts.push_back(I);
6557 continue;
6558 }
6559
6560 // Save the current state.
6561 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6562 TPT.getRestorationPoint();
6563 SmallVector<Instruction *, 4> NewExts;
6564 unsigned NewCreatedInstsCost = 0;
6565 unsigned ExtCost = !TLI->isExtFree(I);
6566 // Promote.
6567 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6568 &NewExts, nullptr, *TLI);
6569 assert(PromotedVal &&
6570 "TypePromotionHelper should have filtered out those cases");
6571
6572 // We would be able to merge only one extension in a load.
6573 // Therefore, if we have more than 1 new extension we heuristically
6574 // cut this search path, because it means we degrade the code quality.
6575 // With exactly 2, the transformation is neutral, because we will merge
6576 // one extension but leave one. However, we optimistically keep going,
6577 // because the new extension may be removed too. Also avoid replacing a
6578 // single free extension with multiple extensions, as this increases the
6579 // number of IR instructions while not providing any savings.
6580 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6581 // FIXME: It would be possible to propagate a negative value instead of
6582 // conservatively ceiling it to 0.
6583 TotalCreatedInstsCost =
6584 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6585 if (!Opts.cgp_stress_ext_ld_promotion &&
6586 (TotalCreatedInstsCost > 1 ||
6587 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6588 (ExtCost == 0 && NewExts.size() > 1))) {
6589 // This promotion is not profitable, rollback to the previous state, and
6590 // save the current extension in ProfitablyMovedExts as the latest
6591 // speculative promotion turned out to be unprofitable.
6592 TPT.rollback(LastKnownGood);
6593 ProfitablyMovedExts.push_back(I);
6594 continue;
6595 }
6596 // Continue promoting NewExts as far as doing so is profitable.
6597 SmallVector<Instruction *, 2> NewlyMovedExts;
6598 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6599 bool NewPromoted = false;
6600 for (auto *ExtInst : NewlyMovedExts) {
6601 Instruction *MovedExt = cast<Instruction>(ExtInst);
6602 Value *ExtOperand = MovedExt->getOperand(0);
6603 // If we have reached to a load, we need this extra profitability check
6604 // as it could potentially be merged into an ext(load).
6605 if (isa<LoadInst>(ExtOperand) &&
6606 !(Opts.cgp_stress_ext_ld_promotion ||
6607 NewCreatedInstsCost <= ExtCost ||
6608 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6609 continue;
6610
6611 ProfitablyMovedExts.push_back(MovedExt);
6612 NewPromoted = true;
6613 }
6614
6615 // If none of speculative promotions for NewExts is profitable, rollback
6616 // and save the current extension (I) as the last profitable extension.
6617 if (!NewPromoted) {
6618 TPT.rollback(LastKnownGood);
6619 ProfitablyMovedExts.push_back(I);
6620 continue;
6621 }
6622 // The promotion is profitable.
6623 Promoted = true;
6624 }
6625 return Promoted;
6626}
6627
6628/// Merging redundant sexts when one is dominating the other.
6629bool CodeGenPrepare::mergeSExts(Function &F) {
6630 bool Changed = false;
6631 for (auto &Entry : ValToSExtendedUses) {
6632 SExts &Insts = Entry.second;
6633 SExts CurPts;
6634 for (Instruction *Inst : Insts) {
6635 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6636 Inst->getOperand(0) != Entry.first)
6637 continue;
6638 bool inserted = false;
6639 for (auto &Pt : CurPts) {
6640 if (getDT().dominates(Inst, Pt)) {
6641 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6642 RemovedInsts.insert(Pt);
6643 Pt->removeFromParent();
6644 Pt = Inst;
6645 inserted = true;
6646 Changed = true;
6647 break;
6648 }
6649 if (!getDT().dominates(Pt, Inst))
6650 // Give up if we need to merge in a common dominator as the
6651 // experiments show it is not profitable.
6652 continue;
6653 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6654 RemovedInsts.insert(Inst);
6655 Inst->removeFromParent();
6656 inserted = true;
6657 Changed = true;
6658 break;
6659 }
6660 if (!inserted)
6661 CurPts.push_back(Inst);
6662 }
6663 }
6664 return Changed;
6665}
6666
6667// Splitting large data structures so that the GEPs accessing them can have
6668// smaller offsets so that they can be sunk to the same blocks as their users.
6669// For example, a large struct starting from %base is split into two parts
6670// where the second part starts from %new_base.
6671//
6672// Before:
6673// BB0:
6674// %base =
6675//
6676// BB1:
6677// %gep0 = gep %base, off0
6678// %gep1 = gep %base, off1
6679// %gep2 = gep %base, off2
6680//
6681// BB2:
6682// %load1 = load %gep0
6683// %load2 = load %gep1
6684// %load3 = load %gep2
6685//
6686// After:
6687// BB0:
6688// %base =
6689// %new_base = gep %base, off0
6690//
6691// BB1:
6692// %new_gep0 = %new_base
6693// %new_gep1 = gep %new_base, off1 - off0
6694// %new_gep2 = gep %new_base, off2 - off0
6695//
6696// BB2:
6697// %load1 = load i32, i32* %new_gep0
6698// %load2 = load i32, i32* %new_gep1
6699// %load3 = load i32, i32* %new_gep2
6700//
6701// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6702// their offsets are smaller enough to fit into the addressing mode.
6703bool CodeGenPrepare::splitLargeGEPOffsets() {
6704 bool Changed = false;
6705 for (auto &Entry : LargeOffsetGEPMap) {
6706 Value *OldBase = Entry.first;
6707 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6708 &LargeOffsetGEPs = Entry.second;
6709 auto compareGEPOffset =
6710 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6711 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6712 if (LHS.first == RHS.first)
6713 return false;
6714 if (LHS.second != RHS.second)
6715 return LHS.second < RHS.second;
6716 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6717 };
6718 // Sorting all the GEPs of the same data structures based on the offsets.
6719 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6720 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6721 // Skip if all the GEPs have the same offsets.
6722 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6723 continue;
6724 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6725 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6726 Value *NewBaseGEP = nullptr;
6727
6728 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6729 GetElementPtrInst *GEP) {
6730 LLVMContext &Ctx = GEP->getContext();
6731 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6732 Type *I8PtrTy =
6733 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6734
6735 BasicBlock::iterator NewBaseInsertPt;
6736 BasicBlock *NewBaseInsertBB;
6737 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6738 // If the base of the struct is an instruction, the new base will be
6739 // inserted close to it.
6740 NewBaseInsertBB = BaseI->getParent();
6741 if (isa<PHINode>(BaseI))
6742 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6743 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6744 NewBaseInsertBB =
6745 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6746 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6747 } else
6748 NewBaseInsertPt = std::next(BaseI->getIterator());
6749 } else {
6750 // If the current base is an argument or global value, the new base
6751 // will be inserted to the entry block.
6752 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6753 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6754 }
6755 IRBuilder<> NewBaseBuilder(NewBaseInsertPt);
6756 // Create a new base.
6757 // TODO: Avoid implicit trunc?
6758 // See https://github.com/llvm/llvm-project/issues/112510.
6759 Value *BaseIndex =
6760 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6761 NewBaseGEP = OldBase;
6762 if (NewBaseGEP->getType() != I8PtrTy)
6763 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6764 NewBaseGEP =
6765 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6766 NewGEPBases.insert(NewBaseGEP);
6767 return;
6768 };
6769
6770 // Check whether all the offsets can be encoded with prefered common base.
6771 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6772 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6773 BaseOffset = PreferBase;
6774 // Create a new base if the offset of the BaseGEP can be decoded with one
6775 // instruction.
6776 createNewBase(BaseOffset, OldBase, BaseGEP);
6777 }
6778
6779 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6780 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6781 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6782 int64_t Offset = LargeOffsetGEP->second;
6783 if (Offset != BaseOffset) {
6784 TargetLowering::AddrMode AddrMode;
6785 AddrMode.HasBaseReg = true;
6786 AddrMode.BaseOffs = Offset - BaseOffset;
6787 // The result type of the GEP might not be the type of the memory
6788 // access.
6790 GEP->getResultElementType(),
6791 GEP->getAddressSpace())) {
6792 // We need to create a new base if the offset to the current base is
6793 // too large to fit into the addressing mode. So, a very large struct
6794 // may be split into several parts.
6795 BaseGEP = GEP;
6796 BaseOffset = Offset;
6797 NewBaseGEP = nullptr;
6798 }
6799 }
6800
6801 // Generate a new GEP to replace the current one.
6802 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6803
6804 if (!NewBaseGEP) {
6805 // Create a new base if we don't have one yet. Find the insertion
6806 // pointer for the new base first.
6807 createNewBase(BaseOffset, OldBase, GEP);
6808 }
6809
6810 IRBuilder<> Builder(GEP);
6811 Value *NewGEP = NewBaseGEP;
6812 if (Offset != BaseOffset) {
6813 // Calculate the new offset for the new GEP.
6814 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
6815 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6816 }
6817 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
6818 LargeOffsetGEPID.erase(GEP);
6819 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6820 GEP->eraseFromParent();
6821 Changed = true;
6822 }
6823 }
6824 return Changed;
6825}
6826
6827bool CodeGenPrepare::optimizePhiType(
6828 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6829 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6830 // We are looking for a collection on interconnected phi nodes that together
6831 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6832 // are of the same type. Convert the whole set of nodes to the type of the
6833 // bitcast.
6834 Type *PhiTy = I->getType();
6835 Type *ConvertTy = nullptr;
6836 if (Visited.count(I) ||
6837 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6838 return false;
6839
6840 SmallVector<Instruction *, 4> Worklist;
6841 Worklist.push_back(cast<Instruction>(I));
6842 SmallPtrSet<PHINode *, 4> PhiNodes;
6843 SmallPtrSet<ConstantData *, 4> Constants;
6844 PhiNodes.insert(I);
6845 Visited.insert(I);
6846 SmallPtrSet<Instruction *, 4> Defs;
6847 SmallPtrSet<Instruction *, 4> Uses;
6848 // This works by adding extra bitcasts between load/stores and removing
6849 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
6850 // we can get in the situation where we remove a bitcast in one iteration
6851 // just to add it again in the next. We need to ensure that at least one
6852 // bitcast we remove are anchored to something that will not change back.
6853 bool AnyAnchored = false;
6854
6855 while (!Worklist.empty()) {
6856 Instruction *II = Worklist.pop_back_val();
6857
6858 if (auto *Phi = dyn_cast<PHINode>(II)) {
6859 // Handle Defs, which might also be PHI's
6860 for (Value *V : Phi->incoming_values()) {
6861 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6862 if (!PhiNodes.count(OpPhi)) {
6863 if (!Visited.insert(OpPhi).second)
6864 return false;
6865 PhiNodes.insert(OpPhi);
6866 Worklist.push_back(OpPhi);
6867 }
6868 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
6869 if (!OpLoad->isSimple())
6870 return false;
6871 if (Defs.insert(OpLoad).second)
6872 Worklist.push_back(OpLoad);
6873 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
6874 if (Defs.insert(OpEx).second)
6875 Worklist.push_back(OpEx);
6876 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6877 if (!ConvertTy)
6878 ConvertTy = OpBC->getOperand(0)->getType();
6879 if (OpBC->getOperand(0)->getType() != ConvertTy)
6880 return false;
6881 if (Defs.insert(OpBC).second) {
6882 Worklist.push_back(OpBC);
6883 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
6884 !isa<ExtractElementInst>(OpBC->getOperand(0));
6885 }
6886 } else if (auto *OpC = dyn_cast<ConstantData>(V))
6887 Constants.insert(OpC);
6888 else
6889 return false;
6890 }
6891 }
6892
6893 // Handle uses which might also be phi's
6894 for (User *V : II->users()) {
6895 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6896 if (!PhiNodes.count(OpPhi)) {
6897 if (Visited.count(OpPhi))
6898 return false;
6899 PhiNodes.insert(OpPhi);
6900 Visited.insert(OpPhi);
6901 Worklist.push_back(OpPhi);
6902 }
6903 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
6904 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
6905 return false;
6906 Uses.insert(OpStore);
6907 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6908 if (!ConvertTy)
6909 ConvertTy = OpBC->getType();
6910 if (OpBC->getType() != ConvertTy)
6911 return false;
6912 Uses.insert(OpBC);
6913 AnyAnchored |=
6914 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
6915 } else {
6916 return false;
6917 }
6918 }
6919 }
6920
6921 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
6922 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
6923 return false;
6924
6925 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
6926 << *ConvertTy << "\n");
6927
6928 // Create all the new phi nodes of the new type, and bitcast any loads to the
6929 // correct type.
6930 ValueToValueMap ValMap;
6931 for (ConstantData *C : Constants)
6932 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
6933 for (Instruction *D : Defs) {
6934 if (isa<BitCastInst>(D)) {
6935 ValMap[D] = D->getOperand(0);
6936 DeletedInstrs.insert(D);
6937 } else {
6938 BasicBlock::iterator insertPt = std::next(D->getIterator());
6939 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
6940 }
6941 }
6942 for (PHINode *Phi : PhiNodes)
6943 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
6944 Phi->getName() + ".tc", Phi->getIterator());
6945 // Pipe together all the PhiNodes.
6946 for (PHINode *Phi : PhiNodes) {
6947 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
6948 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
6949 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
6950 Phi->getIncomingBlock(i));
6951 Visited.insert(NewPhi);
6952 }
6953 // And finally pipe up the stores and bitcasts
6954 for (Instruction *U : Uses) {
6955 if (isa<BitCastInst>(U)) {
6956 DeletedInstrs.insert(U);
6957 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
6958 } else {
6959 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
6960 U->getIterator()));
6961 }
6962 }
6963
6964 // Save the removed phis to be deleted later.
6965 DeletedInstrs.insert_range(PhiNodes);
6966 return true;
6967}
6968
6969bool CodeGenPrepare::optimizePhiTypes(Function &F) {
6970 if (!Opts.cgp_optimize_phi_types)
6971 return false;
6972
6973 bool Changed = false;
6974 SmallPtrSet<PHINode *, 4> Visited;
6975 SmallPtrSet<Instruction *, 4> DeletedInstrs;
6976
6977 // Attempt to optimize all the phis in the functions to the correct type.
6978 for (auto &BB : F)
6979 for (auto &Phi : BB.phis())
6980 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
6981
6982 // Remove any old phi's that have been converted.
6983 for (auto *I : DeletedInstrs) {
6984 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
6985 I->eraseFromParent();
6986 }
6987
6988 return Changed;
6989}
6990
6991/// Return true, if an ext(load) can be formed from an extension in
6992/// \p MovedExts.
6993bool CodeGenPrepare::canFormExtLd(
6994 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
6995 Instruction *&Inst, bool HasPromoted) {
6996 for (auto *MovedExtInst : MovedExts) {
6997 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
6998 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
6999 Inst = MovedExtInst;
7000 break;
7001 }
7002 }
7003 if (!LI)
7004 return false;
7005
7006 // If they're already in the same block, there's nothing to do.
7007 // Make the cheap checks first if we did not promote.
7008 // If we promoted, we need to check if it is indeed profitable.
7009 if (!HasPromoted && LI->getParent() == Inst->getParent())
7010 return false;
7011
7012 return TLI->isExtLoad(LI, Inst, *DL);
7013}
7014
7015/// Move a zext or sext fed by a load into the same basic block as the load,
7016/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7017/// extend into the load.
7018///
7019/// E.g.,
7020/// \code
7021/// %ld = load i32* %addr
7022/// %add = add nuw i32 %ld, 4
7023/// %zext = zext i32 %add to i64
7024// \endcode
7025/// =>
7026/// \code
7027/// %ld = load i32* %addr
7028/// %zext = zext i32 %ld to i64
7029/// %add = add nuw i64 %zext, 4
7030/// \encode
7031/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7032/// allow us to match zext(load i32*) to i64.
7033///
7034/// Also, try to promote the computations used to obtain a sign extended
7035/// value used into memory accesses.
7036/// E.g.,
7037/// \code
7038/// a = add nsw i32 b, 3
7039/// d = sext i32 a to i64
7040/// e = getelementptr ..., i64 d
7041/// \endcode
7042/// =>
7043/// \code
7044/// f = sext i32 b to i64
7045/// a = add nsw i64 f, 3
7046/// e = getelementptr ..., i64 a
7047/// \endcode
7048///
7049/// \p Inst[in/out] the extension may be modified during the process if some
7050/// promotions apply.
7051bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7052 bool AllowPromotionWithoutCommonHeader = false;
7053 /// See if it is an interesting sext operations for the address type
7054 /// promotion before trying to promote it, e.g., the ones with the right
7055 /// type and used in memory accesses.
7056 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7057 *Inst, AllowPromotionWithoutCommonHeader);
7058 TypePromotionTransaction TPT(RemovedInsts);
7059 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7060 TPT.getRestorationPoint();
7062 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7063 Exts.push_back(Inst);
7064
7065 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7066
7067 // Look for a load being extended.
7068 LoadInst *LI = nullptr;
7069 Instruction *ExtFedByLoad;
7070
7071 // Try to promote a chain of computation if it allows to form an extended
7072 // load.
7073 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7074 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7075 TPT.commit();
7076 // Move the extend into the same block as the load.
7077 ExtFedByLoad->moveAfter(LI);
7078 ++NumExtsMoved;
7079 Inst = ExtFedByLoad;
7080 return true;
7081 }
7082
7083 // Continue promoting SExts if known as considerable depending on targets.
7084 if (ATPConsiderable &&
7085 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7086 HasPromoted, TPT, SpeculativelyMovedExts))
7087 return true;
7088
7089 TPT.rollback(LastKnownGood);
7090 return false;
7091}
7092
7093// Perform address type promotion if doing so is profitable.
7094// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7095// instructions that sign extended the same initial value. However, if
7096// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7097// extension is just profitable.
7098bool CodeGenPrepare::performAddressTypePromotion(
7099 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7100 bool HasPromoted, TypePromotionTransaction &TPT,
7101 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7102 bool Promoted = false;
7103 SmallPtrSet<Instruction *, 1> UnhandledExts;
7104 bool AllSeenFirst = true;
7105 for (auto *I : SpeculativelyMovedExts) {
7106 Value *HeadOfChain = I->getOperand(0);
7107 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7108 // If there is an unhandled SExt which has the same header, try to promote
7109 // it as well.
7110 if (AlreadySeen != SeenChainsForSExt.end()) {
7111 if (AlreadySeen->second != nullptr)
7112 UnhandledExts.insert(AlreadySeen->second);
7113 AllSeenFirst = false;
7114 }
7115 }
7116
7117 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7118 SpeculativelyMovedExts.size() == 1)) {
7119 TPT.commit();
7120 if (HasPromoted)
7121 Promoted = true;
7122 for (auto *I : SpeculativelyMovedExts) {
7123 Value *HeadOfChain = I->getOperand(0);
7124 SeenChainsForSExt[HeadOfChain] = nullptr;
7125 ValToSExtendedUses[HeadOfChain].push_back(I);
7126 }
7127 // Update Inst as promotion happen.
7128 Inst = SpeculativelyMovedExts.pop_back_val();
7129 } else {
7130 // This is the first chain visited from the header, keep the current chain
7131 // as unhandled. Defer to promote this until we encounter another SExt
7132 // chain derived from the same header.
7133 for (auto *I : SpeculativelyMovedExts) {
7134 Value *HeadOfChain = I->getOperand(0);
7135 SeenChainsForSExt[HeadOfChain] = Inst;
7136 }
7137 return false;
7138 }
7139
7140 if (!AllSeenFirst && !UnhandledExts.empty())
7141 for (auto *VisitedSExt : UnhandledExts) {
7142 if (RemovedInsts.count(VisitedSExt))
7143 continue;
7144 TypePromotionTransaction TPT(RemovedInsts);
7146 SmallVector<Instruction *, 2> Chains;
7147 Exts.push_back(VisitedSExt);
7148 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7149 TPT.commit();
7150 if (HasPromoted)
7151 Promoted = true;
7152 for (auto *I : Chains) {
7153 Value *HeadOfChain = I->getOperand(0);
7154 // Mark this as handled.
7155 SeenChainsForSExt[HeadOfChain] = nullptr;
7156 ValToSExtendedUses[HeadOfChain].push_back(I);
7157 }
7158 }
7159 return Promoted;
7160}
7161
7162bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7163 BasicBlock *DefBB = I->getParent();
7164
7165 // If the result of a {s|z}ext and its source are both live out, rewrite all
7166 // other uses of the source with result of extension.
7167 Value *Src = I->getOperand(0);
7168 if (Src->hasOneUse())
7169 return false;
7170
7171 // Only do this xform if truncating is free.
7172 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7173 return false;
7174
7175 // Only safe to perform the optimization if the source is also defined in
7176 // this block.
7177 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7178 return false;
7179
7180 bool DefIsLiveOut = false;
7181 for (User *U : I->users()) {
7183
7184 // Figure out which BB this ext is used in.
7185 BasicBlock *UserBB = UI->getParent();
7186 if (UserBB == DefBB)
7187 continue;
7188 DefIsLiveOut = true;
7189 break;
7190 }
7191 if (!DefIsLiveOut)
7192 return false;
7193
7194 // Make sure none of the uses are PHI nodes.
7195 for (User *U : Src->users()) {
7197 BasicBlock *UserBB = UI->getParent();
7198 if (UserBB == DefBB)
7199 continue;
7200 // Be conservative. We don't want this xform to end up introducing
7201 // reloads just before load / store instructions.
7202 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7203 return false;
7204 }
7205
7206 // InsertedTruncs - Only insert one trunc in each block once.
7207 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7208
7209 bool MadeChange = false;
7210 for (Use &U : make_early_inc_range(Src->uses())) {
7211 Instruction *User = cast<Instruction>(U.getUser());
7212
7213 // Figure out which BB this ext is used in.
7214 BasicBlock *UserBB = User->getParent();
7215 if (UserBB == DefBB)
7216 continue;
7217
7218 // Both src and def are live in this block. Rewrite the use.
7219 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7220
7221 if (!InsertedTrunc) {
7222 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7223 assert(InsertPt != UserBB->end());
7224 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7225 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7226 InsertedInsts.insert(InsertedTrunc);
7227 }
7228
7229 // Replace a use of the {s|z}ext source with a use of the result.
7230 U = InsertedTrunc;
7231 ++NumExtUses;
7232 MadeChange = true;
7233 }
7234
7235 // The uses rewritten above read trunc(I), which equals Src only where I isn't
7236 // poison. A poison-generating flag such as zext nneg can only hold under a
7237 // guard, such as a sign check of Src, that itself is one of those uses.
7238 if (MadeChange)
7239 I->dropPoisonGeneratingFlags();
7240
7241 return MadeChange;
7242}
7243
7244// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7245// just after the load if the target can fold this into one extload instruction,
7246// with the hope of eliminating some of the other later "and" instructions using
7247// the loaded value. "and"s that are made trivially redundant by the insertion
7248// of the new "and" are removed by this function, while others (e.g. those whose
7249// path from the load goes through a phi) are left for isel to potentially
7250// remove.
7251//
7252// For example:
7253//
7254// b0:
7255// x = load i32
7256// ...
7257// b1:
7258// y = and x, 0xff
7259// z = use y
7260//
7261// becomes:
7262//
7263// b0:
7264// x = load i32
7265// x' = and x, 0xff
7266// ...
7267// b1:
7268// z = use x'
7269//
7270// whereas:
7271//
7272// b0:
7273// x1 = load i32
7274// ...
7275// b1:
7276// x2 = load i32
7277// ...
7278// b2:
7279// x = phi x1, x2
7280// y = and x, 0xff
7281//
7282// becomes (after a call to optimizeLoadExt for each load):
7283//
7284// b0:
7285// x1 = load i32
7286// x1' = and x1, 0xff
7287// ...
7288// b1:
7289// x2 = load i32
7290// x2' = and x2, 0xff
7291// ...
7292// b2:
7293// x = phi x1', x2'
7294// y = and x, 0xff
7295bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7296 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7297 return false;
7298
7299 // Skip loads we've already transformed.
7300 if (Load->hasOneUse() &&
7301 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
7302 return false;
7303
7304 // Look at all uses of Load, looking through phis, to determine how many bits
7305 // of the loaded value are needed.
7306 SmallVector<Instruction *, 8> WorkList;
7307 SmallPtrSet<Instruction *, 16> Visited;
7308 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7309 SmallVector<Instruction *, 8> DropFlags;
7310 for (auto *U : Load->users())
7311 WorkList.push_back(cast<Instruction>(U));
7312
7313 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7314 unsigned BitWidth = LoadResultVT.getSizeInBits();
7315 // If the BitWidth is 0, do not try to optimize the type
7316 if (BitWidth == 0)
7317 return false;
7318
7319 APInt DemandBits(BitWidth, 0);
7320 APInt WidestAndBits(BitWidth, 0);
7321
7322 while (!WorkList.empty()) {
7323 Instruction *I = WorkList.pop_back_val();
7324
7325 // Break use-def graph loops.
7326 if (!Visited.insert(I).second)
7327 continue;
7328
7329 // For a PHI node, push all of its users.
7330 if (auto *Phi = dyn_cast<PHINode>(I)) {
7331 for (auto *U : Phi->users())
7332 WorkList.push_back(cast<Instruction>(U));
7333 continue;
7334 }
7335
7336 switch (I->getOpcode()) {
7337 case Instruction::And: {
7338 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7339 if (!AndC)
7340 return false;
7341 APInt AndBits = AndC->getValue();
7342 DemandBits |= AndBits;
7343 // Keep track of the widest and mask we see.
7344 if (AndBits.ugt(WidestAndBits))
7345 WidestAndBits = AndBits;
7346 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7347 AndsToMaybeRemove.push_back(I);
7348 break;
7349 }
7350
7351 case Instruction::Shl: {
7352 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7353 if (!ShlC)
7354 return false;
7355 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7356 DemandBits.setLowBits(BitWidth - ShiftAmt);
7357 DropFlags.push_back(I);
7358 break;
7359 }
7360
7361 case Instruction::Trunc: {
7362 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7363 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7364 DemandBits.setLowBits(TruncBitWidth);
7365 DropFlags.push_back(I);
7366 break;
7367 }
7368
7369 default:
7370 return false;
7371 }
7372 }
7373
7374 uint32_t ActiveBits = DemandBits.getActiveBits();
7375 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7376 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7377 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7378 // true, but (and (load x) 1) is not matched as a single instruction, rather
7379 // as a LDR followed by an AND.
7380 // TODO: Look into removing this restriction by fixing backends to either
7381 // return false for isLoadLegal for i1 or have them select this pattern to
7382 // a single instruction.
7383 //
7384 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7385 // mask, since these are the only ands that will be removed by isel.
7386 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7387 WidestAndBits != DemandBits)
7388 return false;
7389
7390 LLVMContext &Ctx = Load->getType()->getContext();
7391 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7392 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7393
7394 // Reject cases that won't be matched as extloads.
7395 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7396 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7397 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7398 return false;
7399
7400 IRBuilder<> Builder(Load->getNextNode());
7401 auto *NewAnd = cast<Instruction>(
7402 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7403 // Mark this instruction as "inserted by CGP", so that other
7404 // optimizations don't touch it.
7405 InsertedInsts.insert(NewAnd);
7406
7407 // Replace all uses of load with new and (except for the use of load in the
7408 // new and itself).
7409 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7410 NewAnd->setOperand(0, Load);
7411
7412 // Remove any and instructions that are now redundant.
7413 for (auto *And : AndsToMaybeRemove)
7414 // Check that the and mask is the same as the one we decided to put on the
7415 // new and.
7416 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7417 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7418 if (&*CurInstIterator == And)
7419 CurInstIterator = std::next(And->getIterator());
7420 And->eraseFromParent();
7421 ++NumAndUses;
7422 }
7423
7424 // NSW flags may not longer hold.
7425 for (auto *Inst : DropFlags)
7426 Inst->setHasNoSignedWrap(false);
7427
7428 ++NumAndsAdded;
7429 return true;
7430}
7431
7432/// Check if V (an operand of a select instruction) is an expensive instruction
7433/// that is only used once.
7435 auto *I = dyn_cast<Instruction>(V);
7436 // If it's safe to speculatively execute, then it should not have side
7437 // effects; therefore, it's safe to sink and possibly *not* execute.
7438 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7439 TTI->isExpensiveToSpeculativelyExecute(I);
7440}
7441
7442/// Returns true if a SelectInst should be turned into an explicit branch.
7444 const TargetLowering *TLI,
7445 SelectInst *SI) {
7446 // If even a predictable select is cheap, then a branch can't be cheaper.
7447 if (!TLI->isPredictableSelectExpensive())
7448 return false;
7449
7450 // FIXME: This should use the same heuristics as IfConversion to determine
7451 // whether a select is better represented as a branch.
7452
7453 // If metadata tells us that the select condition is obviously predictable,
7454 // then we want to replace the select with a branch.
7455 uint64_t TrueWeight, FalseWeight;
7456 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7457 uint64_t Max = std::max(TrueWeight, FalseWeight);
7458 uint64_t Sum = TrueWeight + FalseWeight;
7459 if (Sum != 0) {
7460 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7461 if (Probability > TTI->getPredictableBranchThreshold())
7462 return true;
7463 }
7464 }
7465
7466 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7467
7468 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7469 // comparison condition. If the compare has more than one use, there's
7470 // probably another cmov or setcc around, so it's not worth emitting a branch.
7471 if (!Cmp || !Cmp->hasOneUse())
7472 return false;
7473
7474 // If either operand of the select is expensive and only needed on one side
7475 // of the select, we should form a branch.
7476 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7477 sinkSelectOperand(TTI, SI->getFalseValue()))
7478 return true;
7479
7480 return false;
7481}
7482
7483/// If \p isTrue is true, return the true value of \p SI, otherwise return
7484/// false value of \p SI. If the true/false value of \p SI is defined by any
7485/// select instructions in \p Selects, look through the defining select
7486/// instruction until the true/false value is not defined in \p Selects.
7487static Value *
7489 const SmallPtrSet<const Instruction *, 2> &Selects) {
7490 Value *V = nullptr;
7491
7492 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7493 DefSI = dyn_cast<SelectInst>(V)) {
7494 assert(DefSI->getCondition() == SI->getCondition() &&
7495 "The condition of DefSI does not match with SI");
7496 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7497 }
7498
7499 assert(V && "Failed to get select true/false value");
7500 return V;
7501}
7502
7503bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7504 assert(Shift->isShift() && "Expected a shift");
7505
7506 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7507 // general vector shifts, and (3) the shift amount is a select-of-splatted
7508 // values, hoist the shifts before the select:
7509 // shift Op0, (select Cond, TVal, FVal) -->
7510 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7511 //
7512 // This is inverting a generic IR transform when we know that the cost of a
7513 // general vector shift is more than the cost of 2 shift-by-scalars.
7514 // We can't do this effectively in SDAG because we may not be able to
7515 // determine if the select operands are splats from within a basic block.
7516 Type *Ty = Shift->getType();
7517 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7518 return false;
7519 Value *Cond, *TVal, *FVal;
7520 if (!match(Shift->getOperand(1),
7521 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7522 return false;
7523 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7524 return false;
7525
7526 IRBuilder<> Builder(Shift);
7527 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7528 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7529 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7530 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7531 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7532 Shift->eraseFromParent();
7533 return true;
7534}
7535
7536bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7537 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7538 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7539 "Expected a funnel shift");
7540
7541 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7542 // than general vector shifts, and (3) the shift amount is select-of-splatted
7543 // values, hoist the funnel shifts before the select:
7544 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7545 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7546 //
7547 // This is inverting a generic IR transform when we know that the cost of a
7548 // general vector shift is more than the cost of 2 shift-by-scalars.
7549 // We can't do this effectively in SDAG because we may not be able to
7550 // determine if the select operands are splats from within a basic block.
7551 Type *Ty = Fsh->getType();
7552 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7553 return false;
7554 Value *Cond, *TVal, *FVal;
7555 if (!match(Fsh->getOperand(2),
7556 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7557 return false;
7558 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7559 return false;
7560
7561 IRBuilder<> Builder(Fsh);
7562 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7563 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7564 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7565 Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
7566 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7567 Fsh->eraseFromParent();
7568 return true;
7569}
7570
7571/// If we have a SelectInst that will likely profit from branch prediction,
7572/// turn it into a branch.
7573bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7574 if (!Opts.cgp_select2branch)
7575 return false;
7576
7577 // If the SelectOptimize pass is enabled, selects have already been optimized.
7578 if (!Opts.disable_select_optimize)
7579 return false;
7580
7581 // Find all consecutive select instructions that share the same condition.
7583 ASI.push_back(SI);
7585 It != SI->getParent()->end(); ++It) {
7586 SelectInst *I = dyn_cast<SelectInst>(&*It);
7587 if (I && SI->getCondition() == I->getCondition()) {
7588 ASI.push_back(I);
7589 } else {
7590 break;
7591 }
7592 }
7593
7594 SelectInst *LastSI = ASI.back();
7595 // Increment the current iterator to skip all the rest of select instructions
7596 // because they will be either "not lowered" or "all lowered" to branch.
7597 CurInstIterator = std::next(LastSI->getIterator());
7598 // Examine debug-info attached to the consecutive select instructions. They
7599 // won't be individually optimised by optimizeInst, so we need to perform
7600 // DbgVariableRecord maintenence here instead.
7601 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7602 fixupDbgVariableRecordsOnInst(*SI);
7603
7604 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7605
7606 // Can we convert the 'select' to CF ?
7607 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7608 return false;
7609
7610 TargetLowering::SelectSupportKind SelectKind;
7611 if (SI->getType()->isVectorTy())
7612 SelectKind = TargetLowering::ScalarCondVectorVal;
7613 else
7614 SelectKind = TargetLowering::ScalarValSelect;
7615
7616 if (TLI->isSelectSupported(SelectKind) &&
7618 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7619 return false;
7620
7621 // Transform a sequence like this:
7622 // start:
7623 // %cmp = cmp uge i32 %a, %b
7624 // %sel = select i1 %cmp, i32 %c, i32 %d
7625 //
7626 // Into:
7627 // start:
7628 // %cmp = cmp uge i32 %a, %b
7629 // %cmp.frozen = freeze %cmp
7630 // br i1 %cmp.frozen, label %select.true, label %select.false
7631 // select.true:
7632 // br label %select.end
7633 // select.false:
7634 // br label %select.end
7635 // select.end:
7636 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7637 //
7638 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7639 // In addition, we may sink instructions that produce %c or %d from
7640 // the entry block into the destination(s) of the new branch.
7641 // If the true or false blocks do not contain a sunken instruction, that
7642 // block and its branch may be optimized away. In that case, one side of the
7643 // first branch will point directly to select.end, and the corresponding PHI
7644 // predecessor block will be the start block.
7645 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7646 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7647 // runOnFunction for each select optimized.
7648
7649 // Collect values that go on the true side and the values that go on the false
7650 // side.
7651 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7652 for (SelectInst *SI : ASI) {
7653 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7654 TrueInstrs.push_back(cast<Instruction>(V));
7655 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7656 FalseInstrs.push_back(cast<Instruction>(V));
7657 }
7658
7659 // Split the select block, according to how many (if any) values go on each
7660 // side.
7661 BasicBlock *StartBlock = SI->getParent();
7662 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7663 // We should split before any debug-info.
7664 SplitPt.setHeadBit(true);
7665
7666 IRBuilder<> IB(SI);
7667 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7668
7669 BasicBlock *TrueBlock = nullptr;
7670 BasicBlock *FalseBlock = nullptr;
7671 BasicBlock *EndBlock = nullptr;
7672 UncondBrInst *TrueBranch = nullptr;
7673 UncondBrInst *FalseBranch = nullptr;
7674 if (TrueInstrs.size() == 0) {
7675 FalseBranch = cast<UncondBrInst>(
7676 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7677 FalseBlock = FalseBranch->getParent();
7678 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7679 } else if (FalseInstrs.size() == 0) {
7680 TrueBranch = cast<UncondBrInst>(
7681 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7682 TrueBlock = TrueBranch->getParent();
7683 EndBlock = TrueBranch->getSuccessor();
7684 } else {
7685 Instruction *ThenTerm = nullptr;
7686 Instruction *ElseTerm = nullptr;
7687 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7688 nullptr, DTU, LI);
7689 TrueBranch = cast<UncondBrInst>(ThenTerm);
7690 FalseBranch = cast<UncondBrInst>(ElseTerm);
7691 TrueBlock = TrueBranch->getParent();
7692 FalseBlock = FalseBranch->getParent();
7693 EndBlock = TrueBranch->getSuccessor();
7694 }
7695
7696 EndBlock->setName("select.end");
7697 if (TrueBlock)
7698 TrueBlock->setName("select.true.sink");
7699 if (FalseBlock)
7700 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7701 : "select.false.sink");
7702
7703 if (IsHugeFunc) {
7704 if (TrueBlock)
7705 FreshBBs.insert(TrueBlock);
7706 if (FalseBlock)
7707 FreshBBs.insert(FalseBlock);
7708 FreshBBs.insert(EndBlock);
7709 }
7710
7711 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7712
7713 static const unsigned MD[] = {
7714 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7715 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7716 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7717
7718 // Sink expensive instructions into the conditional blocks to avoid executing
7719 // them speculatively.
7720 for (Instruction *I : TrueInstrs)
7721 I->moveBefore(TrueBranch->getIterator());
7722 for (Instruction *I : FalseInstrs)
7723 I->moveBefore(FalseBranch->getIterator());
7724
7725 // If we did not create a new block for one of the 'true' or 'false' paths
7726 // of the condition, it means that side of the branch goes to the end block
7727 // directly and the path originates from the start block from the point of
7728 // view of the new PHI.
7729 if (TrueBlock == nullptr)
7730 TrueBlock = StartBlock;
7731 else if (FalseBlock == nullptr)
7732 FalseBlock = StartBlock;
7733
7734 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7735 // Use reverse iterator because later select may use the value of the
7736 // earlier select, and we need to propagate value through earlier select
7737 // to get the PHI operand.
7738 for (SelectInst *SI : llvm::reverse(ASI)) {
7739 // The select itself is replaced with a PHI Node.
7740 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7741 PN->insertBefore(EndBlock->begin());
7742 PN->takeName(SI);
7743 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7744 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7745 PN->setDebugLoc(SI->getDebugLoc());
7746
7747 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7748 SI->eraseFromParent();
7749 INS.erase(SI);
7750 ++NumSelectsExpanded;
7751 }
7752
7753 // Instruct OptimizeBlock to skip to the next block.
7754 CurInstIterator = StartBlock->end();
7755 return true;
7756}
7757
7758/// Some targets only accept certain types for splat inputs. For example a VDUP
7759/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7760/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7761bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7762 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7764 m_Undef(), m_ZeroMask())))
7765 return false;
7766 Type *NewType = TLI->shouldConvertSplatType(SVI);
7767 if (!NewType)
7768 return false;
7769
7770 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7771 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7772 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7773 "Expected a type of the same size!");
7774 auto *NewVecType =
7775 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7776
7777 // Create a bitcast (shuffle (insert (bitcast(..))))
7778 IRBuilder<> Builder(SVI);
7779 Value *BC1 = Builder.CreateBitCast(
7780 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7781 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7782 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7783
7784 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7786 SVI, TLInfo, nullptr,
7787 [&](Value *V) { removeAllAssertingVHReferences(V); });
7788
7789 // Also hoist the bitcast up to its operand if it they are not in the same
7790 // block.
7791 if (auto *BCI = dyn_cast<Instruction>(BC1))
7792 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7793 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7794 !Op->isTerminator() && !Op->isEHPad())
7795 BCI->moveAfter(Op);
7796
7797 return true;
7798}
7799
7800bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7801 // If the operands of I can be folded into a target instruction together with
7802 // I, duplicate and sink them.
7803 SmallVector<Use *, 4> OpsToSink;
7804 if (!TTI->isProfitableToSinkOperands(I, OpsToSink, LI))
7805 return false;
7806
7807 // OpsToSink can contain multiple uses in a use chain (e.g.
7808 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7809 // uses must come first, so we process the ops in reverse order so as to not
7810 // create invalid IR.
7811 BasicBlock *TargetBB = I->getParent();
7812 bool Changed = false;
7813 SmallVector<Use *, 4> ToReplace;
7814 Instruction *InsertPoint = I;
7815 for (Use *U : reverse(OpsToSink)) {
7816 auto *UI = cast<Instruction>(U->get());
7817 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7818 continue;
7819 if (UI->getParent() == TargetBB) {
7820 if (UI->comesBefore(InsertPoint))
7821 InsertPoint = UI;
7822 continue;
7823 }
7824 ToReplace.push_back(U);
7825 }
7826
7827 SetVector<Instruction *> MaybeDead;
7828 DenseMap<Instruction *, Instruction *> NewInstructions;
7829 for (Use *U : ToReplace) {
7830 auto *UI = cast<Instruction>(U->get());
7831 Instruction *NI = UI->clone();
7832
7833 if (IsHugeFunc) {
7834 // Now we clone an instruction, its operands' defs may sink to this BB
7835 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7836 for (Value *Op : NI->operands())
7837 if (auto *OpDef = dyn_cast<Instruction>(Op))
7838 FreshBBs.insert(OpDef->getParent());
7839 }
7840
7841 NewInstructions[UI] = NI;
7842 MaybeDead.insert(UI);
7843 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7844 NI->insertBefore(InsertPoint->getIterator());
7845 InsertPoint = NI;
7846 InsertedInsts.insert(NI);
7847
7848 // Update the use for the new instruction, making sure that we update the
7849 // sunk instruction uses, if it is part of a chain that has already been
7850 // sunk.
7851 Instruction *OldI = cast<Instruction>(U->getUser());
7852 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
7853 It->second->setOperand(U->getOperandNo(), NI);
7854 else
7855 U->set(NI);
7856 Changed = true;
7857 }
7858
7859 // Remove instructions that are dead after sinking.
7860 for (auto *I : MaybeDead) {
7861 if (!I->hasNUsesOrMore(1)) {
7862 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
7863 I->eraseFromParent();
7864 }
7865 }
7866
7867 return Changed;
7868}
7869
7870bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7871 Value *Cond = SI->getCondition();
7872 Type *OldType = Cond->getType();
7873 LLVMContext &Context = Cond->getContext();
7874 EVT OldVT = TLI->getValueType(*DL, OldType);
7876 unsigned RegWidth = RegType.getSizeInBits();
7877
7878 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
7879 return false;
7880
7881 // If the register width is greater than the type width, expand the condition
7882 // of the switch instruction and each case constant to the width of the
7883 // register. By widening the type of the switch condition, subsequent
7884 // comparisons (for case comparisons) will not need to be extended to the
7885 // preferred register width, so we will potentially eliminate N-1 extends,
7886 // where N is the number of cases in the switch.
7887 auto *NewType = Type::getIntNTy(Context, RegWidth);
7888
7889 // Extend the switch condition and case constants using the target preferred
7890 // extend unless the switch condition is a function argument with an extend
7891 // attribute. In that case, we can avoid an unnecessary mask/extension by
7892 // matching the argument extension instead.
7893 Instruction::CastOps ExtType = Instruction::ZExt;
7894 // Some targets prefer SExt over ZExt.
7895 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
7896 ExtType = Instruction::SExt;
7897
7898 if (auto *Arg = dyn_cast<Argument>(Cond)) {
7899 if (Arg->hasSExtAttr())
7900 ExtType = Instruction::SExt;
7901 if (Arg->hasZExtAttr())
7902 ExtType = Instruction::ZExt;
7903 }
7904
7905 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
7906 ExtInst->insertBefore(SI->getIterator());
7907 ExtInst->setDebugLoc(SI->getDebugLoc());
7908 SI->setCondition(ExtInst);
7909 for (auto Case : SI->cases()) {
7910 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7911 APInt WideConst = (ExtType == Instruction::ZExt)
7912 ? NarrowConst.zext(RegWidth)
7913 : NarrowConst.sext(RegWidth);
7914 Case.setValue(ConstantInt::get(Context, WideConst));
7915 }
7916
7917 return true;
7918}
7919
7920bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7921 // The SCCP optimization tends to produce code like this:
7922 // switch(x) { case 42: phi(42, ...) }
7923 // Materializing the constant for the phi-argument needs instructions; So we
7924 // change the code to:
7925 // switch(x) { case 42: phi(x, ...) }
7926
7927 Value *Condition = SI->getCondition();
7928 // Avoid endless loop in degenerate case.
7929 if (isa<ConstantInt>(*Condition))
7930 return false;
7931
7932 bool Changed = false;
7933 BasicBlock *SwitchBB = SI->getParent();
7934 Type *ConditionType = Condition->getType();
7935
7936 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
7937 ConstantInt *CaseValue = Case.getCaseValue();
7938 BasicBlock *CaseBB = Case.getCaseSuccessor();
7939 // Set to true if we previously checked that `CaseBB` is only reached by
7940 // a single case from this switch.
7941 bool CheckedForSinglePred = false;
7942 for (PHINode &PHI : CaseBB->phis()) {
7943 Type *PHIType = PHI.getType();
7944 // If ZExt is free then we can also catch patterns like this:
7945 // switch((i32)x) { case 42: phi((i64)42, ...); }
7946 // and replace `(i64)42` with `zext i32 %x to i64`.
7947 bool TryZExt =
7948 PHIType->isIntegerTy() &&
7949 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
7950 TLI->isZExtFree(ConditionType, PHIType);
7951 if (PHIType == ConditionType || TryZExt) {
7952 // Set to true to skip this case because of multiple preds.
7953 bool SkipCase = false;
7954 Value *Replacement = nullptr;
7955 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
7956 Value *PHIValue = PHI.getIncomingValue(I);
7957 if (PHIValue != CaseValue) {
7958 if (!TryZExt)
7959 continue;
7960 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
7961 if (!PHIValueInt ||
7962 PHIValueInt->getValue() !=
7963 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
7964 continue;
7965 }
7966 if (PHI.getIncomingBlock(I) != SwitchBB)
7967 continue;
7968 // We cannot optimize if there are multiple case labels jumping to
7969 // this block. This check may get expensive when there are many
7970 // case labels so we test for it last.
7971 if (!CheckedForSinglePred) {
7972 CheckedForSinglePred = true;
7973 if (SI->findCaseDest(CaseBB) == nullptr) {
7974 SkipCase = true;
7975 break;
7976 }
7977 }
7978
7979 if (Replacement == nullptr) {
7980 if (PHIValue == CaseValue) {
7981 Replacement = Condition;
7982 } else {
7983 IRBuilder<> Builder(SI);
7984 Replacement = Builder.CreateZExt(Condition, PHIType);
7985 }
7986 }
7987 PHI.setIncomingValue(I, Replacement);
7988 Changed = true;
7989 }
7990 if (SkipCase)
7991 break;
7992 }
7993 }
7994 }
7995 return Changed;
7996}
7997
7998bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
7999 bool Changed = optimizeSwitchType(SI);
8000 Changed |= optimizeSwitchPhiConstants(SI);
8001 return Changed;
8002}
8003
8004namespace {
8005
8006/// Helper class to promote a scalar operation to a vector one.
8007/// This class is used to move downward extractelement transition.
8008/// E.g.,
8009/// a = vector_op <2 x i32>
8010/// b = extractelement <2 x i32> a, i32 0
8011/// c = scalar_op b
8012/// store c
8013///
8014/// =>
8015/// a = vector_op <2 x i32>
8016/// c = vector_op a (equivalent to scalar_op on the related lane)
8017/// * d = extractelement <2 x i32> c, i32 0
8018/// * store d
8019/// Assuming both extractelement and store can be combine, we get rid of the
8020/// transition.
8021class VectorPromoteHelper {
8022 /// DataLayout associated with the current module.
8023 const DataLayout &DL;
8024
8025 /// Used to perform some checks on the legality of vector operations.
8026 const TargetLowering &TLI;
8027
8028 /// Used to estimated the cost of the promoted chain.
8029 const TargetTransformInfo &TTI;
8030
8031 /// The transition being moved downwards.
8032 Instruction *Transition;
8033
8034 /// The sequence of instructions to be promoted.
8035 SmallVector<Instruction *, 4> InstsToBePromoted;
8036
8037 /// Cost of combining a store and an extract.
8038 unsigned StoreExtractCombineCost;
8039
8040 bool StressStoreExtract;
8041
8042 /// Instruction that will be combined with the transition.
8043 Instruction *CombineInst = nullptr;
8044
8045 /// The instruction that represents the current end of the transition.
8046 /// Since we are faking the promotion until we reach the end of the chain
8047 /// of computation, we need a way to get the current end of the transition.
8048 Instruction *getEndOfTransition() const {
8049 if (InstsToBePromoted.empty())
8050 return Transition;
8051 return InstsToBePromoted.back();
8052 }
8053
8054 /// Return the index of the original value in the transition.
8055 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8056 /// c, is at index 0.
8057 unsigned getTransitionOriginalValueIdx() const {
8058 assert(isa<ExtractElementInst>(Transition) &&
8059 "Other kind of transitions are not supported yet");
8060 return 0;
8061 }
8062
8063 /// Return the index of the index in the transition.
8064 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8065 /// is at index 1.
8066 unsigned getTransitionIdx() const {
8067 assert(isa<ExtractElementInst>(Transition) &&
8068 "Other kind of transitions are not supported yet");
8069 return 1;
8070 }
8071
8072 /// Get the type of the transition.
8073 /// This is the type of the original value.
8074 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8075 /// transition is <2 x i32>.
8076 Type *getTransitionType() const {
8077 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8078 }
8079
8080 /// Promote \p ToBePromoted by moving \p Def downward through.
8081 /// I.e., we have the following sequence:
8082 /// Def = Transition <ty1> a to <ty2>
8083 /// b = ToBePromoted <ty2> Def, ...
8084 /// =>
8085 /// b = ToBePromoted <ty1> a, ...
8086 /// Def = Transition <ty1> ToBePromoted to <ty2>
8087 void promoteImpl(Instruction *ToBePromoted);
8088
8089 /// Check whether or not it is profitable to promote all the
8090 /// instructions enqueued to be promoted.
8091 bool isProfitableToPromote() {
8092 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8093 unsigned Index = isa<ConstantInt>(ValIdx)
8094 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8095 : -1;
8096 Type *PromotedType = getTransitionType();
8097
8098 StoreInst *ST = cast<StoreInst>(CombineInst);
8099 unsigned AS = ST->getPointerAddressSpace();
8100 // Check if this store is supported.
8102 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8103 ST->getAlign())) {
8104 // If this is not supported, there is no way we can combine
8105 // the extract with the store.
8106 return false;
8107 }
8108
8109 // The scalar chain of computation has to pay for the transition
8110 // scalar to vector.
8111 // The vector chain has to account for the combining cost.
8114 InstructionCost ScalarCost =
8115 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8116 InstructionCost VectorCost = StoreExtractCombineCost;
8117 for (const auto &Inst : InstsToBePromoted) {
8118 // Compute the cost.
8119 // By construction, all instructions being promoted are arithmetic ones.
8120 // Moreover, one argument is a constant that can be viewed as a splat
8121 // constant.
8122 Value *Arg0 = Inst->getOperand(0);
8123 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8124 isa<ConstantFP>(Arg0);
8125 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8126 if (IsArg0Constant)
8128 else
8130
8131 ScalarCost += TTI.getArithmeticInstrCost(
8132 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8133 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8134 CostKind, Arg0Info, Arg1Info);
8135 }
8136 LLVM_DEBUG(
8137 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8138 << ScalarCost << "\nVector: " << VectorCost << '\n');
8139 return ScalarCost > VectorCost;
8140 }
8141
8142 /// Generate a constant vector with \p Val with the same
8143 /// number of elements as the transition.
8144 /// \p UseSplat defines whether or not \p Val should be replicated
8145 /// across the whole vector.
8146 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8147 /// otherwise we generate a vector with as many poison as possible:
8148 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8149 /// used at the index of the extract.
8150 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8151 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8152 if (!UseSplat) {
8153 // If we cannot determine where the constant must be, we have to
8154 // use a splat constant.
8155 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8156 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8157 ExtractIdx = CstVal->getSExtValue();
8158 else
8159 UseSplat = true;
8160 }
8161
8162 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8163 if (UseSplat)
8164 return ConstantVector::getSplat(EC, Val);
8165
8166 if (!EC.isScalable()) {
8167 SmallVector<Constant *, 4> ConstVec;
8168 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8169 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8170 if (Idx == ExtractIdx)
8171 ConstVec.push_back(Val);
8172 else
8173 ConstVec.push_back(PoisonVal);
8174 }
8175 return ConstantVector::get(ConstVec);
8176 } else
8178 "Generate scalable vector for non-splat is unimplemented");
8179 }
8180
8181 /// Check if promoting to a vector type an operand at \p OperandIdx
8182 /// in \p Use can trigger undefined behavior.
8183 static bool canCauseUndefinedBehavior(const Instruction *Use,
8184 unsigned OperandIdx) {
8185 // This is not safe to introduce undef when the operand is on
8186 // the right hand side of a division-like instruction.
8187 if (OperandIdx != 1)
8188 return false;
8189 switch (Use->getOpcode()) {
8190 default:
8191 return false;
8192 case Instruction::SDiv:
8193 case Instruction::UDiv:
8194 case Instruction::SRem:
8195 case Instruction::URem:
8196 return true;
8197 case Instruction::FDiv:
8198 case Instruction::FRem:
8199 return !Use->hasNoNaNs();
8200 }
8201 llvm_unreachable(nullptr);
8202 }
8203
8204public:
8205 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8206 const TargetTransformInfo &TTI, Instruction *Transition,
8207 unsigned CombineCost, bool StressStoreExtract)
8208 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8209 StoreExtractCombineCost(CombineCost),
8210 StressStoreExtract(StressStoreExtract) {
8211 assert(Transition && "Do not know how to promote null");
8212 }
8213
8214 /// Check if we can promote \p ToBePromoted to \p Type.
8215 bool canPromote(const Instruction *ToBePromoted) const {
8216 // We could support CastInst too.
8217 return isa<BinaryOperator>(ToBePromoted);
8218 }
8219
8220 /// Check if it is profitable to promote \p ToBePromoted
8221 /// by moving downward the transition through.
8222 bool shouldPromote(const Instruction *ToBePromoted) const {
8224 return false;
8225 // Promote only if all the operands can be statically expanded.
8226 // Indeed, we do not want to introduce any new kind of transitions.
8227 for (const Use &U : ToBePromoted->operands()) {
8228 const Value *Val = U.get();
8229 if (Val == getEndOfTransition()) {
8230 continue;
8231 }
8232 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8233 !isa<ConstantFP>(Val))
8234 return false;
8235 }
8236 // Check that the resulting operation is legal.
8237 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8238 if (!ISDOpcode)
8239 return false;
8240 return StressStoreExtract ||
8242 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8243 }
8244
8245 /// Check whether or not \p Use can be combined
8246 /// with the transition.
8247 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8248 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8249
8250 /// Record \p ToBePromoted as part of the chain to be promoted.
8251 void enqueueForPromotion(Instruction *ToBePromoted) {
8252 InstsToBePromoted.push_back(ToBePromoted);
8253 }
8254
8255 /// Set the instruction that will be combined with the transition.
8256 void recordCombineInstruction(Instruction *ToBeCombined) {
8257 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8258 CombineInst = ToBeCombined;
8259 }
8260
8261 /// Promote all the instructions enqueued for promotion if it is
8262 /// is profitable.
8263 /// \return True if the promotion happened, false otherwise.
8264 bool promote() {
8265 // Check if there is something to promote.
8266 // Right now, if we do not have anything to combine with,
8267 // we assume the promotion is not profitable.
8268 if (InstsToBePromoted.empty() || !CombineInst)
8269 return false;
8270
8271 // Check cost.
8272 if (!StressStoreExtract && !isProfitableToPromote())
8273 return false;
8274
8275 // Promote.
8276 for (auto &ToBePromoted : InstsToBePromoted)
8277 promoteImpl(ToBePromoted);
8278 InstsToBePromoted.clear();
8279 return true;
8280 }
8281};
8282
8283} // end anonymous namespace
8284
8285void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8286 // At this point, we know that all the operands of ToBePromoted but Def
8287 // can be statically promoted.
8288 // For Def, we need to use its parameter in ToBePromoted:
8289 // b = ToBePromoted ty1 a
8290 // Def = Transition ty1 b to ty2
8291 // Move the transition down.
8292 // 1. Replace all uses of the promoted operation by the transition.
8293 // = ... b => = ... Def.
8294 assert(ToBePromoted->getType() == Transition->getType() &&
8295 "The type of the result of the transition does not match "
8296 "the final type");
8297 ToBePromoted->replaceAllUsesWith(Transition);
8298 // 2. Update the type of the uses.
8299 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8300 Type *TransitionTy = getTransitionType();
8301 ToBePromoted->mutateType(TransitionTy);
8302 // 3. Update all the operands of the promoted operation with promoted
8303 // operands.
8304 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8305 for (Use &U : ToBePromoted->operands()) {
8306 Value *Val = U.get();
8307 Value *NewVal = nullptr;
8308 if (Val == Transition)
8309 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8310 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8311 isa<ConstantFP>(Val)) {
8312 // Use a splat constant if it is not safe to use undef.
8313 NewVal = getConstantVector(
8314 cast<Constant>(Val),
8315 isa<UndefValue>(Val) ||
8316 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8317 } else
8318 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8319 "this?");
8320 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8321 }
8322 Transition->moveAfter(ToBePromoted);
8323 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8324}
8325
8326/// Some targets can do store(extractelement) with one instruction.
8327/// Try to push the extractelement towards the stores when the target
8328/// has this feature and this is profitable.
8329bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8330 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8331 if (!Opts.cgp_store_extract ||
8332 (!Opts.cgp_stress_store_extract &&
8334 Inst->getOperand(1), CombineCost)))
8335 return false;
8336
8337 // At this point we know that Inst is a vector to scalar transition.
8338 // Try to move it down the def-use chain, until:
8339 // - We can combine the transition with its single use
8340 // => we got rid of the transition.
8341 // - We escape the current basic block
8342 // => we would need to check that we are moving it at a cheaper place and
8343 // we do not do that for now.
8344 BasicBlock *Parent = Inst->getParent();
8345 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8346 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost,
8347 Opts.cgp_stress_store_extract);
8348 // If the transition has more than one use, assume this is not going to be
8349 // beneficial.
8350 while (Inst->hasOneUse()) {
8351 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
8352 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8353
8354 if (ToBePromoted->getParent() != Parent) {
8355 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8356 << ToBePromoted->getParent()->getName()
8357 << ") than the transition (" << Parent->getName()
8358 << ").\n");
8359 return false;
8360 }
8361
8362 if (VPH.canCombine(ToBePromoted)) {
8363 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8364 << "will be combined with: " << *ToBePromoted << '\n');
8365 VPH.recordCombineInstruction(ToBePromoted);
8366 bool Changed = VPH.promote();
8367 NumStoreExtractExposed += Changed;
8368 return Changed;
8369 }
8370
8371 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8372 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8373 return false;
8374
8375 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8376
8377 VPH.enqueueForPromotion(ToBePromoted);
8378 Inst = ToBePromoted;
8379 }
8380 return false;
8381}
8382
8383/// For the instruction sequence of store below, F and I values
8384/// are bundled together as an i64 value before being stored into memory.
8385/// Sometimes it is more efficient to generate separate stores for F and I,
8386/// which can remove the bitwise instructions or sink them to colder places.
8387///
8388/// (store (or (zext (bitcast F to i32) to i64),
8389/// (shl (zext I to i64), 32)), addr) -->
8390/// (store F, addr) and (store I, addr+4)
8391///
8392/// Similarly, splitting for other merged store can also be beneficial, like:
8393/// For pair of {i32, i32}, i64 store --> two i32 stores.
8394/// For pair of {i32, i16}, i64 store --> two i32 stores.
8395/// For pair of {i16, i16}, i32 store --> two i16 stores.
8396/// For pair of {i16, i8}, i32 store --> two i16 stores.
8397/// For pair of {i8, i8}, i16 store --> two i8 stores.
8398///
8399/// We allow each target to determine specifically which kind of splitting is
8400/// supported.
8401///
8402/// The store patterns are commonly seen from the simple code snippet below
8403/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8404/// void goo(const std::pair<int, float> &);
8405/// hoo() {
8406/// ...
8407/// goo(std::make_pair(tmp, ftmp));
8408/// ...
8409/// }
8410///
8411/// Although we already have similar splitting in DAG Combine, we duplicate
8412/// it in CodeGenPrepare to catch the case in which pattern is across
8413/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8414/// during code expansion.
8416 const TargetLowering &TLI,
8417 bool ForceSplitStore) {
8418 // Handle simple but common cases only.
8419 Type *StoreType = SI.getValueOperand()->getType();
8420
8421 // The code below assumes shifting a value by <number of bits>,
8422 // whereas scalable vectors would have to be shifted by
8423 // <2log(vscale) + number of bits> in order to store the
8424 // low/high parts. Bailing out for now.
8425 if (StoreType->isScalableTy())
8426 return false;
8427
8428 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8429 DL.getTypeSizeInBits(StoreType) == 0)
8430 return false;
8431
8432 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8433 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8434 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8435 return false;
8436
8437 // Don't split the store if it is volatile or atomic.
8438 if (!SI.isSimple())
8439 return false;
8440
8441 // Match the following patterns:
8442 // (store (or (zext LValue to i64),
8443 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8444 // or
8445 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8446 // (zext LValue to i64),
8447 // Expect both operands of OR and the first operand of SHL have only
8448 // one use.
8449 Value *LValue, *HValue;
8450 if (!match(SI.getValueOperand(),
8453 m_SpecificInt(HalfValBitSize))))))
8454 return false;
8455
8456 // Check LValue and HValue are int with size less or equal than 32.
8457 if (!LValue->getType()->isIntegerTy() ||
8458 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8459 !HValue->getType()->isIntegerTy() ||
8460 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8461 return false;
8462
8463 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8464 // as the input of target query.
8465 auto *LBC = dyn_cast<BitCastInst>(LValue);
8466 auto *HBC = dyn_cast<BitCastInst>(HValue);
8467 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8468 : EVT::getEVT(LValue->getType());
8469 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8470 : EVT::getEVT(HValue->getType());
8471 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8472 return false;
8473
8474 // Start to split store.
8475 IRBuilder<> Builder(&SI);
8476 Builder.disableGEPCanonicalization();
8477
8478 // If LValue/HValue is a bitcast in another BB, create a new one in current
8479 // BB so it may be merged with the splitted stores by dag combiner.
8480 if (LBC && LBC->getParent() != SI.getParent())
8481 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8482 if (HBC && HBC->getParent() != SI.getParent())
8483 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8484
8485 bool IsLE = SI.getDataLayout().isLittleEndian();
8486 auto CreateSplitStore = [&](Value *V, bool Upper) {
8487 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8488 Value *Addr = SI.getPointerOperand();
8489 Align Alignment = SI.getAlign();
8490 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8491 if (IsOffsetStore) {
8492 Addr = Builder.CreateGEP(
8493 SplitStoreType, Addr,
8494 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8495
8496 // When splitting the store in half, naturally one half will retain the
8497 // alignment of the original wider store, regardless of whether it was
8498 // over-aligned or not, while the other will require adjustment.
8499 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8500 }
8501 Builder.CreateAlignedStore(V, Addr, Alignment);
8502 };
8503
8504 CreateSplitStore(LValue, false);
8505 CreateSplitStore(HValue, true);
8506
8507 // Delete the old store.
8508 SI.eraseFromParent();
8509 return true;
8510}
8511
8512// Try unmerging GEPs to reduce liveness interference (register pressure) across
8513// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8514// reducing liveness interference across those edges benefits global register
8515// allocation. Currently handles only certain cases.
8516//
8517// For example, unmerge %GEPI and %UGEPI as below.
8518//
8519// ---------- BEFORE ----------
8520// SrcBlock:
8521// ...
8522// %GEPIOp = ...
8523// ...
8524// %GEPI = gep %GEPIOp, Idx
8525// ...
8526// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8527// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8528// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8529// %UGEPI)
8530//
8531// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8532// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8533// ...
8534//
8535// DstBi:
8536// ...
8537// %UGEPI = gep %GEPIOp, UIdx
8538// ...
8539// ---------------------------
8540//
8541// ---------- AFTER ----------
8542// SrcBlock:
8543// ... (same as above)
8544// (* %GEPI is still alive on the indirectbr edges)
8545// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8546// unmerging)
8547// ...
8548//
8549// DstBi:
8550// ...
8551// %UGEPI = gep %GEPI, (UIdx-Idx)
8552// ...
8553// ---------------------------
8554//
8555// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8556// no longer alive on them.
8557//
8558// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8559// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8560// not to disable further simplications and optimizations as a result of GEP
8561// merging.
8562//
8563// Note this unmerging may increase the length of the data flow critical path
8564// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8565// between the register pressure and the length of data-flow critical
8566// path. Restricting this to the uncommon IndirectBr case would minimize the
8567// impact of potentially longer critical path, if any, and the impact on compile
8568// time.
8570 const TargetTransformInfo *TTI) {
8571 const DataLayout &DL = GEPI->getDataLayout();
8572 BasicBlock *SrcBlock = GEPI->getParent();
8573 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8574 // (non-IndirectBr) cases exit early here.
8575 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8576 return false;
8577 // Check that GEPI is a constant ptradd with canonical index type.
8578 Instruction *GEPIOp;
8579 ConstantInt *GEPIIdx;
8580 if (!match(GEPI, m_PtrAdd(DL, m_Instruction(GEPIOp), m_ConstantInt(GEPIIdx))))
8581 return false;
8582 // Check that GEPI is a cheap one.
8583 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8586 return false;
8587 // Check that GEPIOp is also defined in SrcBlock.
8588 if (GEPIOp->getParent() != SrcBlock)
8589 return false;
8590 // Check that GEP is used outside the block, meaning it's alive on the
8591 // IndirectBr edge(s).
8592 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8593 if (auto *I = dyn_cast<Instruction>(Usr)) {
8594 if (I->getParent() != SrcBlock) {
8595 return true;
8596 }
8597 }
8598 return false;
8599 }))
8600 return false;
8601 // The second elements of the GEP chains to be unmerged.
8602 std::vector<GetElementPtrInst *> UGEPIs;
8603 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8604 // on IndirectBr edges.
8605 for (User *Usr : GEPIOp->users()) {
8606 if (Usr == GEPI)
8607 continue;
8608 // Check if Usr is an Instruction. If not, give up.
8609 if (!isa<Instruction>(Usr))
8610 return false;
8611 auto *UI = cast<Instruction>(Usr);
8612 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8613 if (UI->getParent() == SrcBlock)
8614 continue;
8615 // Check if Usr is also a constant ptradd with GEPIOp as pointer operand.
8616 // If so, record it in the vector. If not, give up.
8617 ConstantInt *UGEPIIdx;
8618 if (!match(Usr, m_PtrAdd(DL, m_Specific(GEPIOp), m_ConstantInt(UGEPIIdx))))
8619 return false;
8620 if (GEPIIdx->getType() != UGEPIIdx->getType())
8621 return false;
8622 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8625 return false;
8626 UGEPIs.push_back(cast<GetElementPtrInst>(Usr));
8627 }
8628 if (UGEPIs.size() == 0)
8629 return false;
8630 // Check the materializing cost of (Uidx-Idx).
8631 for (GetElementPtrInst *UGEPI : UGEPIs) {
8632 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8633 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8635 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8636 if (ImmCost > TargetTransformInfo::TCC_Basic)
8637 return false;
8638 }
8639 // Now unmerge between GEPI and UGEPIs.
8640 for (GetElementPtrInst *UGEPI : UGEPIs) {
8641 UGEPI->setOperand(0, GEPI);
8642 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8643 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8644 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8645 UGEPI->setOperand(1, NewUGEPIIdx);
8646
8647 auto SourceFlags = GEPI->getNoWrapFlags();
8648 // Intersect flags to avoid UB in updated GEP.
8649 auto TargetFlags =
8650 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8651 // If UGEPI now has a negative index, drop the nuw flag.
8652 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8653 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8654 UGEPI->setNoWrapFlags(TargetFlags);
8655 }
8656 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8657 // alive on IndirectBr edges).
8658 assert(llvm::none_of(GEPIOp->users(),
8659 [&](User *Usr) {
8660 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8661 }) &&
8662 "GEPIOp is used outside SrcBlock");
8663 return true;
8664}
8665
8666static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8668 bool IsHugeFunc) {
8669 // Try and convert
8670 // %c = icmp ult %x, 8
8671 // br %c, bla, blb
8672 // %tc = lshr %x, 3
8673 // to
8674 // %tc = lshr %x, 3
8675 // %c = icmp eq %tc, 0
8676 // br %c, bla, blb
8677 // Creating the cmp to zero can be better for the backend, especially if the
8678 // lshr produces flags that can be used automatically.
8679 if (!TLI.preferZeroCompareBranch())
8680 return false;
8681
8682 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8683 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8684 return false;
8685
8686 Value *X = Cmp->getOperand(0);
8687 if (!X->hasUseList())
8688 return false;
8689
8690 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8691
8692 for (auto *U : X->users()) {
8694 // A quick dominance check
8695 if (!UI ||
8696 (UI->getParent() != Branch->getParent() &&
8697 UI->getParent() != Branch->getSuccessor(0) &&
8698 UI->getParent() != Branch->getSuccessor(1)) ||
8699 (UI->getParent() != Branch->getParent() &&
8700 !UI->getParent()->getSinglePredecessor()))
8701 continue;
8702
8703 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8704 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8705 IRBuilder<> Builder(Branch);
8706 if (UI->getParent() != Branch->getParent())
8707 UI->moveBefore(Branch->getIterator());
8709 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8710 ConstantInt::get(UI->getType(), 0));
8711 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8712 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8713 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8714 return true;
8715 }
8716 if (Cmp->isEquality() &&
8717 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8718 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8719 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8720 IRBuilder<> Builder(Branch);
8721 if (UI->getParent() != Branch->getParent())
8722 UI->moveBefore(Branch->getIterator());
8724 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8725 ConstantInt::get(UI->getType(), 0));
8726 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8727 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8728 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8729 return true;
8730 }
8731 }
8732 return false;
8733}
8734
8735// Performs very basic loop strength reduction to vector values with a known
8736// evolution from one iteration to the next that are used as the value operand
8737// for a store.
8738// A simple example to illustrate:
8739//
8740// %vec.ind = phi <vscale x 2 x i64> [ %start, %vector.ph ],
8741// [ %vec.ind.next, %vector.body ]
8742// %data.gep = getelementptr inbounds nuw [72 x i8], ptr %datap,
8743// <vscale x 2 x i64> %vec.ind
8744// %addr.gep = getelementptr inbounds nuw [8 x i8], ptr %addrp, i64 %index
8745// store <vscale x 2 x ptr> %data.gep, ptr %addr.gep, align 8
8746// %vec.ind.next = add nuw nsw <vscale x 2 x i64> %vec.ind, %elt.cnt.splat
8747//
8748// We want to change this to:
8749// vector.ph:
8750// %base = gep i8, %datap, (<stepvector> * 72)
8751// %stride = splat(elementcount) * 72
8752//
8753// vector.body:
8754// %vec.lsr.phi = phi <vscale x 2 x ptr> [ %base, %vector.ph ],
8755// [ %vec.lsr.next, %vector.body ]
8756// %addr.gep = gep inbounds nuw [8 x i8], ptr %addrp, i64 %index
8757// store <vscale x 2 x ptr> %vec.lsr.phi, ptr %addr.gep, align 8
8758// %vec.lsr.next = gep i8, %vec.lsr.phi, %stride
8759//
8760// Doing so will remove a multiply from the loop, and leave the update as just
8761// an add.
8762//
8764 // We're only interested in header phis in innermost loops.
8765 // We want a loop with an identifiable preheader and single latch.
8766 Loop *L = LI->getLoopFor(Phi->getParent());
8767 if (!L || !L->isInnermost())
8768 return false;
8769
8770 BasicBlock *Header = L->getHeader();
8771 BasicBlock *PreHeader = L->getLoopPreheader();
8772 BasicBlock *Latch = L->getLoopLatch();
8773 if (!PreHeader || !Latch || Phi->getParent() != Header ||
8774 Phi->getNumIncomingValues() != 2)
8775 return false;
8776
8777 // Check the progression of the phi.
8778 Value *Start = Phi->getIncomingValueForBlock(PreHeader);
8779 Value *Step = Phi->getIncomingValueForBlock(Latch);
8780
8781 // Check that the elements are integers equal in size to pointers.
8782 DataLayout DL = Phi->getFunction()->getDataLayout();
8783 VectorType *VTy = dyn_cast<VectorType>(Start->getType());
8784 if (!VTy)
8785 return false;
8786 Type *ITy = VTy->getElementType();
8787 if (DL.getTypeStoreSize(ITy) != DL.getPointerSize())
8788 return false;
8789
8790 // TODO: Handle offsets from stepvector.
8792 return false;
8793
8794 Value *LoopStride = nullptr;
8795 if (!match(Step, m_OneUse(m_c_Add(m_Specific(Phi), m_Value(LoopStride)))))
8796 return false;
8797
8798 // Make sure the loop stride matches the pointer stride.
8799 auto EltCnt = cast<VectorType>(Phi->getType())->getElementCount();
8800 const APInt *ShiftAmt = nullptr;
8801 Value *PtrStride = nullptr;
8802 if (!match(
8803 LoopStride,
8804 m_Splat(m_Value(PtrStride, m_Shl(m_VScale(), m_APInt(ShiftAmt))))) ||
8805 (1ULL << ShiftAmt->getZExtValue()) != EltCnt.getKnownMinValue())
8806 return false;
8807
8808 // Make sure the stride isn't defined inside the loop, so we don't have to
8809 // worry about dominance.
8810 if (L->contains(cast<Instruction>(PtrStride)))
8811 return false;
8812
8813 // For the simplest case, we're only interested if the phi has two users;
8814 // The Step forming the incoming value for the backedge, and a GEP.
8815 GetElementPtrInst *GEP = nullptr;
8816 Value *Base = nullptr;
8817 for (User *U : Phi->users()) {
8818 // Skip over the step, handled above.
8819 if (Step == U)
8820 continue;
8821
8822 // If we've already found a GEP, bail out.
8823 // TODO: Support multiple GEPs.
8824 if (GEP)
8825 return false;
8826
8827 // We're only interested in single index GEPs
8829 if (!GEP || GEP->getNumOperands() != 2)
8830 return false;
8831
8832 // Reject if the base isn't loop invariant.
8833 Base = GEP->getOperand(0);
8834 if (!L->isLoopInvariant(Base))
8835 return false;
8836 }
8837
8838 // Make sure we found a GEP.
8839 if (!GEP)
8840 return false;
8841
8842 // Check that the indexed size is also the same.
8843 unsigned Size = DL.getTypeStoreSize(GEP->getResultElementType());
8844
8845 // Multiply the start by the size of the struct, and add the base pointer.
8846 Type *Int8Ty = IntegerType::getInt8Ty(ITy->getContext());
8847 IRBuilder<> Builder(PreHeader->getTerminator());
8848 Value *StructSize = ConstantInt::get(ITy, Size);
8849 Value *SizeSplat =
8850 Builder.CreateVectorSplat(VTy->getElementCount(), StructSize);
8851 Value *NewStart = Builder.CreateMul(Start, SizeSplat);
8852 NewStart = Builder.CreateGEP(Int8Ty, Base, NewStart);
8853
8854 // Create a new step based on the total size of all struct addresses per
8855 // iteration.
8856 Value *StructStride = Builder.CreateMul(PtrStride, StructSize);
8857 StructStride =
8858 Builder.CreateVectorSplat(VTy->getElementCount(), StructStride);
8859
8860 Builder.SetInsertPoint(Phi);
8861 PHINode *NewPhi = Builder.CreatePHI(GEP->getType(), 2, "vec.lsr.phi");
8862 Builder.SetInsertPoint(cast<Instruction>(Step));
8863 StructStride = Builder.CreateGEP(Int8Ty, NewPhi, StructStride);
8864
8865 // Set up the new PHI.
8866 NewPhi->addIncoming(NewStart, PreHeader);
8867 NewPhi->addIncoming(StructStride, Latch);
8868
8869 // Replace the GEP with the new phi.
8870 Builder.SetInsertPoint(GEP);
8871 GEP->replaceAllUsesWith(NewPhi);
8872
8873 // Remove old phi, gep, and step.
8874 Phi->replaceAllUsesWith(llvm::PoisonValue::get(Phi->getType()));
8876
8877 return true;
8878}
8879
8880bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8881 bool AnyChange = false;
8882 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8883
8884 // Bail out if we inserted the instruction to prevent optimizations from
8885 // stepping on each other's toes.
8886 if (InsertedInsts.count(I))
8887 return AnyChange;
8888
8889 // TODO: Move into the switch on opcode below here.
8890 if (PHINode *P = dyn_cast<PHINode>(I)) {
8891 // It is possible for very late stage optimizations (such as SimplifyCFG)
8892 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8893 // trivial PHI, go ahead and zap it here.
8894 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8895 LargeOffsetGEPMap.erase(P);
8896 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8897 P->eraseFromParent();
8898 ++NumPHIsElim;
8899 return true;
8900 }
8901
8902 // Look for simple GEPs on scalable vectors used as data which may
8903 // introduce unnecessary multiplies in the loop.
8904 // TODO: Support fixed vectors too.
8905 if (P->getType()->isScalableTy())
8906 AnyChange |= strengthReduceVectorPhiUsers(P, LI);
8907 return AnyChange;
8908 }
8909
8910 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8911 // If the source of the cast is a constant, then this should have
8912 // already been constant folded. The only reason NOT to constant fold
8913 // it is if something (e.g. LSR) was careful to place the constant
8914 // evaluation in a block other than then one that uses it (e.g. to hoist
8915 // the address of globals out of a loop). If this is the case, we don't
8916 // want to forward-subst the cast.
8917 if (auto *BCI = dyn_cast<BitCastInst>(CI)) {
8918 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8919 // and prevent register splitting.
8920 if (optimizeBitCast(BCI, *TLI, *DL)) {
8921 return true;
8922 }
8923 }
8924
8925 if (isa<Constant>(CI->getOperand(0)))
8926 return AnyChange;
8927
8928 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8929 return true;
8930
8932 isa<TruncInst>(I)) &&
8934 I, LI->getLoopFor(I->getParent()), *TTI))
8935 return true;
8936
8937 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8938 /// Sink a zext or sext into its user blocks if the target type doesn't
8939 /// fit in one register
8940 if (TLI->getTypeAction(CI->getContext(),
8941 TLI->getValueType(*DL, CI->getType())) ==
8942 TargetLowering::TypeExpandInteger) {
8943 return SinkCast(CI);
8944 } else {
8946 I, LI->getLoopFor(I->getParent()), *TTI))
8947 return true;
8948
8949 bool MadeChange = optimizeExt(I);
8950 return MadeChange | optimizeExtUses(I);
8951 }
8952 }
8953 return AnyChange;
8954 }
8955
8956 if (auto *Cmp = dyn_cast<CmpInst>(I))
8957 if (optimizeCmp(Cmp, ModifiedDT))
8958 return true;
8959
8960 if (match(I, m_URem(m_Value(), m_Value())))
8961 if (optimizeURem(I))
8962 return true;
8963
8964 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8965 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8966 bool Modified = optimizeLoadExt(LI);
8967 unsigned AS = LI->getPointerAddressSpace();
8968 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
8969 return Modified;
8970 }
8971
8972 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
8973 if (splitMergedValStore(*SI, *DL, *TLI, Opts.cgp_force_split_store))
8974 return true;
8975 bool Modified = tryToSinkFreeOperands(I);
8976 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8977 unsigned AS = SI->getPointerAddressSpace();
8978 Modified |= optimizeMemoryInst(I, SI->getOperand(1),
8979 SI->getOperand(0)->getType(), AS);
8980 return Modified;
8981 }
8982
8983 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
8984 unsigned AS = RMW->getPointerAddressSpace();
8985 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
8986 }
8987
8988 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
8989 unsigned AS = CmpX->getPointerAddressSpace();
8990 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
8991 CmpX->getCompareOperand()->getType(), AS);
8992 }
8993
8994 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
8995
8996 if (BinOp && BinOp->getOpcode() == Instruction::And &&
8997 Opts.cgp_andcmp_sinking &&
8998 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
8999 return true;
9000
9001 // TODO: Move this into the switch on opcode - it handles shifts already.
9002 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
9003 BinOp->getOpcode() == Instruction::LShr)) {
9004 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
9005 if (CI && TLI->hasExtractBitsInsn())
9006 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
9007 return true;
9008 }
9009
9010 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
9011 if (GEPI->hasAllZeroIndices()) {
9012 /// The GEP operand must be a pointer, so must its result -> BitCast
9013 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
9014 GEPI->getName(), GEPI->getIterator());
9015 NC->setDebugLoc(GEPI->getDebugLoc());
9016 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
9018 GEPI, TLInfo, nullptr,
9019 [&](Value *V) { removeAllAssertingVHReferences(V); });
9020 ++NumGEPsElim;
9021 optimizeInst(NC, ModifiedDT);
9022 return true;
9023 }
9025 return true;
9026 }
9027 }
9028
9029 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
9030 // freeze(icmp a, const)) -> icmp (freeze a), const
9031 // This helps generate efficient conditional jumps.
9032 CmpInst *CmpI = dyn_cast<CmpInst>(FI->getOperand(0));
9033 if (CmpI && CmpI->hasOneUse()) {
9034 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
9035 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
9037 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
9039 if (Const0 || Const1) {
9040 if (!Const0 || !Const1) {
9041 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9042 F->takeName(FI);
9043 CmpI->setOperand(Const0 ? 1 : 0, F);
9044 }
9046 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
9047 FI->eraseFromParent();
9048 return true;
9049 }
9050 }
9051 return AnyChange;
9052 }
9053
9054 // Try to fold some cross-lane vector operations if in a loop.
9055 if (I->getType()->isVectorTy() &&
9056 TLI->optimizeVectorCrossLaneOperation(I, LI->getLoopFor(I->getParent())))
9057 return true;
9058
9059 if (tryToSinkFreeOperands(I))
9060 return true;
9061
9062 switch (I->getOpcode()) {
9063 case Instruction::Shl:
9064 case Instruction::LShr:
9065 case Instruction::AShr:
9066 return optimizeShiftInst(cast<BinaryOperator>(I));
9067 case Instruction::Call:
9068 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
9069 case Instruction::Select:
9070 return optimizeSelectInst(cast<SelectInst>(I));
9071 case Instruction::ShuffleVector:
9072 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
9073 case Instruction::Switch:
9074 return optimizeSwitchInst(cast<SwitchInst>(I));
9075 case Instruction::ExtractElement:
9076 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
9077 case Instruction::CondBr:
9078 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
9079 }
9080
9081 return AnyChange;
9082}
9083
9084/// Given an OR instruction, check to see if this is a bitreverse
9085/// idiom. If so, insert the new intrinsic and return true.
9086bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9087 if (!I.getType()->isIntegerTy() ||
9089 TLI->getValueType(*DL, I.getType(), true)))
9090 return false;
9091
9092 SmallVector<Instruction *, 4> Insts;
9093 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9094 return false;
9095 Instruction *LastInst = Insts.back();
9096 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9098 &I, TLInfo, nullptr,
9099 [&](Value *V) { removeAllAssertingVHReferences(V); });
9100 return true;
9101}
9102
9103// In this pass we look for GEP and cast instructions that are used
9104// across basic blocks and rewrite them to improve basic-block-at-a-time
9105// selection.
9106bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9107 SunkAddrs.clear();
9108 bool MadeChange = false;
9109
9110 do {
9111 CurInstIterator = BB.begin();
9112 ModifiedDT = ModifyDT::NotModifyDT;
9113 while (CurInstIterator != BB.end()) {
9114 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9115 if (ModifiedDT != ModifyDT::NotModifyDT) {
9116 // For huge function we tend to quickly go though the inner optmization
9117 // opportunities in the BB. So we go back to the BB head to re-optimize
9118 // each instruction instead of go back to the function head.
9119 if (IsHugeFunc)
9120 break;
9121 return true;
9122 }
9123 }
9124 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9125
9126 bool MadeBitReverse = true;
9127 while (MadeBitReverse) {
9128 MadeBitReverse = false;
9129 for (auto &I : reverse(BB)) {
9130 if (makeBitReverse(I)) {
9131 MadeBitReverse = MadeChange = true;
9132 break;
9133 }
9134 }
9135 }
9136 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9137
9138 return MadeChange;
9139}
9140
9141bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9142 bool AnyChange = false;
9143 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9144 AnyChange |= fixupDbgVariableRecord(DVR);
9145 return AnyChange;
9146}
9147
9148// FIXME: should updating debug-info really cause the "changed" flag to fire,
9149// which can cause a function to be reprocessed?
9150bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9151 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9152 DVR.Type != DbgVariableRecord::LocationType::Assign)
9153 return false;
9154
9155 // Does this DbgVariableRecord refer to a sunk address calculation?
9156 bool AnyChange = false;
9157 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9158 DVR.location_ops().end());
9159 for (Value *Location : LocationOps) {
9160 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9161 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9162 if (SunkAddr) {
9163 // Point dbg.value at locally computed address, which should give the best
9164 // opportunity to be accurately lowered. This update may change the type
9165 // of pointer being referred to; however this makes no difference to
9166 // debugging information, and we can't generate bitcasts that may affect
9167 // codegen.
9168 DVR.replaceVariableLocationOp(Location, SunkAddr);
9169 AnyChange = true;
9170 }
9171 }
9172 return AnyChange;
9173}
9174
9176 DVR->removeFromParent();
9177 BasicBlock *VIBB = VI->getParent();
9178 if (isa<PHINode>(VI))
9179 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9180 else
9181 VIBB->insertDbgRecordAfter(DVR, &*VI);
9182}
9183
9184// A llvm.dbg.value may be using a value before its definition, due to
9185// optimizations in this pass and others. Scan for such dbg.values, and rescue
9186// them by moving the dbg.value to immediately after the value definition.
9187// FIXME: Ideally this should never be necessary, and this has the potential
9188// to re-order dbg.value intrinsics.
9189bool CodeGenPrepare::placeDbgValues(Function &F) {
9190 bool MadeChange = false;
9191 DominatorTree &DT = getDT();
9192
9193 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9194 SmallVector<Instruction *, 4> VIs;
9195 for (Value *V : DbgItem->location_ops())
9196 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9197 VIs.push_back(VI);
9198
9199 // This item may depend on multiple instructions, complicating any
9200 // potential sink. This block takes the defensive approach, opting to
9201 // "undef" the item if it has more than one instruction and any of them do
9202 // not dominate iem.
9203 for (Instruction *VI : VIs) {
9204 if (VI->isTerminator())
9205 continue;
9206
9207 // If VI is a phi in a block with an EHPad terminator, we can't insert
9208 // after it.
9209 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9210 continue;
9211
9212 // If the defining instruction dominates the dbg.value, we do not need
9213 // to move the dbg.value.
9214 if (DT.dominates(VI, Position))
9215 continue;
9216
9217 // If we depend on multiple instructions and any of them doesn't
9218 // dominate this DVI, we probably can't salvage it: moving it to
9219 // after any of the instructions could cause us to lose the others.
9220 if (VIs.size() > 1) {
9221 LLVM_DEBUG(
9222 dbgs()
9223 << "Unable to find valid location for Debug Value, undefing:\n"
9224 << *DbgItem);
9225 DbgItem->setKillLocation();
9226 break;
9227 }
9228
9229 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9230 << *DbgItem << ' ' << *VI);
9231 DbgInserterHelper(DbgItem, VI->getIterator());
9232 MadeChange = true;
9233 ++NumDbgValueMoved;
9234 }
9235 };
9236
9237 for (BasicBlock &BB : F) {
9238 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9239 // Process any DbgVariableRecord records attached to this
9240 // instruction.
9241 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9242 filterDbgVars(Insn.getDbgRecordRange()))) {
9243 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9244 continue;
9245 DbgProcessor(&DVR, &Insn);
9246 }
9247 }
9248 }
9249
9250 return MadeChange;
9251}
9252
9253// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9254// probes can be chained dependencies of other regular DAG nodes and block DAG
9255// combine optimizations.
9256bool CodeGenPrepare::placePseudoProbes(Function &F) {
9257 bool MadeChange = false;
9258 for (auto &Block : F) {
9259 // Move the rest probes to the beginning of the block.
9260 auto FirstInst = Block.getFirstInsertionPt();
9261 while (FirstInst != Block.end() && isa<PseudoProbeInst>(FirstInst))
9262 ++FirstInst;
9263 BasicBlock::iterator I(FirstInst);
9264 I++;
9265 while (I != Block.end()) {
9266 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9267 II->moveBefore(FirstInst);
9268 MadeChange = true;
9269 }
9270 }
9271 }
9272 return MadeChange;
9273}
9274
9275/// Some targets prefer to split a conditional branch like:
9276/// \code
9277/// %0 = icmp ne i32 %a, 0
9278/// %1 = icmp ne i32 %b, 0
9279/// %or.cond = or i1 %0, %1
9280/// br i1 %or.cond, label %TrueBB, label %FalseBB
9281/// \endcode
9282/// into multiple branch instructions like:
9283/// \code
9284/// bb1:
9285/// %0 = icmp ne i32 %a, 0
9286/// br i1 %0, label %TrueBB, label %bb2
9287/// bb2:
9288/// %1 = icmp ne i32 %b, 0
9289/// br i1 %1, label %TrueBB, label %FalseBB
9290/// \endcode
9291/// This usually allows instruction selection to do even further optimizations
9292/// and combine the compare with the branch instruction. Currently this is
9293/// applied for targets which have "cheap" jump instructions.
9294///
9295/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9296///
9297bool CodeGenPrepare::splitBranchCondition(Function &F) {
9299 return false;
9300
9301 bool MadeChange = false;
9302 for (auto &BB : F) {
9303 // Does this BB end with the following?
9304 // %cond1 = icmp|fcmp|binary instruction ...
9305 // %cond2 = icmp|fcmp|binary instruction ...
9306 // %cond.or = or|and i1 %cond1, cond2
9307 // br i1 %cond.or label %dest1, label %dest2"
9308 Instruction *LogicOp;
9309 BasicBlock *TBB, *FBB;
9310 if (!match(BB.getTerminator(),
9311 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9312 continue;
9313
9314 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9315 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9316 continue;
9317
9318 // The merging of mostly empty BB can cause a degenerate branch.
9319 if (TBB == FBB)
9320 continue;
9321
9322 unsigned Opc;
9323 Value *Cond1, *Cond2;
9324 if (match(LogicOp,
9325 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9326 Opc = Instruction::And;
9327 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9328 m_OneUse(m_Value(Cond2)))))
9329 Opc = Instruction::Or;
9330 else
9331 continue;
9332
9333 auto IsGoodCond = [](Value *Cond) {
9334 return match(
9335 Cond,
9337 m_LogicalOr(m_Value(), m_Value()))));
9338 };
9339 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9340 continue;
9341
9342 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9343
9344 // Create a new BB.
9345 auto *TmpBB =
9346 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9347 BB.getParent(), BB.getNextNode());
9348 if (IsHugeFunc)
9349 FreshBBs.insert(TmpBB);
9350
9351 // Update original basic block by using the first condition directly by the
9352 // branch instruction and removing the no longer needed and/or instruction.
9353 Br1->setCondition(Cond1);
9354 LogicOp->eraseFromParent();
9355
9356 // Depending on the condition we have to either replace the true or the
9357 // false successor of the original branch instruction.
9358 if (Opc == Instruction::And)
9359 Br1->setSuccessor(0, TmpBB);
9360 else
9361 Br1->setSuccessor(1, TmpBB);
9362
9363 // Fill in the new basic block.
9364 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9365 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9366 I->removeFromParent();
9367 I->insertBefore(Br2->getIterator());
9368 }
9369
9370 // Update PHI nodes in both successors. The original BB needs to be
9371 // replaced in one successor's PHI nodes, because the branch comes now from
9372 // the newly generated BB (NewBB). In the other successor we need to add one
9373 // incoming edge to the PHI nodes, because both branch instructions target
9374 // now the same successor. Depending on the original branch condition
9375 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9376 // we perform the correct update for the PHI nodes.
9377 // This doesn't change the successor order of the just created branch
9378 // instruction (or any other instruction).
9379 if (Opc == Instruction::Or)
9380 std::swap(TBB, FBB);
9381
9382 // Replace the old BB with the new BB.
9383 TBB->replacePhiUsesWith(&BB, TmpBB);
9384
9385 // Add another incoming edge from the new BB.
9386 for (PHINode &PN : FBB->phis()) {
9387 auto *Val = PN.getIncomingValueForBlock(&BB);
9388 PN.addIncoming(Val, TmpBB);
9389 }
9390
9391 if (Loop *L = LI->getLoopFor(&BB))
9392 L->addBasicBlockToLoop(TmpBB, *LI);
9393
9394 // The edge we need to delete starts at BB and ends at whatever TBB ends
9395 // up pointing to.
9396 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9397 {DominatorTree::Insert, TmpBB, TBB},
9398 {DominatorTree::Insert, TmpBB, FBB},
9399 {DominatorTree::Delete, &BB, TBB}});
9400
9401 // Update the branch weights (from SelectionDAGBuilder::
9402 // FindMergedConditions).
9403 if (Opc == Instruction::Or) {
9404 // Codegen X | Y as:
9405 // BB1:
9406 // jmp_if_X TBB
9407 // jmp TmpBB
9408 // TmpBB:
9409 // jmp_if_Y TBB
9410 // jmp FBB
9411 //
9412
9413 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9414 // The requirement is that
9415 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9416 // = TrueProb for original BB.
9417 // Assuming the original weights are A and B, one choice is to set BB1's
9418 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9419 // assumes that
9420 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9421 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9422 // TmpBB, but the math is more complicated.
9423 uint64_t TrueWeight, FalseWeight;
9424 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9425 uint64_t NewTrueWeight = TrueWeight;
9426 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9427 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9428 hasBranchWeightOrigin(*Br1));
9429
9430 NewTrueWeight = TrueWeight;
9431 NewFalseWeight = 2 * FalseWeight;
9432 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9433 /*IsExpected=*/false);
9434 }
9435 } else {
9436 // Codegen X & Y as:
9437 // BB1:
9438 // jmp_if_X TmpBB
9439 // jmp FBB
9440 // TmpBB:
9441 // jmp_if_Y TBB
9442 // jmp FBB
9443 //
9444 // This requires creation of TmpBB after CurBB.
9445
9446 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9447 // The requirement is that
9448 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9449 // = FalseProb for original BB.
9450 // Assuming the original weights are A and B, one choice is to set BB1's
9451 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9452 // assumes that
9453 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9454 uint64_t TrueWeight, FalseWeight;
9455 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9456 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9457 uint64_t NewFalseWeight = FalseWeight;
9458 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9459 /*IsExpected=*/false);
9460
9461 NewTrueWeight = 2 * TrueWeight;
9462 NewFalseWeight = FalseWeight;
9463 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9464 /*IsExpected=*/false);
9465 }
9466 }
9467
9468 MadeChange = true;
9469
9470 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9471 TmpBB->dump());
9472 }
9473 return MadeChange;
9474}
#define Success
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
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)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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 foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
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 isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut)
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 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 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.
Definition Compiler.h:690
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)
#define DEBUG_TYPE
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
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.
iv users
Definition IVUsers.cpp:48
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
Definition LICM.cpp:1188
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PointerIntPair class.
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
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
This file contains some templates that are useful if you are working with the STL at all.
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)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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.
This pass exposes codegen information to IR-level passes.
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)
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
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),...
Definition ArrayRef.h:40
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.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
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.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
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
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
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...
Definition BasicBlock.h:170
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.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
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.
Definition InstrTypes.h:512
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.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
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.
Definition InstrTypes.h:828
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.
Definition Constants.h:87
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.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
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 ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
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.
Definition Constant.h:44
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.
Definition DataLayout.h:64
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)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
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 extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const BasicBlock & getEntryBlock() const
Definition Function.h:794
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.
Definition Globals.cpp:422
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.
Definition Globals.cpp:640
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.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2987
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.
user_iterator user_end()
bool isShift() const
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.
Definition LoopInfo.h:598
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.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static MVT getIntegerVT(unsigned BitWidth)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:211
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.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
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.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
VectorType * getType() const
Overload to return most specific vector type.
size_type size() const
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.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
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 resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
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...
TargetOptions Options
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
virtual bool addrSinkUsingGEPs() const
Sink addresses into blocks using GEP instructions rather than pointer casts and arithmetic.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops, const LoopInfo *LI=nullptr) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
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.
Definition Use.h:35
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition Value.cpp:234
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.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isNonZero() const
Definition TypeSize.h:156
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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_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)
Definition MCAsmInfo.h:51
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:550
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
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.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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.
Definition STLExtras.h:1685
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
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...
Definition Local.cpp:133
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.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
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...
Definition Utils.cpp:1837
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)
Definition APInt.h:2139
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.
Definition STLExtras.h:2224
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...
Definition STLExtras.h:649
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,...
Definition MathExtras.h:703
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)
Definition STLExtras.h:2150
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...
Definition STLExtras.h:2189
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
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)
Definition STLExtras.h:408
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3850
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
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.
Definition STLExtras.h:1415
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...
Definition Analysis.cpp:214
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:54
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...
Definition Casting.h:547
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.
Definition ModRef.h:74
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...
Definition Analysis.cpp:704
TargetTransformInfo TTI
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.
@ Add
Sum 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...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
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.
Definition Casting.h:559
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...
Definition STLExtras.h:2208
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
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.
Definition Local.h:240
constexpr bool valueOr(BoolOrDefault X, bool Default)
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...
Definition MathExtras.h:777
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
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.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
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.
Definition ValueTypes.h:354
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:286
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
This contains information for each constraint that we are lowering.