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