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