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