LLVM 17.0.0git
InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
1//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
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 file implements the visit functions for load, store and alloca.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/MapVector.h"
16#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/Loads.h"
19#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/LLVMContext.h"
26using namespace llvm;
27using namespace PatternMatch;
28
29#define DEBUG_TYPE "instcombine"
30
31STATISTIC(NumDeadStore, "Number of dead stores eliminated");
32STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
33
35 "instcombine-max-copied-from-constant-users", cl::init(300),
36 cl::desc("Maximum users to visit in copy from constant transform"),
38
39/// isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived)
40/// pointer to an alloca. Ignore any reads of the pointer, return false if we
41/// see any stores or other unknown uses. If we see pointer arithmetic, keep
42/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
43/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
44/// the alloca, and if the source pointer is a pointer to a constant memory
45/// location, we can optimize this.
46static bool
48 MemTransferInst *&TheCopy,
50 // We track lifetime intrinsics as we encounter them. If we decide to go
51 // ahead and replace the value with the memory location, this lets the caller
52 // quickly eliminate the markers.
53
54 using ValueAndIsOffset = PointerIntPair<Value *, 1, bool>;
57 Worklist.emplace_back(V, false);
58 while (!Worklist.empty()) {
59 ValueAndIsOffset Elem = Worklist.pop_back_val();
60 if (!Visited.insert(Elem).second)
61 continue;
62 if (Visited.size() > MaxCopiedFromConstantUsers)
63 return false;
64
65 const auto [Value, IsOffset] = Elem;
66 for (auto &U : Value->uses()) {
67 auto *I = cast<Instruction>(U.getUser());
68
69 if (auto *LI = dyn_cast<LoadInst>(I)) {
70 // Ignore non-volatile loads, they are always ok.
71 if (!LI->isSimple()) return false;
72 continue;
73 }
74
75 if (isa<PHINode, SelectInst>(I)) {
76 // We set IsOffset=true, to forbid the memcpy from occurring after the
77 // phi: If one of the phi operands is not based on the alloca, we
78 // would incorrectly omit a write.
79 Worklist.emplace_back(I, true);
80 continue;
81 }
82 if (isa<BitCastInst, AddrSpaceCastInst>(I)) {
83 // If uses of the bitcast are ok, we are ok.
84 Worklist.emplace_back(I, IsOffset);
85 continue;
86 }
87 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
88 // If the GEP has all zero indices, it doesn't offset the pointer. If it
89 // doesn't, it does.
90 Worklist.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
91 continue;
92 }
93
94 if (auto *Call = dyn_cast<CallBase>(I)) {
95 // If this is the function being called then we treat it like a load and
96 // ignore it.
97 if (Call->isCallee(&U))
98 continue;
99
100 unsigned DataOpNo = Call->getDataOperandNo(&U);
101 bool IsArgOperand = Call->isArgOperand(&U);
102
103 // Inalloca arguments are clobbered by the call.
104 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
105 return false;
106
107 // If this call site doesn't modify the memory, then we know it is just
108 // a load (but one that potentially returns the value itself), so we can
109 // ignore it if we know that the value isn't captured.
110 bool NoCapture = Call->doesNotCapture(DataOpNo);
111 if ((Call->onlyReadsMemory() && (Call->use_empty() || NoCapture)) ||
112 (Call->onlyReadsMemory(DataOpNo) && NoCapture))
113 continue;
114
115 // If this is being passed as a byval argument, the caller is making a
116 // copy, so it is only a read of the alloca.
117 if (IsArgOperand && Call->isByValArgument(DataOpNo))
118 continue;
119 }
120
121 // Lifetime intrinsics can be handled by the caller.
122 if (I->isLifetimeStartOrEnd()) {
123 assert(I->use_empty() && "Lifetime markers have no result to use!");
124 ToDelete.push_back(I);
125 continue;
126 }
127
128 // If this is isn't our memcpy/memmove, reject it as something we can't
129 // handle.
130 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
131 if (!MI)
132 return false;
133
134 // If the transfer is volatile, reject it.
135 if (MI->isVolatile())
136 return false;
137
138 // If the transfer is using the alloca as a source of the transfer, then
139 // ignore it since it is a load (unless the transfer is volatile).
140 if (U.getOperandNo() == 1)
141 continue;
142
143 // If we already have seen a copy, reject the second one.
144 if (TheCopy) return false;
145
146 // If the pointer has been offset from the start of the alloca, we can't
147 // safely handle this.
148 if (IsOffset) return false;
149
150 // If the memintrinsic isn't using the alloca as the dest, reject it.
151 if (U.getOperandNo() != 0) return false;
152
153 // If the source of the memcpy/move is not constant, reject it.
154 if (isModSet(AA->getModRefInfoMask(MI->getSource())))
155 return false;
156
157 // Otherwise, the transform is safe. Remember the copy instruction.
158 TheCopy = MI;
159 }
160 }
161 return true;
162}
163
164/// isOnlyCopiedFromConstantMemory - Return true if the specified alloca is only
165/// modified by a copy from a constant memory location. If we can prove this, we
166/// can replace any uses of the alloca with uses of the memory location
167/// directly.
168static MemTransferInst *
170 AllocaInst *AI,
172 MemTransferInst *TheCopy = nullptr;
173 if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))
174 return TheCopy;
175 return nullptr;
176}
177
178/// Returns true if V is dereferenceable for size of alloca.
179static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
180 const DataLayout &DL) {
181 if (AI->isArrayAllocation())
182 return false;
183 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
184 if (!AllocaSize)
185 return false;
187 APInt(64, AllocaSize), DL);
188}
189
191 AllocaInst &AI, DominatorTree &DT) {
192 // Check for array size of 1 (scalar allocation).
193 if (!AI.isArrayAllocation()) {
194 // i32 1 is the canonical array size for scalar allocations.
195 if (AI.getArraySize()->getType()->isIntegerTy(32))
196 return nullptr;
197
198 // Canonicalize it.
199 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
200 }
201
202 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
203 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
204 if (C->getValue().getActiveBits() <= 64) {
205 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
206 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),
207 nullptr, AI.getName());
208 New->setAlignment(AI.getAlign());
209
210 replaceAllDbgUsesWith(AI, *New, *New, DT);
211
212 // Scan to the end of the allocation instructions, to skip over a block of
213 // allocas if possible...also skip interleaved debug info
214 //
215 BasicBlock::iterator It(New);
216 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
217 ++It;
218
219 // Now that I is pointing to the first non-allocation-inst in the block,
220 // insert our getelementptr instruction...
221 //
222 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
223 Value *NullIdx = Constant::getNullValue(IdxTy);
224 Value *Idx[2] = {NullIdx, NullIdx};
226 NewTy, New, Idx, New->getName() + ".sub");
227 IC.InsertNewInstBefore(GEP, *It);
228
229 // Now make everything use the getelementptr instead of the original
230 // allocation.
231 return IC.replaceInstUsesWith(AI, GEP);
232 }
233 }
234
235 if (isa<UndefValue>(AI.getArraySize()))
237
238 // Ensure that the alloca array size argument has type intptr_t, so that
239 // any casting is exposed early.
240 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
241 if (AI.getArraySize()->getType() != IntPtrTy) {
242 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
243 return IC.replaceOperand(AI, 0, V);
244 }
245
246 return nullptr;
247}
248
249namespace {
250// If I and V are pointers in different address space, it is not allowed to
251// use replaceAllUsesWith since I and V have different types. A
252// non-target-specific transformation should not use addrspacecast on V since
253// the two address space may be disjoint depending on target.
254//
255// This class chases down uses of the old pointer until reaching the load
256// instructions, then replaces the old pointer in the load instructions with
257// the new pointer. If during the chasing it sees bitcast or GEP, it will
258// create new bitcast or GEP with the new pointer and use them in the load
259// instruction.
260class PointerReplacer {
261public:
262 PointerReplacer(InstCombinerImpl &IC, Instruction &Root)
263 : IC(IC), Root(Root) {}
264
265 bool collectUsers();
266 void replacePointer(Value *V);
267
268private:
269 bool collectUsersRecursive(Instruction &I);
270 void replace(Instruction *I);
271 Value *getReplacement(Value *I);
272 bool isAvailable(Instruction *I) const {
273 return I == &Root || Worklist.contains(I);
274 }
275
276 SmallPtrSet<Instruction *, 32> ValuesToRevisit;
280 Instruction &Root;
281};
282} // end anonymous namespace
283
284bool PointerReplacer::collectUsers() {
285 if (!collectUsersRecursive(Root))
286 return false;
287
288 // Ensure that all outstanding (indirect) users of I
289 // are inserted into the Worklist. Return false
290 // otherwise.
291 for (auto *Inst : ValuesToRevisit)
292 if (!Worklist.contains(Inst))
293 return false;
294 return true;
295}
296
297bool PointerReplacer::collectUsersRecursive(Instruction &I) {
298 for (auto *U : I.users()) {
299 auto *Inst = cast<Instruction>(&*U);
300 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
301 if (Load->isVolatile())
302 return false;
303 Worklist.insert(Load);
304 } else if (auto *PHI = dyn_cast<PHINode>(Inst)) {
305 // All incoming values must be instructions for replacability
306 if (any_of(PHI->incoming_values(),
307 [](Value *V) { return !isa<Instruction>(V); }))
308 return false;
309
310 // If at least one incoming value of the PHI is not in Worklist,
311 // store the PHI for revisiting and skip this iteration of the
312 // loop.
313 if (any_of(PHI->incoming_values(), [this](Value *V) {
314 return !isAvailable(cast<Instruction>(V));
315 })) {
316 ValuesToRevisit.insert(Inst);
317 continue;
318 }
319
320 Worklist.insert(PHI);
321 if (!collectUsersRecursive(*PHI))
322 return false;
323 } else if (auto *SI = dyn_cast<SelectInst>(Inst)) {
324 if (!isa<Instruction>(SI->getTrueValue()) ||
325 !isa<Instruction>(SI->getFalseValue()))
326 return false;
327
328 if (!isAvailable(cast<Instruction>(SI->getTrueValue())) ||
329 !isAvailable(cast<Instruction>(SI->getFalseValue()))) {
330 ValuesToRevisit.insert(Inst);
331 continue;
332 }
333 Worklist.insert(SI);
334 if (!collectUsersRecursive(*SI))
335 return false;
336 } else if (isa<GetElementPtrInst, BitCastInst>(Inst)) {
337 Worklist.insert(Inst);
338 if (!collectUsersRecursive(*Inst))
339 return false;
340 } else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {
341 if (MI->isVolatile())
342 return false;
343 Worklist.insert(Inst);
344 } else if (Inst->isLifetimeStartOrEnd()) {
345 continue;
346 } else {
347 LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');
348 return false;
349 }
350 }
351
352 return true;
353}
354
355Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }
356
357void PointerReplacer::replace(Instruction *I) {
358 if (getReplacement(I))
359 return;
360
361 if (auto *LT = dyn_cast<LoadInst>(I)) {
362 auto *V = getReplacement(LT->getPointerOperand());
363 assert(V && "Operand not replaced");
364 auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),
365 LT->getAlign(), LT->getOrdering(),
366 LT->getSyncScopeID());
367 NewI->takeName(LT);
368 copyMetadataForLoad(*NewI, *LT);
369
370 IC.InsertNewInstWith(NewI, *LT);
371 IC.replaceInstUsesWith(*LT, NewI);
372 WorkMap[LT] = NewI;
373 } else if (auto *PHI = dyn_cast<PHINode>(I)) {
374 Type *NewTy = getReplacement(PHI->getIncomingValue(0))->getType();
375 auto *NewPHI = PHINode::Create(NewTy, PHI->getNumIncomingValues(),
376 PHI->getName(), PHI);
377 for (unsigned int I = 0; I < PHI->getNumIncomingValues(); ++I)
378 NewPHI->addIncoming(getReplacement(PHI->getIncomingValue(I)),
379 PHI->getIncomingBlock(I));
380 WorkMap[PHI] = NewPHI;
381 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
382 auto *V = getReplacement(GEP->getPointerOperand());
383 assert(V && "Operand not replaced");
385 Indices.append(GEP->idx_begin(), GEP->idx_end());
386 auto *NewI =
387 GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);
388 IC.InsertNewInstWith(NewI, *GEP);
389 NewI->takeName(GEP);
390 WorkMap[GEP] = NewI;
391 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
392 auto *V = getReplacement(BC->getOperand(0));
393 assert(V && "Operand not replaced");
394 auto *NewT = PointerType::getWithSamePointeeType(
395 cast<PointerType>(BC->getType()),
396 V->getType()->getPointerAddressSpace());
397 auto *NewI = new BitCastInst(V, NewT);
398 IC.InsertNewInstWith(NewI, *BC);
399 NewI->takeName(BC);
400 WorkMap[BC] = NewI;
401 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
402 auto *NewSI = SelectInst::Create(
403 SI->getCondition(), getReplacement(SI->getTrueValue()),
404 getReplacement(SI->getFalseValue()), SI->getName(), nullptr, SI);
405 IC.InsertNewInstWith(NewSI, *SI);
406 NewSI->takeName(SI);
407 WorkMap[SI] = NewSI;
408 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
409 auto *SrcV = getReplacement(MemCpy->getRawSource());
410 // The pointer may appear in the destination of a copy, but we don't want to
411 // replace it.
412 if (!SrcV) {
413 assert(getReplacement(MemCpy->getRawDest()) &&
414 "destination not in replace list");
415 return;
416 }
417
418 IC.Builder.SetInsertPoint(MemCpy);
419 auto *NewI = IC.Builder.CreateMemTransferInst(
420 MemCpy->getIntrinsicID(), MemCpy->getRawDest(), MemCpy->getDestAlign(),
421 SrcV, MemCpy->getSourceAlign(), MemCpy->getLength(),
422 MemCpy->isVolatile());
423 AAMDNodes AAMD = MemCpy->getAAMetadata();
424 if (AAMD)
425 NewI->setAAMetadata(AAMD);
426
427 IC.eraseInstFromFunction(*MemCpy);
428 WorkMap[MemCpy] = NewI;
429 } else {
430 llvm_unreachable("should never reach here");
431 }
432}
433
434void PointerReplacer::replacePointer(Value *V) {
435#ifndef NDEBUG
436 auto *PT = cast<PointerType>(Root.getType());
437 auto *NT = cast<PointerType>(V->getType());
438 assert(PT != NT && PT->hasSameElementTypeAs(NT) && "Invalid usage");
439#endif
440 WorkMap[&Root] = V;
441
442 for (Instruction *Workitem : Worklist)
443 replace(Workitem);
444}
445
447 if (auto *I = simplifyAllocaArraySize(*this, AI, DT))
448 return I;
449
450 if (AI.getAllocatedType()->isSized()) {
451 // Move all alloca's of zero byte objects to the entry block and merge them
452 // together. Note that we only do this for alloca's, because malloc should
453 // allocate and return a unique pointer, even for a zero byte allocation.
455 // For a zero sized alloca there is no point in doing an array allocation.
456 // This is helpful if the array size is a complicated expression not used
457 // elsewhere.
458 if (AI.isArrayAllocation())
459 return replaceOperand(AI, 0,
461
462 // Get the first instruction in the entry block.
463 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
464 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
465 if (FirstInst != &AI) {
466 // If the entry block doesn't start with a zero-size alloca then move
467 // this one to the start of the entry block. There is no problem with
468 // dominance as the array size was forced to a constant earlier already.
469 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
470 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
472 .getKnownMinValue() != 0) {
473 AI.moveBefore(FirstInst);
474 return &AI;
475 }
476
477 // Replace this zero-sized alloca with the one at the start of the entry
478 // block after ensuring that the address will be aligned enough for both
479 // types.
480 const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
481 EntryAI->setAlignment(MaxAlign);
482 if (AI.getType() != EntryAI->getType())
483 return new BitCastInst(EntryAI, AI.getType());
484 return replaceInstUsesWith(AI, EntryAI);
485 }
486 }
487 }
488
489 // Check to see if this allocation is only modified by a memcpy/memmove from
490 // a memory location whose alignment is equal to or exceeds that of the
491 // allocation. If this is the case, we can change all users to use the
492 // constant memory location instead. This is commonly produced by the CFE by
493 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
494 // is only subsequently read.
496 if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {
497 Value *TheSrc = Copy->getSource();
498 Align AllocaAlign = AI.getAlign();
499 Align SourceAlign = getOrEnforceKnownAlignment(
500 TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
501 if (AllocaAlign <= SourceAlign &&
502 isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
503 !isa<Instruction>(TheSrc)) {
504 // FIXME: Can we sink instructions without violating dominance when TheSrc
505 // is an instruction instead of a constant or argument?
506 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
507 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
508 unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
509 auto *DestTy = PointerType::get(AI.getAllocatedType(), SrcAddrSpace);
510 if (AI.getAddressSpace() == SrcAddrSpace) {
511 for (Instruction *Delete : ToDelete)
512 eraseInstFromFunction(*Delete);
513
514 Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
515 Instruction *NewI = replaceInstUsesWith(AI, Cast);
517 ++NumGlobalCopies;
518 return NewI;
519 }
520
521 PointerReplacer PtrReplacer(*this, AI);
522 if (PtrReplacer.collectUsers()) {
523 for (Instruction *Delete : ToDelete)
524 eraseInstFromFunction(*Delete);
525
526 Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
527 PtrReplacer.replacePointer(Cast);
528 ++NumGlobalCopies;
529 }
530 }
531 }
532
533 // At last, use the generic allocation site handler to aggressively remove
534 // unused allocas.
535 return visitAllocSite(AI);
536}
537
538// Are we allowed to form a atomic load or store of this type?
539static bool isSupportedAtomicType(Type *Ty) {
540 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
541}
542
543/// Helper to combine a load to a new type.
544///
545/// This just does the work of combining a load to a new type. It handles
546/// metadata, etc., and returns the new instruction. The \c NewTy should be the
547/// loaded *value* type. This will convert it to a pointer, cast the operand to
548/// that pointer type, load it, etc.
549///
550/// Note that this will create all of the instructions with whatever insert
551/// point the \c InstCombinerImpl currently is using.
553 const Twine &Suffix) {
554 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
555 "can't fold an atomic load to requested type");
556
557 Value *Ptr = LI.getPointerOperand();
558 unsigned AS = LI.getPointerAddressSpace();
559 Type *NewPtrTy = NewTy->getPointerTo(AS);
560 Value *NewPtr = nullptr;
561 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
562 NewPtr->getType() == NewPtrTy))
563 NewPtr = Builder.CreateBitCast(Ptr, NewPtrTy);
564
566 NewTy, NewPtr, LI.getAlign(), LI.isVolatile(), LI.getName() + Suffix);
567 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
568 copyMetadataForLoad(*NewLoad, LI);
569 return NewLoad;
570}
571
572/// Combine a store to a new type.
573///
574/// Returns the newly created store instruction.
576 Value *V) {
577 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
578 "can't fold an atomic store of requested type");
579
580 Value *Ptr = SI.getPointerOperand();
581 unsigned AS = SI.getPointerAddressSpace();
583 SI.getAllMetadata(MD);
584
585 StoreInst *NewStore = IC.Builder.CreateAlignedStore(
586 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
587 SI.getAlign(), SI.isVolatile());
588 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
589 for (const auto &MDPair : MD) {
590 unsigned ID = MDPair.first;
591 MDNode *N = MDPair.second;
592 // Note, essentially every kind of metadata should be preserved here! This
593 // routine is supposed to clone a store instruction changing *only its
594 // type*. The only metadata it makes sense to drop is metadata which is
595 // invalidated when the pointer type changes. This should essentially
596 // never be the case in LLVM, but we explicitly switch over only known
597 // metadata to be conservatively correct. If you are adding metadata to
598 // LLVM which pertains to stores, you almost certainly want to add it
599 // here.
600 switch (ID) {
601 case LLVMContext::MD_dbg:
602 case LLVMContext::MD_DIAssignID:
603 case LLVMContext::MD_tbaa:
604 case LLVMContext::MD_prof:
605 case LLVMContext::MD_fpmath:
606 case LLVMContext::MD_tbaa_struct:
607 case LLVMContext::MD_alias_scope:
608 case LLVMContext::MD_noalias:
609 case LLVMContext::MD_nontemporal:
610 case LLVMContext::MD_mem_parallel_loop_access:
611 case LLVMContext::MD_access_group:
612 // All of these directly apply.
613 NewStore->setMetadata(ID, N);
614 break;
615 case LLVMContext::MD_invariant_load:
616 case LLVMContext::MD_nonnull:
617 case LLVMContext::MD_noundef:
618 case LLVMContext::MD_range:
619 case LLVMContext::MD_align:
620 case LLVMContext::MD_dereferenceable:
621 case LLVMContext::MD_dereferenceable_or_null:
622 // These don't apply for stores.
623 break;
624 }
625 }
626
627 return NewStore;
628}
629
630/// Returns true if instruction represent minmax pattern like:
631/// select ((cmp load V1, load V2), V1, V2).
632static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) {
633 assert(V->getType()->isPointerTy() && "Expected pointer type.");
634 // Ignore possible ty* to ixx* bitcast.
636 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax
637 // pattern.
639 Instruction *L1;
640 Instruction *L2;
641 Value *LHS;
642 Value *RHS;
643 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
644 m_Value(LHS), m_Value(RHS))))
645 return false;
646 LoadTy = L1->getType();
647 return (match(L1, m_Load(m_Specific(LHS))) &&
648 match(L2, m_Load(m_Specific(RHS)))) ||
649 (match(L1, m_Load(m_Specific(RHS))) &&
650 match(L2, m_Load(m_Specific(LHS))));
651}
652
653/// Combine loads to match the type of their uses' value after looking
654/// through intervening bitcasts.
655///
656/// The core idea here is that if the result of a load is used in an operation,
657/// we should load the type most conducive to that operation. For example, when
658/// loading an integer and converting that immediately to a pointer, we should
659/// instead directly load a pointer.
660///
661/// However, this routine must never change the width of a load or the number of
662/// loads as that would introduce a semantic change. This combine is expected to
663/// be a semantic no-op which just allows loads to more closely model the types
664/// of their consuming operations.
665///
666/// Currently, we also refuse to change the precise type used for an atomic load
667/// or a volatile load. This is debatable, and might be reasonable to change
668/// later. However, it is risky in case some backend or other part of LLVM is
669/// relying on the exact type loaded to select appropriate atomic operations.
671 LoadInst &Load) {
672 // FIXME: We could probably with some care handle both volatile and ordered
673 // atomic loads here but it isn't clear that this is important.
674 if (!Load.isUnordered())
675 return nullptr;
676
677 if (Load.use_empty())
678 return nullptr;
679
680 // swifterror values can't be bitcasted.
681 if (Load.getPointerOperand()->isSwiftError())
682 return nullptr;
683
684 // Fold away bit casts of the loaded value by loading the desired type.
685 // Note that we should not do this for pointer<->integer casts,
686 // because that would result in type punning.
687 if (Load.hasOneUse()) {
688 // Don't transform when the type is x86_amx, it makes the pass that lower
689 // x86_amx type happy.
690 Type *LoadTy = Load.getType();
691 if (auto *BC = dyn_cast<BitCastInst>(Load.user_back())) {
692 assert(!LoadTy->isX86_AMXTy() && "Load from x86_amx* should not happen!");
693 if (BC->getType()->isX86_AMXTy())
694 return nullptr;
695 }
696
697 if (auto *CastUser = dyn_cast<CastInst>(Load.user_back())) {
698 Type *DestTy = CastUser->getDestTy();
699 if (CastUser->isNoopCast(IC.getDataLayout()) &&
700 LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&
701 (!Load.isAtomic() || isSupportedAtomicType(DestTy))) {
702 LoadInst *NewLoad = IC.combineLoadToNewType(Load, DestTy);
703 CastUser->replaceAllUsesWith(NewLoad);
704 IC.eraseInstFromFunction(*CastUser);
705 return &Load;
706 }
707 }
708 }
709
710 // FIXME: We should also canonicalize loads of vectors when their elements are
711 // cast to other types.
712 return nullptr;
713}
714
716 // FIXME: We could probably with some care handle both volatile and atomic
717 // stores here but it isn't clear that this is important.
718 if (!LI.isSimple())
719 return nullptr;
720
721 Type *T = LI.getType();
722 if (!T->isAggregateType())
723 return nullptr;
724
725 StringRef Name = LI.getName();
726
727 if (auto *ST = dyn_cast<StructType>(T)) {
728 // If the struct only have one element, we unpack.
729 auto NumElements = ST->getNumElements();
730 if (NumElements == 1) {
731 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
732 ".unpack");
733 NewLoad->setAAMetadata(LI.getAAMetadata());
735 PoisonValue::get(T), NewLoad, 0, Name));
736 }
737
738 // We don't want to break loads with padding here as we'd loose
739 // the knowledge that padding exists for the rest of the pipeline.
740 const DataLayout &DL = IC.getDataLayout();
741 auto *SL = DL.getStructLayout(ST);
742 if (SL->hasPadding())
743 return nullptr;
744
745 const auto Align = LI.getAlign();
746 auto *Addr = LI.getPointerOperand();
747 auto *IdxType = Type::getInt32Ty(T->getContext());
748 auto *Zero = ConstantInt::get(IdxType, 0);
749
751 for (unsigned i = 0; i < NumElements; i++) {
752 Value *Indices[2] = {
753 Zero,
754 ConstantInt::get(IdxType, i),
755 };
756 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices),
757 Name + ".elt");
758 auto *L = IC.Builder.CreateAlignedLoad(
759 ST->getElementType(i), Ptr,
760 commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");
761 // Propagate AA metadata. It'll still be valid on the narrowed load.
762 L->setAAMetadata(LI.getAAMetadata());
763 V = IC.Builder.CreateInsertValue(V, L, i);
764 }
765
766 V->setName(Name);
767 return IC.replaceInstUsesWith(LI, V);
768 }
769
770 if (auto *AT = dyn_cast<ArrayType>(T)) {
771 auto *ET = AT->getElementType();
772 auto NumElements = AT->getNumElements();
773 if (NumElements == 1) {
774 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
775 NewLoad->setAAMetadata(LI.getAAMetadata());
777 PoisonValue::get(T), NewLoad, 0, Name));
778 }
779
780 // Bail out if the array is too large. Ideally we would like to optimize
781 // arrays of arbitrary size but this has a terrible impact on compile time.
782 // The threshold here is chosen arbitrarily, maybe needs a little bit of
783 // tuning.
784 if (NumElements > IC.MaxArraySizeForCombine)
785 return nullptr;
786
787 const DataLayout &DL = IC.getDataLayout();
788 auto EltSize = DL.getTypeAllocSize(ET);
789 const auto Align = LI.getAlign();
790
791 auto *Addr = LI.getPointerOperand();
792 auto *IdxType = Type::getInt64Ty(T->getContext());
793 auto *Zero = ConstantInt::get(IdxType, 0);
794
796 uint64_t Offset = 0;
797 for (uint64_t i = 0; i < NumElements; i++) {
798 Value *Indices[2] = {
799 Zero,
800 ConstantInt::get(IdxType, i),
801 };
802 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices),
803 Name + ".elt");
804 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
806 Name + ".unpack");
807 L->setAAMetadata(LI.getAAMetadata());
808 V = IC.Builder.CreateInsertValue(V, L, i);
809 Offset += EltSize;
810 }
811
812 V->setName(Name);
813 return IC.replaceInstUsesWith(LI, V);
814 }
815
816 return nullptr;
817}
818
819// If we can determine that all possible objects pointed to by the provided
820// pointer value are, not only dereferenceable, but also definitively less than
821// or equal to the provided maximum size, then return true. Otherwise, return
822// false (constant global values and allocas fall into this category).
823//
824// FIXME: This should probably live in ValueTracking (or similar).
826 const DataLayout &DL) {
828 SmallVector<Value *, 4> Worklist(1, V);
829
830 do {
831 Value *P = Worklist.pop_back_val();
832 P = P->stripPointerCasts();
833
834 if (!Visited.insert(P).second)
835 continue;
836
837 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
838 Worklist.push_back(SI->getTrueValue());
839 Worklist.push_back(SI->getFalseValue());
840 continue;
841 }
842
843 if (PHINode *PN = dyn_cast<PHINode>(P)) {
844 append_range(Worklist, PN->incoming_values());
845 continue;
846 }
847
848 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
849 if (GA->isInterposable())
850 return false;
851 Worklist.push_back(GA->getAliasee());
852 continue;
853 }
854
855 // If we know how big this object is, and it is less than MaxSize, continue
856 // searching. Otherwise, return false.
857 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
858 if (!AI->getAllocatedType()->isSized())
859 return false;
860
861 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
862 if (!CS)
863 return false;
864
865 TypeSize TS = DL.getTypeAllocSize(AI->getAllocatedType());
866 if (TS.isScalable())
867 return false;
868 // Make sure that, even if the multiplication below would wrap as an
869 // uint64_t, we still do the right thing.
870 if ((CS->getValue().zext(128) * APInt(128, TS.getFixedValue()))
871 .ugt(MaxSize))
872 return false;
873 continue;
874 }
875
876 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
877 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
878 return false;
879
880 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
881 if (InitSize > MaxSize)
882 return false;
883 continue;
884 }
885
886 return false;
887 } while (!Worklist.empty());
888
889 return true;
890}
891
892// If we're indexing into an object of a known size, and the outer index is
893// not a constant, but having any value but zero would lead to undefined
894// behavior, replace it with zero.
895//
896// For example, if we have:
897// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
898// ...
899// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
900// ... = load i32* %arrayidx, align 4
901// Then we know that we can replace %x in the GEP with i64 0.
902//
903// FIXME: We could fold any GEP index to zero that would cause UB if it were
904// not zero. Currently, we only handle the first such index. Also, we could
905// also search through non-zero constant indices if we kept track of the
906// offsets those indices implied.
908 GetElementPtrInst *GEPI, Instruction *MemI,
909 unsigned &Idx) {
910 if (GEPI->getNumOperands() < 2)
911 return false;
912
913 // Find the first non-zero index of a GEP. If all indices are zero, return
914 // one past the last index.
915 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
916 unsigned I = 1;
917 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
918 Value *V = GEPI->getOperand(I);
919 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
920 if (CI->isZero())
921 continue;
922
923 break;
924 }
925
926 return I;
927 };
928
929 // Skip through initial 'zero' indices, and find the corresponding pointer
930 // type. See if the next index is not a constant.
931 Idx = FirstNZIdx(GEPI);
932 if (Idx == GEPI->getNumOperands())
933 return false;
934 if (isa<Constant>(GEPI->getOperand(Idx)))
935 return false;
936
937 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
938 Type *SourceElementType = GEPI->getSourceElementType();
939 // Size information about scalable vectors is not available, so we cannot
940 // deduce whether indexing at n is undefined behaviour or not. Bail out.
941 if (isa<ScalableVectorType>(SourceElementType))
942 return false;
943
944 Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
945 if (!AllocTy || !AllocTy->isSized())
946 return false;
947 const DataLayout &DL = IC.getDataLayout();
948 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedValue();
949
950 // If there are more indices after the one we might replace with a zero, make
951 // sure they're all non-negative. If any of them are negative, the overall
952 // address being computed might be before the base address determined by the
953 // first non-zero index.
954 auto IsAllNonNegative = [&]() {
955 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
956 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
957 if (Known.isNonNegative())
958 continue;
959 return false;
960 }
961
962 return true;
963 };
964
965 // FIXME: If the GEP is not inbounds, and there are extra indices after the
966 // one we'll replace, those could cause the address computation to wrap
967 // (rendering the IsAllNonNegative() check below insufficient). We can do
968 // better, ignoring zero indices (and other indices we can prove small
969 // enough not to wrap).
970 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
971 return false;
972
973 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
974 // also known to be dereferenceable.
975 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
976 IsAllNonNegative();
977}
978
979// If we're indexing into an object with a variable index for the memory
980// access, but the object has only one element, we can assume that the index
981// will always be zero. If we replace the GEP, return it.
982template <typename T>
984 T &MemI) {
985 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
986 unsigned Idx;
987 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
988 Instruction *NewGEPI = GEPI->clone();
989 NewGEPI->setOperand(Idx,
990 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
991 NewGEPI->insertBefore(GEPI);
992 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
993 return NewGEPI;
994 }
995 }
996
997 return nullptr;
998}
999
1001 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
1002 return false;
1003
1004 auto *Ptr = SI.getPointerOperand();
1005 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
1006 Ptr = GEPI->getOperand(0);
1007 return (isa<ConstantPointerNull>(Ptr) &&
1008 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
1009}
1010
1012 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
1013 const Value *GEPI0 = GEPI->getOperand(0);
1014 if (isa<ConstantPointerNull>(GEPI0) &&
1015 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
1016 return true;
1017 }
1018 if (isa<UndefValue>(Op) ||
1019 (isa<ConstantPointerNull>(Op) &&
1021 return true;
1022 return false;
1023}
1024
1026 Value *Op = LI.getOperand(0);
1027 if (Value *Res = simplifyLoadInst(&LI, Op, SQ.getWithInstruction(&LI)))
1028 return replaceInstUsesWith(LI, Res);
1029
1030 // Try to canonicalize the loaded type.
1031 if (Instruction *Res = combineLoadToOperationType(*this, LI))
1032 return Res;
1033
1034 // Attempt to improve the alignment.
1035 Align KnownAlign = getOrEnforceKnownAlignment(
1036 Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);
1037 if (KnownAlign > LI.getAlign())
1038 LI.setAlignment(KnownAlign);
1039
1040 // Replace GEP indices if possible.
1041 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
1042 Worklist.push(NewGEPI);
1043 return &LI;
1044 }
1045
1046 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1047 return Res;
1048
1049 // Do really simple store-to-load forwarding and load CSE, to catch cases
1050 // where there are several consecutive memory accesses to the same location,
1051 // separated by a few arithmetic operations.
1052 bool IsLoadCSE = false;
1053 if (Value *AvailableVal = FindAvailableLoadedValue(&LI, *AA, &IsLoadCSE)) {
1054 if (IsLoadCSE)
1055 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
1056
1057 return replaceInstUsesWith(
1058 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1059 LI.getName() + ".cast"));
1060 }
1061
1062 // None of the following transforms are legal for volatile/ordered atomic
1063 // loads. Most of them do apply for unordered atomics.
1064 if (!LI.isUnordered()) return nullptr;
1065
1066 // load(gep null, ...) -> unreachable
1067 // load null/undef -> unreachable
1068 // TODO: Consider a target hook for valid address spaces for this xforms.
1069 if (canSimplifyNullLoadOrGEP(LI, Op)) {
1070 // Insert a new store to null instruction before the load to indicate
1071 // that this code is not reachable. We do this instead of inserting
1072 // an unreachable instruction directly because we cannot modify the
1073 // CFG.
1074 StoreInst *SI = new StoreInst(PoisonValue::get(LI.getType()),
1075 Constant::getNullValue(Op->getType()), &LI);
1076 SI->setDebugLoc(LI.getDebugLoc());
1077 return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));
1078 }
1079
1080 if (Op->hasOneUse()) {
1081 // Change select and PHI nodes to select values instead of addresses: this
1082 // helps alias analysis out a lot, allows many others simplifications, and
1083 // exposes redundancy in the code.
1084 //
1085 // Note that we cannot do the transformation unless we know that the
1086 // introduced loads cannot trap! Something like this is valid as long as
1087 // the condition is always false: load (select bool %C, int* null, int* %G),
1088 // but it would not be valid if we transformed it to load from null
1089 // unconditionally.
1090 //
1091 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1092 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
1093 Align Alignment = LI.getAlign();
1094 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
1095 Alignment, DL, SI) &&
1096 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
1097 Alignment, DL, SI)) {
1098 LoadInst *V1 =
1099 Builder.CreateLoad(LI.getType(), SI->getOperand(1),
1100 SI->getOperand(1)->getName() + ".val");
1101 LoadInst *V2 =
1102 Builder.CreateLoad(LI.getType(), SI->getOperand(2),
1103 SI->getOperand(2)->getName() + ".val");
1104 assert(LI.isUnordered() && "implied by above");
1105 V1->setAlignment(Alignment);
1106 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1107 V2->setAlignment(Alignment);
1108 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1109 return SelectInst::Create(SI->getCondition(), V1, V2);
1110 }
1111
1112 // load (select (cond, null, P)) -> load P
1113 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
1114 !NullPointerIsDefined(SI->getFunction(),
1115 LI.getPointerAddressSpace()))
1116 return replaceOperand(LI, 0, SI->getOperand(2));
1117
1118 // load (select (cond, P, null)) -> load P
1119 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1120 !NullPointerIsDefined(SI->getFunction(),
1121 LI.getPointerAddressSpace()))
1122 return replaceOperand(LI, 0, SI->getOperand(1));
1123 }
1124 }
1125 return nullptr;
1126}
1127
1128/// Look for extractelement/insertvalue sequence that acts like a bitcast.
1129///
1130/// \returns underlying value that was "cast", or nullptr otherwise.
1131///
1132/// For example, if we have:
1133///
1134/// %E0 = extractelement <2 x double> %U, i32 0
1135/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1136/// %E1 = extractelement <2 x double> %U, i32 1
1137/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1138///
1139/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1140/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1141/// Note that %U may contain non-undef values where %V1 has undef.
1143 Value *U = nullptr;
1144 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1145 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1146 if (!E)
1147 return nullptr;
1148 auto *W = E->getVectorOperand();
1149 if (!U)
1150 U = W;
1151 else if (U != W)
1152 return nullptr;
1153 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1154 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1155 return nullptr;
1156 V = IV->getAggregateOperand();
1157 }
1158 if (!match(V, m_Undef()) || !U)
1159 return nullptr;
1160
1161 auto *UT = cast<VectorType>(U->getType());
1162 auto *VT = V->getType();
1163 // Check that types UT and VT are bitwise isomorphic.
1164 const auto &DL = IC.getDataLayout();
1165 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1166 return nullptr;
1167 }
1168 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1169 if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1170 return nullptr;
1171 } else {
1172 auto *ST = cast<StructType>(VT);
1173 if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1174 return nullptr;
1175 for (const auto *EltT : ST->elements()) {
1176 if (EltT != UT->getElementType())
1177 return nullptr;
1178 }
1179 }
1180 return U;
1181}
1182
1183/// Combine stores to match the type of value being stored.
1184///
1185/// The core idea here is that the memory does not have any intrinsic type and
1186/// where we can we should match the type of a store to the type of value being
1187/// stored.
1188///
1189/// However, this routine must never change the width of a store or the number of
1190/// stores as that would introduce a semantic change. This combine is expected to
1191/// be a semantic no-op which just allows stores to more closely model the types
1192/// of their incoming values.
1193///
1194/// Currently, we also refuse to change the precise type used for an atomic or
1195/// volatile store. This is debatable, and might be reasonable to change later.
1196/// However, it is risky in case some backend or other part of LLVM is relying
1197/// on the exact type stored to select appropriate atomic operations.
1198///
1199/// \returns true if the store was successfully combined away. This indicates
1200/// the caller must erase the store instruction. We have to let the caller erase
1201/// the store instruction as otherwise there is no way to signal whether it was
1202/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1204 // FIXME: We could probably with some care handle both volatile and ordered
1205 // atomic stores here but it isn't clear that this is important.
1206 if (!SI.isUnordered())
1207 return false;
1208
1209 // swifterror values can't be bitcasted.
1210 if (SI.getPointerOperand()->isSwiftError())
1211 return false;
1212
1213 Value *V = SI.getValueOperand();
1214
1215 // Fold away bit casts of the stored value by storing the original type.
1216 if (auto *BC = dyn_cast<BitCastInst>(V)) {
1217 assert(!BC->getType()->isX86_AMXTy() &&
1218 "store to x86_amx* should not happen!");
1219 V = BC->getOperand(0);
1220 // Don't transform when the type is x86_amx, it makes the pass that lower
1221 // x86_amx type happy.
1222 if (V->getType()->isX86_AMXTy())
1223 return false;
1224 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1225 combineStoreToNewValue(IC, SI, V);
1226 return true;
1227 }
1228 }
1229
1230 if (Value *U = likeBitCastFromVector(IC, V))
1231 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1232 combineStoreToNewValue(IC, SI, U);
1233 return true;
1234 }
1235
1236 // FIXME: We should also canonicalize stores of vectors when their elements
1237 // are cast to other types.
1238 return false;
1239}
1240
1242 // FIXME: We could probably with some care handle both volatile and atomic
1243 // stores here but it isn't clear that this is important.
1244 if (!SI.isSimple())
1245 return false;
1246
1247 Value *V = SI.getValueOperand();
1248 Type *T = V->getType();
1249
1250 if (!T->isAggregateType())
1251 return false;
1252
1253 if (auto *ST = dyn_cast<StructType>(T)) {
1254 // If the struct only have one element, we unpack.
1255 unsigned Count = ST->getNumElements();
1256 if (Count == 1) {
1257 V = IC.Builder.CreateExtractValue(V, 0);
1258 combineStoreToNewValue(IC, SI, V);
1259 return true;
1260 }
1261
1262 // We don't want to break loads with padding here as we'd loose
1263 // the knowledge that padding exists for the rest of the pipeline.
1264 const DataLayout &DL = IC.getDataLayout();
1265 auto *SL = DL.getStructLayout(ST);
1266 if (SL->hasPadding())
1267 return false;
1268
1269 const auto Align = SI.getAlign();
1270
1271 SmallString<16> EltName = V->getName();
1272 EltName += ".elt";
1273 auto *Addr = SI.getPointerOperand();
1274 SmallString<16> AddrName = Addr->getName();
1275 AddrName += ".repack";
1276
1277 auto *IdxType = Type::getInt32Ty(ST->getContext());
1278 auto *Zero = ConstantInt::get(IdxType, 0);
1279 for (unsigned i = 0; i < Count; i++) {
1280 Value *Indices[2] = {
1281 Zero,
1282 ConstantInt::get(IdxType, i),
1283 };
1284 auto *Ptr =
1285 IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices), AddrName);
1286 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1287 auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));
1288 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1289 NS->setAAMetadata(SI.getAAMetadata());
1290 }
1291
1292 return true;
1293 }
1294
1295 if (auto *AT = dyn_cast<ArrayType>(T)) {
1296 // If the array only have one element, we unpack.
1297 auto NumElements = AT->getNumElements();
1298 if (NumElements == 1) {
1299 V = IC.Builder.CreateExtractValue(V, 0);
1300 combineStoreToNewValue(IC, SI, V);
1301 return true;
1302 }
1303
1304 // Bail out if the array is too large. Ideally we would like to optimize
1305 // arrays of arbitrary size but this has a terrible impact on compile time.
1306 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1307 // tuning.
1308 if (NumElements > IC.MaxArraySizeForCombine)
1309 return false;
1310
1311 const DataLayout &DL = IC.getDataLayout();
1312 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1313 const auto Align = SI.getAlign();
1314
1315 SmallString<16> EltName = V->getName();
1316 EltName += ".elt";
1317 auto *Addr = SI.getPointerOperand();
1318 SmallString<16> AddrName = Addr->getName();
1319 AddrName += ".repack";
1320
1321 auto *IdxType = Type::getInt64Ty(T->getContext());
1322 auto *Zero = ConstantInt::get(IdxType, 0);
1323
1324 uint64_t Offset = 0;
1325 for (uint64_t i = 0; i < NumElements; i++) {
1326 Value *Indices[2] = {
1327 Zero,
1328 ConstantInt::get(IdxType, i),
1329 };
1330 auto *Ptr =
1331 IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices), AddrName);
1332 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1333 auto EltAlign = commonAlignment(Align, Offset);
1334 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1335 NS->setAAMetadata(SI.getAAMetadata());
1336 Offset += EltSize;
1337 }
1338
1339 return true;
1340 }
1341
1342 return false;
1343}
1344
1345/// equivalentAddressValues - Test if A and B will obviously have the same
1346/// value. This includes recognizing that %t0 and %t1 will have the same
1347/// value in code like this:
1348/// %t0 = getelementptr \@a, 0, 3
1349/// store i32 0, i32* %t0
1350/// %t1 = getelementptr \@a, 0, 3
1351/// %t2 = load i32* %t1
1352///
1354 // Test if the values are trivially equivalent.
1355 if (A == B) return true;
1356
1357 // Test if the values come form identical arithmetic instructions.
1358 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1359 // its only used to compare two uses within the same basic block, which
1360 // means that they'll always either have the same value or one of them
1361 // will have an undefined value.
1362 if (isa<BinaryOperator>(A) ||
1363 isa<CastInst>(A) ||
1364 isa<PHINode>(A) ||
1365 isa<GetElementPtrInst>(A))
1366 if (Instruction *BI = dyn_cast<Instruction>(B))
1367 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1368 return true;
1369
1370 // Otherwise they may not be equivalent.
1371 return false;
1372}
1373
1374/// Converts store (bitcast (load (bitcast (select ...)))) to
1375/// store (load (select ...)), where select is minmax:
1376/// select ((cmp load V1, load V2), V1, V2).
1378 StoreInst &SI) {
1379 // bitcast?
1380 if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
1381 return false;
1382 // load? integer?
1383 Value *LoadAddr;
1384 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
1385 return false;
1386 auto *LI = cast<LoadInst>(SI.getValueOperand());
1387 if (!LI->getType()->isIntegerTy())
1388 return false;
1389 Type *CmpLoadTy;
1390 if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy))
1391 return false;
1392
1393 // Make sure the type would actually change.
1394 // This condition can be hit with chains of bitcasts.
1395 if (LI->getType() == CmpLoadTy)
1396 return false;
1397
1398 // Make sure we're not changing the size of the load/store.
1399 const auto &DL = IC.getDataLayout();
1400 if (DL.getTypeStoreSizeInBits(LI->getType()) !=
1401 DL.getTypeStoreSizeInBits(CmpLoadTy))
1402 return false;
1403
1404 if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1405 auto *SI = dyn_cast<StoreInst>(U);
1406 return SI && SI->getPointerOperand() != LI &&
1407 InstCombiner::peekThroughBitcast(SI->getPointerOperand()) !=
1408 LoadAddr &&
1409 !SI->getPointerOperand()->isSwiftError();
1410 }))
1411 return false;
1412
1413 IC.Builder.SetInsertPoint(LI);
1414 LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy);
1415 // Replace all the stores with stores of the newly loaded value.
1416 for (auto *UI : LI->users()) {
1417 auto *USI = cast<StoreInst>(UI);
1418 IC.Builder.SetInsertPoint(USI);
1419 combineStoreToNewValue(IC, *USI, NewLI);
1420 }
1421 IC.replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
1422 IC.eraseInstFromFunction(*LI);
1423 return true;
1424}
1425
1427 Value *Val = SI.getOperand(0);
1428 Value *Ptr = SI.getOperand(1);
1429
1430 // Try to canonicalize the stored type.
1431 if (combineStoreToValueType(*this, SI))
1432 return eraseInstFromFunction(SI);
1433
1434 // Attempt to improve the alignment.
1435 const Align KnownAlign = getOrEnforceKnownAlignment(
1436 Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);
1437 if (KnownAlign > SI.getAlign())
1438 SI.setAlignment(KnownAlign);
1439
1440 // Try to canonicalize the stored type.
1441 if (unpackStoreToAggregate(*this, SI))
1442 return eraseInstFromFunction(SI);
1443
1445 return eraseInstFromFunction(SI);
1446
1447 // Replace GEP indices if possible.
1448 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1449 Worklist.push(NewGEPI);
1450 return &SI;
1451 }
1452
1453 // Don't hack volatile/ordered stores.
1454 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1455 if (!SI.isUnordered()) return nullptr;
1456
1457 // If the RHS is an alloca with a single use, zapify the store, making the
1458 // alloca dead.
1459 if (Ptr->hasOneUse()) {
1460 if (isa<AllocaInst>(Ptr))
1461 return eraseInstFromFunction(SI);
1462 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1463 if (isa<AllocaInst>(GEP->getOperand(0))) {
1464 if (GEP->getOperand(0)->hasOneUse())
1465 return eraseInstFromFunction(SI);
1466 }
1467 }
1468 }
1469
1470 // If we have a store to a location which is known constant, we can conclude
1471 // that the store must be storing the constant value (else the memory
1472 // wouldn't be constant), and this must be a noop.
1474 return eraseInstFromFunction(SI);
1475
1476 // Do really simple DSE, to catch cases where there are several consecutive
1477 // stores to the same location, separated by a few arithmetic operations. This
1478 // situation often occurs with bitfield accesses.
1480 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1481 --ScanInsts) {
1482 --BBI;
1483 // Don't count debug info directives, lest they affect codegen,
1484 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1485 if (BBI->isDebugOrPseudoInst() ||
1486 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1487 ScanInsts++;
1488 continue;
1489 }
1490
1491 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1492 // Prev store isn't volatile, and stores to the same location?
1493 if (PrevSI->isUnordered() &&
1494 equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&
1495 PrevSI->getValueOperand()->getType() ==
1496 SI.getValueOperand()->getType()) {
1497 ++NumDeadStore;
1498 // Manually add back the original store to the worklist now, so it will
1499 // be processed after the operands of the removed store, as this may
1500 // expose additional DSE opportunities.
1501 Worklist.push(&SI);
1502 eraseInstFromFunction(*PrevSI);
1503 return nullptr;
1504 }
1505 break;
1506 }
1507
1508 // If this is a load, we have to stop. However, if the loaded value is from
1509 // the pointer we're loading and is producing the pointer we're storing,
1510 // then *this* store is dead (X = load P; store X -> P).
1511 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1512 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1513 assert(SI.isUnordered() && "can't eliminate ordering operation");
1514 return eraseInstFromFunction(SI);
1515 }
1516
1517 // Otherwise, this is a load from some other location. Stores before it
1518 // may not be dead.
1519 break;
1520 }
1521
1522 // Don't skip over loads, throws or things that can modify memory.
1523 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1524 break;
1525 }
1526
1527 // store X, null -> turns into 'unreachable' in SimplifyCFG
1528 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1530 if (!isa<PoisonValue>(Val))
1531 return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
1532 return nullptr; // Do not modify these!
1533 }
1534
1535 // store undef, Ptr -> noop
1536 // FIXME: This is technically incorrect because it might overwrite a poison
1537 // value. Change to PoisonValue once #52930 is resolved.
1538 if (isa<UndefValue>(Val))
1539 return eraseInstFromFunction(SI);
1540
1541 return nullptr;
1542}
1543
1544/// Try to transform:
1545/// if () { *P = v1; } else { *P = v2 }
1546/// or:
1547/// *P = v1; if () { *P = v2; }
1548/// into a phi node with a store in the successor.
1550 if (!SI.isUnordered())
1551 return false; // This code has not been audited for volatile/ordered case.
1552
1553 // Check if the successor block has exactly 2 incoming edges.
1554 BasicBlock *StoreBB = SI.getParent();
1555 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1556 if (!DestBB->hasNPredecessors(2))
1557 return false;
1558
1559 // Capture the other block (the block that doesn't contain our store).
1560 pred_iterator PredIter = pred_begin(DestBB);
1561 if (*PredIter == StoreBB)
1562 ++PredIter;
1563 BasicBlock *OtherBB = *PredIter;
1564
1565 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1566 // for example, if SI is in an infinite loop.
1567 if (StoreBB == DestBB || OtherBB == DestBB)
1568 return false;
1569
1570 // Verify that the other block ends in a branch and is not otherwise empty.
1571 BasicBlock::iterator BBI(OtherBB->getTerminator());
1572 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1573 if (!OtherBr || BBI == OtherBB->begin())
1574 return false;
1575
1576 // If the other block ends in an unconditional branch, check for the 'if then
1577 // else' case. There is an instruction before the branch.
1578 StoreInst *OtherStore = nullptr;
1579 if (OtherBr->isUnconditional()) {
1580 --BBI;
1581 // Skip over debugging info and pseudo probes.
1582 while (BBI->isDebugOrPseudoInst() ||
1583 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1584 if (BBI==OtherBB->begin())
1585 return false;
1586 --BBI;
1587 }
1588 // If this isn't a store, isn't a store to the same location, or is not the
1589 // right kind of store, bail out.
1590 OtherStore = dyn_cast<StoreInst>(BBI);
1591 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1592 !SI.isSameOperationAs(OtherStore))
1593 return false;
1594 } else {
1595 // Otherwise, the other block ended with a conditional branch. If one of the
1596 // destinations is StoreBB, then we have the if/then case.
1597 if (OtherBr->getSuccessor(0) != StoreBB &&
1598 OtherBr->getSuccessor(1) != StoreBB)
1599 return false;
1600
1601 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1602 // if/then triangle. See if there is a store to the same ptr as SI that
1603 // lives in OtherBB.
1604 for (;; --BBI) {
1605 // Check to see if we find the matching store.
1606 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1607 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1608 !SI.isSameOperationAs(OtherStore))
1609 return false;
1610 break;
1611 }
1612 // If we find something that may be using or overwriting the stored
1613 // value, or if we run out of instructions, we can't do the transform.
1614 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1615 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1616 return false;
1617 }
1618
1619 // In order to eliminate the store in OtherBr, we have to make sure nothing
1620 // reads or overwrites the stored value in StoreBB.
1621 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1622 // FIXME: This should really be AA driven.
1623 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1624 return false;
1625 }
1626 }
1627
1628 // Insert a PHI node now if we need it.
1629 Value *MergedVal = OtherStore->getOperand(0);
1630 // The debug locations of the original instructions might differ. Merge them.
1631 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1632 OtherStore->getDebugLoc());
1633 if (MergedVal != SI.getOperand(0)) {
1634 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1635 PN->addIncoming(SI.getOperand(0), SI.getParent());
1636 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1637 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1638 PN->setDebugLoc(MergedLoc);
1639 }
1640
1641 // Advance to a place where it is safe to insert the new store and insert it.
1642 BBI = DestBB->getFirstInsertionPt();
1643 StoreInst *NewSI =
1644 new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),
1645 SI.getOrdering(), SI.getSyncScopeID());
1646 InsertNewInstBefore(NewSI, *BBI);
1647 NewSI->setDebugLoc(MergedLoc);
1648 NewSI->mergeDIAssignID({&SI, OtherStore});
1649
1650 // If the two stores had AA tags, merge them.
1651 AAMDNodes AATags = SI.getAAMetadata();
1652 if (AATags)
1653 NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));
1654
1655 // Nuke the old stores.
1657 eraseInstFromFunction(*OtherStore);
1658 return true;
1659}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides internal interfaces used to implement the InstCombine.
static StoreInst * combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
static Instruction * combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &Load)
Combine loads to match the type of their uses' value after looking through intervening bitcasts.
static Instruction * simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI, DominatorTree &DT)
static Instruction * replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, T &MemI)
static bool canSimplifyNullStoreOrGEP(StoreInst &SI)
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op)
static bool isSupportedAtomicType(Type *Ty)
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL)
Returns true if V is dereferenceable for size of alloca.
static Instruction * unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI)
static cl::opt< unsigned > MaxCopiedFromConstantUsers("instcombine-max-copied-from-constant-users", cl::init(300), cl::desc("Maximum users to visit in copy from constant transform"), cl::Hidden)
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI)
static bool removeBitcastsFromLoadStoreOnMinMax(InstCombinerImpl &IC, StoreInst &SI)
Converts store (bitcast (load (bitcast (select ...)))) to store (load (select ...)),...
static Value * likeBitCastFromVector(InstCombinerImpl &IC, Value *V)
Look for extractelement/insertvalue sequence that acts like a bitcast.
static bool isMinMaxWithLoads(Value *V, Type *&LoadTy)
Returns true if instruction represent minmax pattern like: select ((cmp load V1, load V2),...
static bool isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete)
isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived) pointer to an alloca.
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
#define P(N)
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString 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:167
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition: blake3_impl.h:77
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
Class for arbitrary precision integers.
Definition: APInt.h:75
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:973
an instruction to allocate memory on the stack
Definition: Instructions.h:58
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:125
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:100
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:118
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:105
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
Definition: Instructions.h:129
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:96
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:314
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:245
const Instruction & front() const
Definition: BasicBlock.h:326
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition: BasicBlock.cpp:306
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:112
const Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition: BasicBlock.cpp:215
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
This class represents a no-op cast from one type to another.
Conditional or Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:718
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:136
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
static const DILocation * getMergedLocation(const DILocation *LocA, const DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
Definition: DataLayout.cpp:861
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:500
Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:857
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
const BasicBlock & getEntryBlock() const
Definition: Function.h:740
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:940
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Definition: Instructions.h:993
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Type * getSourceElementType() const
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:966
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1696
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2412
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1730
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2405
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1799
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:472
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2094
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2016
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1713
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2085
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1749
Instruction * visitLoadInst(LoadInst &LI)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitStoreInst(StoreInst &SI)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; } into a phi node...
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitAllocaInst(AllocaInst &AI)
const DataLayout & getDataLayout() const
Definition: InstCombiner.h:372
AAResults * AA
Definition: InstCombiner.h:67
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:418
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
Definition: InstCombiner.h:53
const SimplifyQuery SQ
Definition: InstCombiner.h:74
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:62
const DataLayout & DL
Definition: InstCombiner.h:73
static Value * peekThroughBitcast(Value *V, bool OneUseOnly=false)
Return the source operand of a potentially bitcasted value while optionally checking if it has one us...
Definition: InstCombiner.h:101
Instruction * InsertNewInstBefore(Instruction *New, Instruction &Old)
Inserts an instruction New before instruction Old.
Definition: InstCombiner.h:397
AssumptionCache & AC
Definition: InstCombiner.h:70
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:442
DominatorTree & DT
Definition: InstCombiner.h:72
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:461
BuilderTy & Builder
Definition: InstCombiner.h:58
void push(Instruction *I)
Push the instruction onto the worklist stack.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
Definition: DebugInfo.cpp:888
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:88
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:358
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1513
const BasicBlock * getParent() const
Definition: Instruction.h:90
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:74
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1455
AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1499
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:355
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
An instruction for reading from memory.
Definition: Instructions.h:177
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:270
void setAlignment(Align Align)
Definition: Instructions.h:224
Value * getPointerOperand()
Definition: Instructions.h:264
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
Definition: Instructions.h:250
bool isSimple() const
Definition: Instructions.h:256
Align getAlign() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:220
Metadata node.
Definition: Metadata.h:943
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:37
This class wraps the llvm.memcpy/memmove intrinsics.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1750
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
size_type size() const
Definition: SmallPtrSet.h:93
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:365
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:301
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:687
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
An instruction for storing to memory.
Definition: Instructions.h:301
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Definition: Instructions.h:376
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:304
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:264
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition: Type.h:204
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:246
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:231
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:532
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:182
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:166
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:163
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:716
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:772
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:89
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:136
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:406
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:1819
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition: Loads.cpp:201
void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition: Local.cpp:2744
void append_range(Container &C, Range &&R)
Wrapper function to append a range to a container.
Definition: STLExtras.h:2129
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition: Loads.cpp:435
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:1826
Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition: Local.cpp:1439
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:2140
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:109
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition: Local.cpp:2164
Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:2730
void replace(Container &Cont, typename Container::iterator ContIt, typename Container::iterator ContEnd, RandomAccessIterator ValIt, RandomAccessIterator ValEnd)
Given a sequence container Cont, replace the range [ContIt, ContEnd) with the range [ValIt,...
Definition: STLExtras.h:2136
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:332
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:651
AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:99
SimplifyQuery getWithInstruction(Instruction *I) const