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