1 //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass (at IR level) to replace atomic instructions with
10 // __atomic_* library calls, or target specific instruction which implement the
11 // same semantics in a way which better fits the target backend.  This can
12 // include the use of (intrinsic-based) load-linked/store-conditional loops,
13 // AtomicCmpXchg, or type coercions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/AtomicExpandUtils.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InstIterator.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/User.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/AtomicOrdering.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include <cassert>
50 #include <cstdint>
51 #include <iterator>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "atomic-expand"
56 
57 namespace {
58 
59   class AtomicExpand: public FunctionPass {
60     const TargetLowering *TLI = nullptr;
61 
62   public:
63     static char ID; // Pass identification, replacement for typeid
64 
65     AtomicExpand() : FunctionPass(ID) {
66       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
67     }
68 
69     bool runOnFunction(Function &F) override;
70 
71   private:
72     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
73     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
74     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
75     bool tryExpandAtomicLoad(LoadInst *LI);
76     bool expandAtomicLoadToLL(LoadInst *LI);
77     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
78     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
79     bool expandAtomicStore(StoreInst *SI);
80     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
81     AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
82     Value *
83     insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
84                       Align AddrAlign, AtomicOrdering MemOpOrder,
85                       function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
86     void expandAtomicOpToLLSC(
87         Instruction *I, Type *ResultTy, Value *Addr, Align AddrAlign,
88         AtomicOrdering MemOpOrder,
89         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
90     void expandPartwordAtomicRMW(
91         AtomicRMWInst *I,
92         TargetLoweringBase::AtomicExpansionKind ExpansionKind);
93     AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
94     bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
95     void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
96     void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
97 
98     AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
99     static Value *insertRMWCmpXchgLoop(
100         IRBuilder<> &Builder, Type *ResultType, Value *Addr, Align AddrAlign,
101         AtomicOrdering MemOpOrder, SyncScope::ID SSID,
102         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
103         CreateCmpXchgInstFun CreateCmpXchg);
104     bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
105 
106     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
107     bool isIdempotentRMW(AtomicRMWInst *RMWI);
108     bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
109 
110     bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
111                                  Value *PointerOperand, Value *ValueOperand,
112                                  Value *CASExpected, AtomicOrdering Ordering,
113                                  AtomicOrdering Ordering2,
114                                  ArrayRef<RTLIB::Libcall> Libcalls);
115     void expandAtomicLoadToLibcall(LoadInst *LI);
116     void expandAtomicStoreToLibcall(StoreInst *LI);
117     void expandAtomicRMWToLibcall(AtomicRMWInst *I);
118     void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
119 
120     friend bool
121     llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
122                                    CreateCmpXchgInstFun CreateCmpXchg);
123   };
124 
125 } // end anonymous namespace
126 
127 char AtomicExpand::ID = 0;
128 
129 char &llvm::AtomicExpandID = AtomicExpand::ID;
130 
131 INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions",
132                 false, false)
133 
134 FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
135 
136 // Helper functions to retrieve the size of atomic instructions.
137 static unsigned getAtomicOpSize(LoadInst *LI) {
138   const DataLayout &DL = LI->getModule()->getDataLayout();
139   return DL.getTypeStoreSize(LI->getType());
140 }
141 
142 static unsigned getAtomicOpSize(StoreInst *SI) {
143   const DataLayout &DL = SI->getModule()->getDataLayout();
144   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
145 }
146 
147 static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
148   const DataLayout &DL = RMWI->getModule()->getDataLayout();
149   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
150 }
151 
152 static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
153   const DataLayout &DL = CASI->getModule()->getDataLayout();
154   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
155 }
156 
157 // Determine if a particular atomic operation has a supported size,
158 // and is of appropriate alignment, to be passed through for target
159 // lowering. (Versus turning into a __atomic libcall)
160 template <typename Inst>
161 static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
162   unsigned Size = getAtomicOpSize(I);
163   Align Alignment = I->getAlign();
164   return Alignment >= Size &&
165          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
166 }
167 
168 bool AtomicExpand::runOnFunction(Function &F) {
169   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
170   if (!TPC)
171     return false;
172 
173   auto &TM = TPC->getTM<TargetMachine>();
174   if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
175     return false;
176   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
177 
178   SmallVector<Instruction *, 1> AtomicInsts;
179 
180   // Changing control-flow while iterating through it is a bad idea, so gather a
181   // list of all atomic instructions before we start.
182   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
183     Instruction *I = &*II;
184     if (I->isAtomic() && !isa<FenceInst>(I))
185       AtomicInsts.push_back(I);
186   }
187 
188   bool MadeChange = false;
189   for (auto I : AtomicInsts) {
190     auto LI = dyn_cast<LoadInst>(I);
191     auto SI = dyn_cast<StoreInst>(I);
192     auto RMWI = dyn_cast<AtomicRMWInst>(I);
193     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
194     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
195 
196     // If the Size/Alignment is not supported, replace with a libcall.
197     if (LI) {
198       if (!atomicSizeSupported(TLI, LI)) {
199         expandAtomicLoadToLibcall(LI);
200         MadeChange = true;
201         continue;
202       }
203     } else if (SI) {
204       if (!atomicSizeSupported(TLI, SI)) {
205         expandAtomicStoreToLibcall(SI);
206         MadeChange = true;
207         continue;
208       }
209     } else if (RMWI) {
210       if (!atomicSizeSupported(TLI, RMWI)) {
211         expandAtomicRMWToLibcall(RMWI);
212         MadeChange = true;
213         continue;
214       }
215     } else if (CASI) {
216       if (!atomicSizeSupported(TLI, CASI)) {
217         expandAtomicCASToLibcall(CASI);
218         MadeChange = true;
219         continue;
220       }
221     }
222 
223     if (TLI->shouldInsertFencesForAtomic(I)) {
224       auto FenceOrdering = AtomicOrdering::Monotonic;
225       if (LI && isAcquireOrStronger(LI->getOrdering())) {
226         FenceOrdering = LI->getOrdering();
227         LI->setOrdering(AtomicOrdering::Monotonic);
228       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
229         FenceOrdering = SI->getOrdering();
230         SI->setOrdering(AtomicOrdering::Monotonic);
231       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
232                           isAcquireOrStronger(RMWI->getOrdering()))) {
233         FenceOrdering = RMWI->getOrdering();
234         RMWI->setOrdering(AtomicOrdering::Monotonic);
235       } else if (CASI &&
236                  TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
237                      TargetLoweringBase::AtomicExpansionKind::None &&
238                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
239                   isAcquireOrStronger(CASI->getSuccessOrdering()) ||
240                   isAcquireOrStronger(CASI->getFailureOrdering()))) {
241         // If a compare and swap is lowered to LL/SC, we can do smarter fence
242         // insertion, with a stronger one on the success path than on the
243         // failure path. As a result, fence insertion is directly done by
244         // expandAtomicCmpXchg in that case.
245         FenceOrdering = CASI->getMergedOrdering();
246         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
247         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
248       }
249 
250       if (FenceOrdering != AtomicOrdering::Monotonic) {
251         MadeChange |= bracketInstWithFences(I, FenceOrdering);
252       }
253     }
254 
255     if (LI) {
256       if (LI->getType()->isFloatingPointTy()) {
257         // TODO: add a TLI hook to control this so that each target can
258         // convert to lowering the original type one at a time.
259         LI = convertAtomicLoadToIntegerType(LI);
260         assert(LI->getType()->isIntegerTy() && "invariant broken");
261         MadeChange = true;
262       }
263 
264       MadeChange |= tryExpandAtomicLoad(LI);
265     } else if (SI) {
266       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
267         // TODO: add a TLI hook to control this so that each target can
268         // convert to lowering the original type one at a time.
269         SI = convertAtomicStoreToIntegerType(SI);
270         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
271                "invariant broken");
272         MadeChange = true;
273       }
274 
275       if (TLI->shouldExpandAtomicStoreInIR(SI))
276         MadeChange |= expandAtomicStore(SI);
277     } else if (RMWI) {
278       // There are two different ways of expanding RMW instructions:
279       // - into a load if it is idempotent
280       // - into a Cmpxchg/LL-SC loop otherwise
281       // we try them in that order.
282 
283       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
284         MadeChange = true;
285       } else {
286         AtomicRMWInst::BinOp Op = RMWI->getOperation();
287         if (Op == AtomicRMWInst::Xchg &&
288             RMWI->getValOperand()->getType()->isFloatingPointTy()) {
289           // TODO: add a TLI hook to control this so that each target can
290           // convert to lowering the original type one at a time.
291           RMWI = convertAtomicXchgToIntegerType(RMWI);
292           assert(RMWI->getValOperand()->getType()->isIntegerTy() &&
293                  "invariant broken");
294           MadeChange = true;
295         }
296         unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
297         unsigned ValueSize = getAtomicOpSize(RMWI);
298         if (ValueSize < MinCASSize &&
299             (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
300              Op == AtomicRMWInst::And)) {
301           RMWI = widenPartwordAtomicRMW(RMWI);
302           MadeChange = true;
303         }
304 
305         MadeChange |= tryExpandAtomicRMW(RMWI);
306       }
307     } else if (CASI) {
308       // TODO: when we're ready to make the change at the IR level, we can
309       // extend convertCmpXchgToInteger for floating point too.
310       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
311              "unimplemented - floating point not legal at IR level");
312       if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
313         // TODO: add a TLI hook to control this so that each target can
314         // convert to lowering the original type one at a time.
315         CASI = convertCmpXchgToIntegerType(CASI);
316         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
317                "invariant broken");
318         MadeChange = true;
319       }
320 
321       MadeChange |= tryExpandAtomicCmpXchg(CASI);
322     }
323   }
324   return MadeChange;
325 }
326 
327 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
328   IRBuilder<> Builder(I);
329 
330   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
331 
332   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
333   // We have a guard here because not every atomic operation generates a
334   // trailing fence.
335   if (TrailingFence)
336     TrailingFence->moveAfter(I);
337 
338   return (LeadingFence || TrailingFence);
339 }
340 
341 /// Get the iX type with the same bitwidth as T.
342 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
343                                                        const DataLayout &DL) {
344   EVT VT = TLI->getMemValueType(DL, T);
345   unsigned BitWidth = VT.getStoreSizeInBits();
346   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
347   return IntegerType::get(T->getContext(), BitWidth);
348 }
349 
350 /// Convert an atomic load of a non-integral type to an integer load of the
351 /// equivalent bitwidth.  See the function comment on
352 /// convertAtomicStoreToIntegerType for background.
353 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
354   auto *M = LI->getModule();
355   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
356                                             M->getDataLayout());
357 
358   IRBuilder<> Builder(LI);
359 
360   Value *Addr = LI->getPointerOperand();
361   Type *PT = PointerType::get(NewTy,
362                               Addr->getType()->getPointerAddressSpace());
363   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
364 
365   auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
366   NewLI->setAlignment(LI->getAlign());
367   NewLI->setVolatile(LI->isVolatile());
368   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
369   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
370 
371   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
372   LI->replaceAllUsesWith(NewVal);
373   LI->eraseFromParent();
374   return NewLI;
375 }
376 
377 AtomicRMWInst *
378 AtomicExpand::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
379   auto *M = RMWI->getModule();
380   Type *NewTy =
381       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
382 
383   IRBuilder<> Builder(RMWI);
384 
385   Value *Addr = RMWI->getPointerOperand();
386   Value *Val = RMWI->getValOperand();
387   Type *PT = PointerType::get(NewTy, RMWI->getPointerAddressSpace());
388   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
389   Value *NewVal = Builder.CreateBitCast(Val, NewTy);
390 
391   auto *NewRMWI =
392       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, NewAddr, NewVal,
393                               RMWI->getAlign(), RMWI->getOrdering());
394   NewRMWI->setVolatile(RMWI->isVolatile());
395   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
396 
397   Value *NewRVal = Builder.CreateBitCast(NewRMWI, RMWI->getType());
398   RMWI->replaceAllUsesWith(NewRVal);
399   RMWI->eraseFromParent();
400   return NewRMWI;
401 }
402 
403 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
404   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
405   case TargetLoweringBase::AtomicExpansionKind::None:
406     return false;
407   case TargetLoweringBase::AtomicExpansionKind::LLSC:
408     expandAtomicOpToLLSC(
409         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
410         LI->getOrdering(),
411         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
412     return true;
413   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
414     return expandAtomicLoadToLL(LI);
415   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
416     return expandAtomicLoadToCmpXchg(LI);
417   default:
418     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
419   }
420 }
421 
422 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
423   IRBuilder<> Builder(LI);
424 
425   // On some architectures, load-linked instructions are atomic for larger
426   // sizes than normal loads. For example, the only 64-bit load guaranteed
427   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
428   Value *Val =
429       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
430   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
431 
432   LI->replaceAllUsesWith(Val);
433   LI->eraseFromParent();
434 
435   return true;
436 }
437 
438 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
439   IRBuilder<> Builder(LI);
440   AtomicOrdering Order = LI->getOrdering();
441   if (Order == AtomicOrdering::Unordered)
442     Order = AtomicOrdering::Monotonic;
443 
444   Value *Addr = LI->getPointerOperand();
445   Type *Ty = LI->getType();
446   Constant *DummyVal = Constant::getNullValue(Ty);
447 
448   Value *Pair = Builder.CreateAtomicCmpXchg(
449       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
450       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
451   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
452 
453   LI->replaceAllUsesWith(Loaded);
454   LI->eraseFromParent();
455 
456   return true;
457 }
458 
459 /// Convert an atomic store of a non-integral type to an integer store of the
460 /// equivalent bitwidth.  We used to not support floating point or vector
461 /// atomics in the IR at all.  The backends learned to deal with the bitcast
462 /// idiom because that was the only way of expressing the notion of a atomic
463 /// float or vector store.  The long term plan is to teach each backend to
464 /// instruction select from the original atomic store, but as a migration
465 /// mechanism, we convert back to the old format which the backends understand.
466 /// Each backend will need individual work to recognize the new format.
467 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
468   IRBuilder<> Builder(SI);
469   auto *M = SI->getModule();
470   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
471                                             M->getDataLayout());
472   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
473 
474   Value *Addr = SI->getPointerOperand();
475   Type *PT = PointerType::get(NewTy,
476                               Addr->getType()->getPointerAddressSpace());
477   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
478 
479   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
480   NewSI->setAlignment(SI->getAlign());
481   NewSI->setVolatile(SI->isVolatile());
482   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
483   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
484   SI->eraseFromParent();
485   return NewSI;
486 }
487 
488 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
489   // This function is only called on atomic stores that are too large to be
490   // atomic if implemented as a native store. So we replace them by an
491   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
492   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
493   // It is the responsibility of the target to only signal expansion via
494   // shouldExpandAtomicRMW in cases where this is required and possible.
495   IRBuilder<> Builder(SI);
496   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
497       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
498       SI->getAlign(), SI->getOrdering());
499   SI->eraseFromParent();
500 
501   // Now we have an appropriate swap instruction, lower it as usual.
502   return tryExpandAtomicRMW(AI);
503 }
504 
505 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
506                                  Value *Loaded, Value *NewVal, Align AddrAlign,
507                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
508                                  Value *&Success, Value *&NewLoaded) {
509   Type *OrigTy = NewVal->getType();
510 
511   // This code can go away when cmpxchg supports FP types.
512   bool NeedBitcast = OrigTy->isFloatingPointTy();
513   if (NeedBitcast) {
514     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
515     unsigned AS = Addr->getType()->getPointerAddressSpace();
516     Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
517     NewVal = Builder.CreateBitCast(NewVal, IntTy);
518     Loaded = Builder.CreateBitCast(Loaded, IntTy);
519   }
520 
521   Value *Pair = Builder.CreateAtomicCmpXchg(
522       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
523       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
524   Success = Builder.CreateExtractValue(Pair, 1, "success");
525   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
526 
527   if (NeedBitcast)
528     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
529 }
530 
531 /// Emit IR to implement the given atomicrmw operation on values in registers,
532 /// returning the new value.
533 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
534                               Value *Loaded, Value *Inc) {
535   Value *NewVal;
536   switch (Op) {
537   case AtomicRMWInst::Xchg:
538     return Inc;
539   case AtomicRMWInst::Add:
540     return Builder.CreateAdd(Loaded, Inc, "new");
541   case AtomicRMWInst::Sub:
542     return Builder.CreateSub(Loaded, Inc, "new");
543   case AtomicRMWInst::And:
544     return Builder.CreateAnd(Loaded, Inc, "new");
545   case AtomicRMWInst::Nand:
546     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
547   case AtomicRMWInst::Or:
548     return Builder.CreateOr(Loaded, Inc, "new");
549   case AtomicRMWInst::Xor:
550     return Builder.CreateXor(Loaded, Inc, "new");
551   case AtomicRMWInst::Max:
552     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
553     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
554   case AtomicRMWInst::Min:
555     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
556     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
557   case AtomicRMWInst::UMax:
558     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
559     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
560   case AtomicRMWInst::UMin:
561     NewVal = Builder.CreateICmpULE(Loaded, Inc);
562     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
563   case AtomicRMWInst::FAdd:
564     return Builder.CreateFAdd(Loaded, Inc, "new");
565   case AtomicRMWInst::FSub:
566     return Builder.CreateFSub(Loaded, Inc, "new");
567   default:
568     llvm_unreachable("Unknown atomic op");
569   }
570 }
571 
572 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
573   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
574   case TargetLoweringBase::AtomicExpansionKind::None:
575     return false;
576   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
577     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
578     unsigned ValueSize = getAtomicOpSize(AI);
579     if (ValueSize < MinCASSize) {
580       expandPartwordAtomicRMW(AI,
581                               TargetLoweringBase::AtomicExpansionKind::LLSC);
582     } else {
583       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
584         return performAtomicOp(AI->getOperation(), Builder, Loaded,
585                                AI->getValOperand());
586       };
587       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
588                            AI->getAlign(), AI->getOrdering(), PerformOp);
589     }
590     return true;
591   }
592   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
593     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
594     unsigned ValueSize = getAtomicOpSize(AI);
595     if (ValueSize < MinCASSize) {
596       // TODO: Handle atomicrmw fadd/fsub
597       if (AI->getType()->isFloatingPointTy())
598         return false;
599 
600       expandPartwordAtomicRMW(AI,
601                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
602     } else {
603       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
604     }
605     return true;
606   }
607   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
608     expandAtomicRMWToMaskedIntrinsic(AI);
609     return true;
610   }
611   default:
612     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
613   }
614 }
615 
616 namespace {
617 
618 struct PartwordMaskValues {
619   // These three fields are guaranteed to be set by createMaskInstrs.
620   Type *WordType = nullptr;
621   Type *ValueType = nullptr;
622   Value *AlignedAddr = nullptr;
623   Align AlignedAddrAlignment;
624   // The remaining fields can be null.
625   Value *ShiftAmt = nullptr;
626   Value *Mask = nullptr;
627   Value *Inv_Mask = nullptr;
628 };
629 
630 LLVM_ATTRIBUTE_UNUSED
631 raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
632   auto PrintObj = [&O](auto *V) {
633     if (V)
634       O << *V;
635     else
636       O << "nullptr";
637     O << '\n';
638   };
639   O << "PartwordMaskValues {\n";
640   O << "  WordType: ";
641   PrintObj(PMV.WordType);
642   O << "  ValueType: ";
643   PrintObj(PMV.ValueType);
644   O << "  AlignedAddr: ";
645   PrintObj(PMV.AlignedAddr);
646   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
647   O << "  ShiftAmt: ";
648   PrintObj(PMV.ShiftAmt);
649   O << "  Mask: ";
650   PrintObj(PMV.Mask);
651   O << "  Inv_Mask: ";
652   PrintObj(PMV.Inv_Mask);
653   O << "}\n";
654   return O;
655 }
656 
657 } // end anonymous namespace
658 
659 /// This is a helper function which builds instructions to provide
660 /// values necessary for partword atomic operations. It takes an
661 /// incoming address, Addr, and ValueType, and constructs the address,
662 /// shift-amounts and masks needed to work with a larger value of size
663 /// WordSize.
664 ///
665 /// AlignedAddr: Addr rounded down to a multiple of WordSize
666 ///
667 /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
668 ///           from AlignAddr for it to have the same value as if
669 ///           ValueType was loaded from Addr.
670 ///
671 /// Mask: Value to mask with the value loaded from AlignAddr to
672 ///       include only the part that would've been loaded from Addr.
673 ///
674 /// Inv_Mask: The inverse of Mask.
675 static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
676                                            Type *ValueType, Value *Addr,
677                                            Align AddrAlign,
678                                            unsigned MinWordSize) {
679   PartwordMaskValues PMV;
680 
681   Module *M = I->getModule();
682   LLVMContext &Ctx = M->getContext();
683   const DataLayout &DL = M->getDataLayout();
684   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
685 
686   PMV.ValueType = ValueType;
687   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
688                                          : ValueType;
689   if (PMV.ValueType == PMV.WordType) {
690     PMV.AlignedAddr = Addr;
691     PMV.AlignedAddrAlignment = AddrAlign;
692     return PMV;
693   }
694 
695   assert(ValueSize < MinWordSize);
696 
697   Type *WordPtrType =
698       PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
699 
700   // TODO: we could skip some of this if AddrAlign >= MinWordSize.
701   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
702   PMV.AlignedAddr = Builder.CreateIntToPtr(
703       Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
704       "AlignedAddr");
705   PMV.AlignedAddrAlignment = Align(MinWordSize);
706 
707   Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
708   if (DL.isLittleEndian()) {
709     // turn bytes into bits
710     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
711   } else {
712     // turn bytes into bits, and count from the other side.
713     PMV.ShiftAmt = Builder.CreateShl(
714         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
715   }
716 
717   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
718   PMV.Mask = Builder.CreateShl(
719       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
720       "Mask");
721   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
722   return PMV;
723 }
724 
725 static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
726                                  const PartwordMaskValues &PMV) {
727   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
728   if (PMV.WordType == PMV.ValueType)
729     return WideWord;
730 
731   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
732   Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
733   return Trunc;
734 }
735 
736 static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
737                                 Value *Updated, const PartwordMaskValues &PMV) {
738   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
739   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
740   if (PMV.WordType == PMV.ValueType)
741     return Updated;
742 
743   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
744   Value *Shift =
745       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
746   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
747   Value *Or = Builder.CreateOr(And, Shift, "inserted");
748   return Or;
749 }
750 
751 /// Emit IR to implement a masked version of a given atomicrmw
752 /// operation. (That is, only the bits under the Mask should be
753 /// affected by the operation)
754 static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
755                                     IRBuilder<> &Builder, Value *Loaded,
756                                     Value *Shifted_Inc, Value *Inc,
757                                     const PartwordMaskValues &PMV) {
758   // TODO: update to use
759   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
760   // to merge bits from two values without requiring PMV.Inv_Mask.
761   switch (Op) {
762   case AtomicRMWInst::Xchg: {
763     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
764     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
765     return FinalVal;
766   }
767   case AtomicRMWInst::Or:
768   case AtomicRMWInst::Xor:
769   case AtomicRMWInst::And:
770     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
771   case AtomicRMWInst::Add:
772   case AtomicRMWInst::Sub:
773   case AtomicRMWInst::Nand: {
774     // The other arithmetic ops need to be masked into place.
775     Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
776     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
777     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
778     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
779     return FinalVal;
780   }
781   case AtomicRMWInst::Max:
782   case AtomicRMWInst::Min:
783   case AtomicRMWInst::UMax:
784   case AtomicRMWInst::UMin: {
785     // Finally, comparison ops will operate on the full value, so
786     // truncate down to the original size, and expand out again after
787     // doing the operation.
788     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
789     Value *NewVal = performAtomicOp(Op, Builder, Loaded_Extract, Inc);
790     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
791     return FinalVal;
792   }
793   default:
794     llvm_unreachable("Unknown atomic op");
795   }
796 }
797 
798 /// Expand a sub-word atomicrmw operation into an appropriate
799 /// word-sized operation.
800 ///
801 /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
802 /// way as a typical atomicrmw expansion. The only difference here is
803 /// that the operation inside of the loop may operate upon only a
804 /// part of the value.
805 void AtomicExpand::expandPartwordAtomicRMW(
806     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
807   AtomicOrdering MemOpOrder = AI->getOrdering();
808   SyncScope::ID SSID = AI->getSyncScopeID();
809 
810   IRBuilder<> Builder(AI);
811 
812   PartwordMaskValues PMV =
813       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
814                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
815 
816   Value *ValOperand_Shifted =
817       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
818                         PMV.ShiftAmt, "ValOperand_Shifted");
819 
820   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
821     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
822                                  ValOperand_Shifted, AI->getValOperand(), PMV);
823   };
824 
825   Value *OldResult;
826   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
827     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
828                                      PMV.AlignedAddrAlignment, MemOpOrder,
829                                      SSID, PerformPartwordOp,
830                                      createCmpXchgInstFun);
831   } else {
832     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
833     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
834                                   PMV.AlignedAddrAlignment, MemOpOrder,
835                                   PerformPartwordOp);
836   }
837 
838   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
839   AI->replaceAllUsesWith(FinalOldResult);
840   AI->eraseFromParent();
841 }
842 
843 // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
844 AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
845   IRBuilder<> Builder(AI);
846   AtomicRMWInst::BinOp Op = AI->getOperation();
847 
848   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
849           Op == AtomicRMWInst::And) &&
850          "Unable to widen operation");
851 
852   PartwordMaskValues PMV =
853       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
854                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
855 
856   Value *ValOperand_Shifted =
857       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
858                         PMV.ShiftAmt, "ValOperand_Shifted");
859 
860   Value *NewOperand;
861 
862   if (Op == AtomicRMWInst::And)
863     NewOperand =
864         Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
865   else
866     NewOperand = ValOperand_Shifted;
867 
868   AtomicRMWInst *NewAI =
869       Builder.CreateAtomicRMW(Op, PMV.AlignedAddr, NewOperand,
870                               PMV.AlignedAddrAlignment, AI->getOrdering());
871 
872   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
873   AI->replaceAllUsesWith(FinalOldResult);
874   AI->eraseFromParent();
875   return NewAI;
876 }
877 
878 bool AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
879   // The basic idea here is that we're expanding a cmpxchg of a
880   // smaller memory size up to a word-sized cmpxchg. To do this, we
881   // need to add a retry-loop for strong cmpxchg, so that
882   // modifications to other parts of the word don't cause a spurious
883   // failure.
884 
885   // This generates code like the following:
886   //     [[Setup mask values PMV.*]]
887   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
888   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
889   //     %InitLoaded = load i32* %addr
890   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
891   //     br partword.cmpxchg.loop
892   // partword.cmpxchg.loop:
893   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
894   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
895   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
896   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
897   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
898   //        i32 %FullWord_NewVal success_ordering failure_ordering
899   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
900   //     %Success = extractvalue { i32, i1 } %NewCI, 1
901   //     br i1 %Success, label %partword.cmpxchg.end,
902   //        label %partword.cmpxchg.failure
903   // partword.cmpxchg.failure:
904   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
905   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
906   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
907   //         label %partword.cmpxchg.end
908   // partword.cmpxchg.end:
909   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
910   //    %FinalOldVal = trunc i32 %tmp1 to i8
911   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
912   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
913 
914   Value *Addr = CI->getPointerOperand();
915   Value *Cmp = CI->getCompareOperand();
916   Value *NewVal = CI->getNewValOperand();
917 
918   BasicBlock *BB = CI->getParent();
919   Function *F = BB->getParent();
920   IRBuilder<> Builder(CI);
921   LLVMContext &Ctx = Builder.getContext();
922 
923   BasicBlock *EndBB =
924       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
925   auto FailureBB =
926       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
927   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
928 
929   // The split call above "helpfully" added a branch at the end of BB
930   // (to the wrong place).
931   std::prev(BB->end())->eraseFromParent();
932   Builder.SetInsertPoint(BB);
933 
934   PartwordMaskValues PMV =
935       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
936                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
937 
938   // Shift the incoming values over, into the right location in the word.
939   Value *NewVal_Shifted =
940       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
941   Value *Cmp_Shifted =
942       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
943 
944   // Load the entire current word, and mask into place the expected and new
945   // values
946   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
947   InitLoaded->setVolatile(CI->isVolatile());
948   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
949   Builder.CreateBr(LoopBB);
950 
951   // partword.cmpxchg.loop:
952   Builder.SetInsertPoint(LoopBB);
953   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
954   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
955 
956   // Mask/Or the expected and new values into place in the loaded word.
957   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
958   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
959   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
960       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
961       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
962   NewCI->setVolatile(CI->isVolatile());
963   // When we're building a strong cmpxchg, we need a loop, so you
964   // might think we could use a weak cmpxchg inside. But, using strong
965   // allows the below comparison for ShouldContinue, and we're
966   // expecting the underlying cmpxchg to be a machine instruction,
967   // which is strong anyways.
968   NewCI->setWeak(CI->isWeak());
969 
970   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
971   Value *Success = Builder.CreateExtractValue(NewCI, 1);
972 
973   if (CI->isWeak())
974     Builder.CreateBr(EndBB);
975   else
976     Builder.CreateCondBr(Success, EndBB, FailureBB);
977 
978   // partword.cmpxchg.failure:
979   Builder.SetInsertPoint(FailureBB);
980   // Upon failure, verify that the masked-out part of the loaded value
981   // has been modified.  If it didn't, abort the cmpxchg, since the
982   // masked-in part must've.
983   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
984   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
985   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
986 
987   // Add the second value to the phi from above
988   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
989 
990   // partword.cmpxchg.end:
991   Builder.SetInsertPoint(CI);
992 
993   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
994   Value *Res = UndefValue::get(CI->getType());
995   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
996   Res = Builder.CreateInsertValue(Res, Success, 1);
997 
998   CI->replaceAllUsesWith(Res);
999   CI->eraseFromParent();
1000   return true;
1001 }
1002 
1003 void AtomicExpand::expandAtomicOpToLLSC(
1004     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
1005     AtomicOrdering MemOpOrder,
1006     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1007   IRBuilder<> Builder(I);
1008   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
1009                                     MemOpOrder, PerformOp);
1010 
1011   I->replaceAllUsesWith(Loaded);
1012   I->eraseFromParent();
1013 }
1014 
1015 void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
1016   IRBuilder<> Builder(AI);
1017 
1018   PartwordMaskValues PMV =
1019       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1020                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1021 
1022   // The value operand must be sign-extended for signed min/max so that the
1023   // target's signed comparison instructions can be used. Otherwise, just
1024   // zero-ext.
1025   Instruction::CastOps CastOp = Instruction::ZExt;
1026   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
1027   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
1028     CastOp = Instruction::SExt;
1029 
1030   Value *ValOperand_Shifted = Builder.CreateShl(
1031       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
1032       PMV.ShiftAmt, "ValOperand_Shifted");
1033   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
1034       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
1035       AI->getOrdering());
1036   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
1037   AI->replaceAllUsesWith(FinalOldResult);
1038   AI->eraseFromParent();
1039 }
1040 
1041 void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
1042   IRBuilder<> Builder(CI);
1043 
1044   PartwordMaskValues PMV = createMaskInstrs(
1045       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1046       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1047 
1048   Value *CmpVal_Shifted = Builder.CreateShl(
1049       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
1050       "CmpVal_Shifted");
1051   Value *NewVal_Shifted = Builder.CreateShl(
1052       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
1053       "NewVal_Shifted");
1054   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
1055       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
1056       CI->getMergedOrdering());
1057   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1058   Value *Res = UndefValue::get(CI->getType());
1059   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1060   Value *Success = Builder.CreateICmpEQ(
1061       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
1062   Res = Builder.CreateInsertValue(Res, Success, 1);
1063 
1064   CI->replaceAllUsesWith(Res);
1065   CI->eraseFromParent();
1066 }
1067 
1068 Value *AtomicExpand::insertRMWLLSCLoop(
1069     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1070     AtomicOrdering MemOpOrder,
1071     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1072   LLVMContext &Ctx = Builder.getContext();
1073   BasicBlock *BB = Builder.GetInsertBlock();
1074   Function *F = BB->getParent();
1075 
1076   assert(AddrAlign >=
1077              F->getParent()->getDataLayout().getTypeStoreSize(ResultTy) &&
1078          "Expected at least natural alignment at this point.");
1079 
1080   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1081   //
1082   // The standard expansion we produce is:
1083   //     [...]
1084   // atomicrmw.start:
1085   //     %loaded = @load.linked(%addr)
1086   //     %new = some_op iN %loaded, %incr
1087   //     %stored = @store_conditional(%new, %addr)
1088   //     %try_again = icmp i32 ne %stored, 0
1089   //     br i1 %try_again, label %loop, label %atomicrmw.end
1090   // atomicrmw.end:
1091   //     [...]
1092   BasicBlock *ExitBB =
1093       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1094   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1095 
1096   // The split call above "helpfully" added a branch at the end of BB (to the
1097   // wrong place).
1098   std::prev(BB->end())->eraseFromParent();
1099   Builder.SetInsertPoint(BB);
1100   Builder.CreateBr(LoopBB);
1101 
1102   // Start the main loop block now that we've taken care of the preliminaries.
1103   Builder.SetInsertPoint(LoopBB);
1104   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1105 
1106   Value *NewVal = PerformOp(Builder, Loaded);
1107 
1108   Value *StoreSuccess =
1109       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
1110   Value *TryAgain = Builder.CreateICmpNE(
1111       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1112   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1113 
1114   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1115   return Loaded;
1116 }
1117 
1118 /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
1119 /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
1120 /// IR.  As a migration step, we convert back to what use to be the standard
1121 /// way to represent a pointer cmpxchg so that we can update backends one by
1122 /// one.
1123 AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
1124   auto *M = CI->getModule();
1125   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
1126                                             M->getDataLayout());
1127 
1128   IRBuilder<> Builder(CI);
1129 
1130   Value *Addr = CI->getPointerOperand();
1131   Type *PT = PointerType::get(NewTy,
1132                               Addr->getType()->getPointerAddressSpace());
1133   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1134 
1135   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
1136   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
1137 
1138   auto *NewCI = Builder.CreateAtomicCmpXchg(
1139       NewAddr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
1140       CI->getFailureOrdering(), CI->getSyncScopeID());
1141   NewCI->setVolatile(CI->isVolatile());
1142   NewCI->setWeak(CI->isWeak());
1143   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
1144 
1145   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1146   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
1147 
1148   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
1149 
1150   Value *Res = UndefValue::get(CI->getType());
1151   Res = Builder.CreateInsertValue(Res, OldVal, 0);
1152   Res = Builder.CreateInsertValue(Res, Succ, 1);
1153 
1154   CI->replaceAllUsesWith(Res);
1155   CI->eraseFromParent();
1156   return NewCI;
1157 }
1158 
1159 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1160   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1161   AtomicOrdering FailureOrder = CI->getFailureOrdering();
1162   Value *Addr = CI->getPointerOperand();
1163   BasicBlock *BB = CI->getParent();
1164   Function *F = BB->getParent();
1165   LLVMContext &Ctx = F->getContext();
1166   // If shouldInsertFencesForAtomic() returns true, then the target does not
1167   // want to deal with memory orders, and emitLeading/TrailingFence should take
1168   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1169   // should preserve the ordering.
1170   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
1171   AtomicOrdering MemOpOrder = ShouldInsertFencesForAtomic
1172                                   ? AtomicOrdering::Monotonic
1173                                   : CI->getMergedOrdering();
1174 
1175   // In implementations which use a barrier to achieve release semantics, we can
1176   // delay emitting this barrier until we know a store is actually going to be
1177   // attempted. The cost of this delay is that we need 2 copies of the block
1178   // emitting the load-linked, affecting code size.
1179   //
1180   // Ideally, this logic would be unconditional except for the minsize check
1181   // since in other cases the extra blocks naturally collapse down to the
1182   // minimal loop. Unfortunately, this puts too much stress on later
1183   // optimisations so we avoid emitting the extra logic in those cases too.
1184   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
1185                            SuccessOrder != AtomicOrdering::Monotonic &&
1186                            SuccessOrder != AtomicOrdering::Acquire &&
1187                            !F->hasMinSize();
1188 
1189   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1190   // do it even on minsize.
1191   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
1192 
1193   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1194   //
1195   // The full expansion we produce is:
1196   //     [...]
1197   // %aligned.addr = ...
1198   // cmpxchg.start:
1199   //     %unreleasedload = @load.linked(%aligned.addr)
1200   //     %unreleasedload.extract = extract value from %unreleasedload
1201   //     %should_store = icmp eq %unreleasedload.extract, %desired
1202   //     br i1 %should_store, label %cmpxchg.releasingstore,
1203   //                          label %cmpxchg.nostore
1204   // cmpxchg.releasingstore:
1205   //     fence?
1206   //     br label cmpxchg.trystore
1207   // cmpxchg.trystore:
1208   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
1209   //                            [%releasedload, %cmpxchg.releasedload]
1210   //     %updated.new = insert %new into %loaded.trystore
1211   //     %stored = @store_conditional(%updated.new, %aligned.addr)
1212   //     %success = icmp eq i32 %stored, 0
1213   //     br i1 %success, label %cmpxchg.success,
1214   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1215   // cmpxchg.releasedload:
1216   //     %releasedload = @load.linked(%aligned.addr)
1217   //     %releasedload.extract = extract value from %releasedload
1218   //     %should_store = icmp eq %releasedload.extract, %desired
1219   //     br i1 %should_store, label %cmpxchg.trystore,
1220   //                          label %cmpxchg.failure
1221   // cmpxchg.success:
1222   //     fence?
1223   //     br label %cmpxchg.end
1224   // cmpxchg.nostore:
1225   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1226   //                           [%releasedload,
1227   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
1228   //     @load_linked_fail_balance()?
1229   //     br label %cmpxchg.failure
1230   // cmpxchg.failure:
1231   //     fence?
1232   //     br label %cmpxchg.end
1233   // cmpxchg.end:
1234   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1235   //                        [%loaded.trystore, %cmpxchg.trystore]
1236   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1237   //     %loaded = extract value from %loaded.exit
1238   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1239   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1240   //     [...]
1241   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1242   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1243   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1244   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1245   auto ReleasedLoadBB =
1246       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1247   auto TryStoreBB =
1248       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1249   auto ReleasingStoreBB =
1250       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1251   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
1252 
1253   // This grabs the DebugLoc from CI
1254   IRBuilder<> Builder(CI);
1255 
1256   // The split call above "helpfully" added a branch at the end of BB (to the
1257   // wrong place), but we might want a fence too. It's easiest to just remove
1258   // the branch entirely.
1259   std::prev(BB->end())->eraseFromParent();
1260   Builder.SetInsertPoint(BB);
1261   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
1262     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1263 
1264   PartwordMaskValues PMV =
1265       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1266                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1267   Builder.CreateBr(StartBB);
1268 
1269   // Start the main loop block now that we've taken care of the preliminaries.
1270   Builder.SetInsertPoint(StartBB);
1271   Value *UnreleasedLoad =
1272       TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1273   Value *UnreleasedLoadExtract =
1274       extractMaskedValue(Builder, UnreleasedLoad, PMV);
1275   Value *ShouldStore = Builder.CreateICmpEQ(
1276       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
1277 
1278   // If the cmpxchg doesn't actually need any ordering when it fails, we can
1279   // jump straight past that fence instruction (if it exists).
1280   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1281 
1282   Builder.SetInsertPoint(ReleasingStoreBB);
1283   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
1284     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1285   Builder.CreateBr(TryStoreBB);
1286 
1287   Builder.SetInsertPoint(TryStoreBB);
1288   PHINode *LoadedTryStore =
1289       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1290   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1291   Value *NewValueInsert =
1292       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1293   Value *StoreSuccess =
1294       TLI->emitStoreConditional(Builder, NewValueInsert, PMV.AlignedAddr,
1295                                 MemOpOrder);
1296   StoreSuccess = Builder.CreateICmpEQ(
1297       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1298   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
1299   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1300                        CI->isWeak() ? FailureBB : RetryBB);
1301 
1302   Builder.SetInsertPoint(ReleasedLoadBB);
1303   Value *SecondLoad;
1304   if (HasReleasedLoadBB) {
1305     SecondLoad = TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1306     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1307     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1308                                        CI->getCompareOperand(), "should_store");
1309 
1310     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1311     // jump straight past that fence instruction (if it exists).
1312     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1313     // Update PHI node in TryStoreBB.
1314     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
1315   } else
1316     Builder.CreateUnreachable();
1317 
1318   // Make sure later instructions don't get reordered with a fence if
1319   // necessary.
1320   Builder.SetInsertPoint(SuccessBB);
1321   if (ShouldInsertFencesForAtomic)
1322     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
1323   Builder.CreateBr(ExitBB);
1324 
1325   Builder.SetInsertPoint(NoStoreBB);
1326   PHINode *LoadedNoStore =
1327       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1328   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1329   if (HasReleasedLoadBB)
1330     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1331 
1332   // In the failing case, where we don't execute the store-conditional, the
1333   // target might want to balance out the load-linked with a dedicated
1334   // instruction (e.g., on ARM, clearing the exclusive monitor).
1335   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1336   Builder.CreateBr(FailureBB);
1337 
1338   Builder.SetInsertPoint(FailureBB);
1339   PHINode *LoadedFailure =
1340       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1341   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1342   if (CI->isWeak())
1343     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
1344   if (ShouldInsertFencesForAtomic)
1345     TLI->emitTrailingFence(Builder, CI, FailureOrder);
1346   Builder.CreateBr(ExitBB);
1347 
1348   // Finally, we have control-flow based knowledge of whether the cmpxchg
1349   // succeeded or not. We expose this to later passes by converting any
1350   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1351   // PHI.
1352   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1353   PHINode *LoadedExit =
1354       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1355   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1356   LoadedExit->addIncoming(LoadedFailure, FailureBB);
1357   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
1358   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1359   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1360 
1361   // This is the "exit value" from the cmpxchg expansion. It may be of
1362   // a type wider than the one in the cmpxchg instruction.
1363   Value *LoadedFull = LoadedExit;
1364 
1365   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1366   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
1367 
1368   // Look for any users of the cmpxchg that are just comparing the loaded value
1369   // against the desired one, and replace them with the CFG-derived version.
1370   SmallVector<ExtractValueInst *, 2> PrunedInsts;
1371   for (auto User : CI->users()) {
1372     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1373     if (!EV)
1374       continue;
1375 
1376     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1377            "weird extraction from { iN, i1 }");
1378 
1379     if (EV->getIndices()[0] == 0)
1380       EV->replaceAllUsesWith(Loaded);
1381     else
1382       EV->replaceAllUsesWith(Success);
1383 
1384     PrunedInsts.push_back(EV);
1385   }
1386 
1387   // We can remove the instructions now we're no longer iterating through them.
1388   for (auto EV : PrunedInsts)
1389     EV->eraseFromParent();
1390 
1391   if (!CI->use_empty()) {
1392     // Some use of the full struct return that we don't understand has happened,
1393     // so we've got to reconstruct it properly.
1394     Value *Res;
1395     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1396     Res = Builder.CreateInsertValue(Res, Success, 1);
1397 
1398     CI->replaceAllUsesWith(Res);
1399   }
1400 
1401   CI->eraseFromParent();
1402   return true;
1403 }
1404 
1405 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
1406   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1407   if(!C)
1408     return false;
1409 
1410   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1411   switch(Op) {
1412     case AtomicRMWInst::Add:
1413     case AtomicRMWInst::Sub:
1414     case AtomicRMWInst::Or:
1415     case AtomicRMWInst::Xor:
1416       return C->isZero();
1417     case AtomicRMWInst::And:
1418       return C->isMinusOne();
1419     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1420     default:
1421       return false;
1422   }
1423 }
1424 
1425 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
1426   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1427     tryExpandAtomicLoad(ResultingLoad);
1428     return true;
1429   }
1430   return false;
1431 }
1432 
1433 Value *AtomicExpand::insertRMWCmpXchgLoop(
1434     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1435     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
1436     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1437     CreateCmpXchgInstFun CreateCmpXchg) {
1438   LLVMContext &Ctx = Builder.getContext();
1439   BasicBlock *BB = Builder.GetInsertBlock();
1440   Function *F = BB->getParent();
1441 
1442   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1443   //
1444   // The standard expansion we produce is:
1445   //     [...]
1446   //     %init_loaded = load atomic iN* %addr
1447   //     br label %loop
1448   // loop:
1449   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1450   //     %new = some_op iN %loaded, %incr
1451   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1452   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1453   //     %success = extractvalue { iN, i1 } %pair, 1
1454   //     br i1 %success, label %atomicrmw.end, label %loop
1455   // atomicrmw.end:
1456   //     [...]
1457   BasicBlock *ExitBB =
1458       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1459   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1460 
1461   // The split call above "helpfully" added a branch at the end of BB (to the
1462   // wrong place), but we want a load. It's easiest to just remove
1463   // the branch entirely.
1464   std::prev(BB->end())->eraseFromParent();
1465   Builder.SetInsertPoint(BB);
1466   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
1467   Builder.CreateBr(LoopBB);
1468 
1469   // Start the main loop block now that we've taken care of the preliminaries.
1470   Builder.SetInsertPoint(LoopBB);
1471   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1472   Loaded->addIncoming(InitLoaded, BB);
1473 
1474   Value *NewVal = PerformOp(Builder, Loaded);
1475 
1476   Value *NewLoaded = nullptr;
1477   Value *Success = nullptr;
1478 
1479   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
1480                 MemOpOrder == AtomicOrdering::Unordered
1481                     ? AtomicOrdering::Monotonic
1482                     : MemOpOrder,
1483                 SSID, Success, NewLoaded);
1484   assert(Success && NewLoaded);
1485 
1486   Loaded->addIncoming(NewLoaded, LoopBB);
1487 
1488   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1489 
1490   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1491   return NewLoaded;
1492 }
1493 
1494 bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1495   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1496   unsigned ValueSize = getAtomicOpSize(CI);
1497 
1498   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1499   default:
1500     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1501   case TargetLoweringBase::AtomicExpansionKind::None:
1502     if (ValueSize < MinCASSize)
1503       return expandPartwordCmpXchg(CI);
1504     return false;
1505   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
1506     return expandAtomicCmpXchg(CI);
1507   }
1508   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
1509     expandAtomicCmpXchgToMaskedIntrinsic(CI);
1510     return true;
1511   }
1512 }
1513 
1514 // Note: This function is exposed externally by AtomicExpandUtils.h
1515 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1516                                     CreateCmpXchgInstFun CreateCmpXchg) {
1517   IRBuilder<> Builder(AI);
1518   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1519       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1520       AI->getOrdering(), AI->getSyncScopeID(),
1521       [&](IRBuilder<> &Builder, Value *Loaded) {
1522         return performAtomicOp(AI->getOperation(), Builder, Loaded,
1523                                AI->getValOperand());
1524       },
1525       CreateCmpXchg);
1526 
1527   AI->replaceAllUsesWith(Loaded);
1528   AI->eraseFromParent();
1529   return true;
1530 }
1531 
1532 // In order to use one of the sized library calls such as
1533 // __atomic_fetch_add_4, the alignment must be sufficient, the size
1534 // must be one of the potentially-specialized sizes, and the value
1535 // type must actually exist in C on the target (otherwise, the
1536 // function wouldn't actually be defined.)
1537 static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
1538                                   const DataLayout &DL) {
1539   // TODO: "LargestSize" is an approximation for "largest type that
1540   // you can express in C". It seems to be the case that int128 is
1541   // supported on all 64-bit platforms, otherwise only up to 64-bit
1542   // integers are supported. If we get this wrong, then we'll try to
1543   // call a sized libcall that doesn't actually exist. There should
1544   // really be some more reliable way in LLVM of determining integer
1545   // sizes which are valid in the target's C ABI...
1546   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1547   return Alignment >= Size &&
1548          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1549          Size <= LargestSize;
1550 }
1551 
1552 void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
1553   static const RTLIB::Libcall Libcalls[6] = {
1554       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1555       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1556   unsigned Size = getAtomicOpSize(I);
1557 
1558   bool expanded = expandAtomicOpToLibcall(
1559       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
1560       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1561   if (!expanded)
1562     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
1563 }
1564 
1565 void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
1566   static const RTLIB::Libcall Libcalls[6] = {
1567       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1568       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1569   unsigned Size = getAtomicOpSize(I);
1570 
1571   bool expanded = expandAtomicOpToLibcall(
1572       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1573       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1574   if (!expanded)
1575     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
1576 }
1577 
1578 void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1579   static const RTLIB::Libcall Libcalls[6] = {
1580       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1581       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1582       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1583   unsigned Size = getAtomicOpSize(I);
1584 
1585   bool expanded = expandAtomicOpToLibcall(
1586       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
1587       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1588       Libcalls);
1589   if (!expanded)
1590     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
1591 }
1592 
1593 static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1594   static const RTLIB::Libcall LibcallsXchg[6] = {
1595       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1596       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1597       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1598   static const RTLIB::Libcall LibcallsAdd[6] = {
1599       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1600       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1601       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1602   static const RTLIB::Libcall LibcallsSub[6] = {
1603       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1604       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1605       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1606   static const RTLIB::Libcall LibcallsAnd[6] = {
1607       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1608       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1609       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1610   static const RTLIB::Libcall LibcallsOr[6] = {
1611       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1612       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1613       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1614   static const RTLIB::Libcall LibcallsXor[6] = {
1615       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1616       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1617       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1618   static const RTLIB::Libcall LibcallsNand[6] = {
1619       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1620       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1621       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1622 
1623   switch (Op) {
1624   case AtomicRMWInst::BAD_BINOP:
1625     llvm_unreachable("Should not have BAD_BINOP.");
1626   case AtomicRMWInst::Xchg:
1627     return makeArrayRef(LibcallsXchg);
1628   case AtomicRMWInst::Add:
1629     return makeArrayRef(LibcallsAdd);
1630   case AtomicRMWInst::Sub:
1631     return makeArrayRef(LibcallsSub);
1632   case AtomicRMWInst::And:
1633     return makeArrayRef(LibcallsAnd);
1634   case AtomicRMWInst::Or:
1635     return makeArrayRef(LibcallsOr);
1636   case AtomicRMWInst::Xor:
1637     return makeArrayRef(LibcallsXor);
1638   case AtomicRMWInst::Nand:
1639     return makeArrayRef(LibcallsNand);
1640   case AtomicRMWInst::Max:
1641   case AtomicRMWInst::Min:
1642   case AtomicRMWInst::UMax:
1643   case AtomicRMWInst::UMin:
1644   case AtomicRMWInst::FAdd:
1645   case AtomicRMWInst::FSub:
1646     // No atomic libcalls are available for max/min/umax/umin.
1647     return {};
1648   }
1649   llvm_unreachable("Unexpected AtomicRMW operation.");
1650 }
1651 
1652 void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1653   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1654 
1655   unsigned Size = getAtomicOpSize(I);
1656 
1657   bool Success = false;
1658   if (!Libcalls.empty())
1659     Success = expandAtomicOpToLibcall(
1660         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1661         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1662 
1663   // The expansion failed: either there were no libcalls at all for
1664   // the operation (min/max), or there were only size-specialized
1665   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1666   // CAS libcall, via a CAS loop, instead.
1667   if (!Success) {
1668     expandAtomicRMWToCmpXchg(
1669         I, [this](IRBuilder<> &Builder, Value *Addr, Value *Loaded,
1670                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1671                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
1672           // Create the CAS instruction normally...
1673           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1674               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1675               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
1676           Success = Builder.CreateExtractValue(Pair, 1, "success");
1677           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1678 
1679           // ...and then expand the CAS into a libcall.
1680           expandAtomicCASToLibcall(Pair);
1681         });
1682   }
1683 }
1684 
1685 // A helper routine for the above expandAtomic*ToLibcall functions.
1686 //
1687 // 'Libcalls' contains an array of enum values for the particular
1688 // ATOMIC libcalls to be emitted. All of the other arguments besides
1689 // 'I' are extracted from the Instruction subclass by the
1690 // caller. Depending on the particular call, some will be null.
1691 bool AtomicExpand::expandAtomicOpToLibcall(
1692     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
1693     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1694     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1695   assert(Libcalls.size() == 6);
1696 
1697   LLVMContext &Ctx = I->getContext();
1698   Module *M = I->getModule();
1699   const DataLayout &DL = M->getDataLayout();
1700   IRBuilder<> Builder(I);
1701   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1702 
1703   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
1704   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1705 
1706   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
1707 
1708   // TODO: the "order" argument type is "int", not int32. So
1709   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1710   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1711   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1712   Constant *OrderingVal =
1713       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1714   Constant *Ordering2Val = nullptr;
1715   if (CASExpected) {
1716     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1717     Ordering2Val =
1718         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1719   }
1720   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1721 
1722   RTLIB::Libcall RTLibType;
1723   if (UseSizedLibcall) {
1724     switch (Size) {
1725     case 1: RTLibType = Libcalls[1]; break;
1726     case 2: RTLibType = Libcalls[2]; break;
1727     case 4: RTLibType = Libcalls[3]; break;
1728     case 8: RTLibType = Libcalls[4]; break;
1729     case 16: RTLibType = Libcalls[5]; break;
1730     }
1731   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1732     RTLibType = Libcalls[0];
1733   } else {
1734     // Can't use sized function, and there's no generic for this
1735     // operation, so give up.
1736     return false;
1737   }
1738 
1739   if (!TLI->getLibcallName(RTLibType)) {
1740     // This target does not implement the requested atomic libcall so give up.
1741     return false;
1742   }
1743 
1744   // Build up the function call. There's two kinds. First, the sized
1745   // variants.  These calls are going to be one of the following (with
1746   // N=1,2,4,8,16):
1747   //  iN    __atomic_load_N(iN *ptr, int ordering)
1748   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1749   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1750   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1751   //                                    int success_order, int failure_order)
1752   //
1753   // Note that these functions can be used for non-integer atomic
1754   // operations, the values just need to be bitcast to integers on the
1755   // way in and out.
1756   //
1757   // And, then, the generic variants. They look like the following:
1758   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1759   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1760   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1761   //                          int ordering)
1762   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1763   //                                  void *desired, int success_order,
1764   //                                  int failure_order)
1765   //
1766   // The different signatures are built up depending on the
1767   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1768   // variables.
1769 
1770   AllocaInst *AllocaCASExpected = nullptr;
1771   Value *AllocaCASExpected_i8 = nullptr;
1772   AllocaInst *AllocaValue = nullptr;
1773   Value *AllocaValue_i8 = nullptr;
1774   AllocaInst *AllocaResult = nullptr;
1775   Value *AllocaResult_i8 = nullptr;
1776 
1777   Type *ResultTy;
1778   SmallVector<Value *, 6> Args;
1779   AttributeList Attr;
1780 
1781   // 'size' argument.
1782   if (!UseSizedLibcall) {
1783     // Note, getIntPtrType is assumed equivalent to size_t.
1784     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1785   }
1786 
1787   // 'ptr' argument.
1788   // note: This assumes all address spaces share a common libfunc
1789   // implementation and that addresses are convertable.  For systems without
1790   // that property, we'd need to extend this mechanism to support AS-specific
1791   // families of atomic intrinsics.
1792   auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
1793   Value *PtrVal = Builder.CreateBitCast(PointerOperand,
1794                                         Type::getInt8PtrTy(Ctx, PtrTypeAS));
1795   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
1796   Args.push_back(PtrVal);
1797 
1798   // 'expected' argument, if present.
1799   if (CASExpected) {
1800     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1801     AllocaCASExpected->setAlignment(AllocaAlignment);
1802     unsigned AllocaAS =  AllocaCASExpected->getType()->getPointerAddressSpace();
1803 
1804     AllocaCASExpected_i8 =
1805       Builder.CreateBitCast(AllocaCASExpected,
1806                             Type::getInt8PtrTy(Ctx, AllocaAS));
1807     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
1808     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1809     Args.push_back(AllocaCASExpected_i8);
1810   }
1811 
1812   // 'val' argument ('desired' for cas), if present.
1813   if (ValueOperand) {
1814     if (UseSizedLibcall) {
1815       Value *IntValue =
1816           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1817       Args.push_back(IntValue);
1818     } else {
1819       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1820       AllocaValue->setAlignment(AllocaAlignment);
1821       AllocaValue_i8 =
1822           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
1823       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
1824       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1825       Args.push_back(AllocaValue_i8);
1826     }
1827   }
1828 
1829   // 'ret' argument.
1830   if (!CASExpected && HasResult && !UseSizedLibcall) {
1831     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1832     AllocaResult->setAlignment(AllocaAlignment);
1833     unsigned AllocaAS =  AllocaResult->getType()->getPointerAddressSpace();
1834     AllocaResult_i8 =
1835       Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
1836     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
1837     Args.push_back(AllocaResult_i8);
1838   }
1839 
1840   // 'ordering' ('success_order' for cas) argument.
1841   Args.push_back(OrderingVal);
1842 
1843   // 'failure_order' argument, if present.
1844   if (Ordering2Val)
1845     Args.push_back(Ordering2Val);
1846 
1847   // Now, the return type.
1848   if (CASExpected) {
1849     ResultTy = Type::getInt1Ty(Ctx);
1850     Attr = Attr.addAttribute(Ctx, AttributeList::ReturnIndex, Attribute::ZExt);
1851   } else if (HasResult && UseSizedLibcall)
1852     ResultTy = SizedIntTy;
1853   else
1854     ResultTy = Type::getVoidTy(Ctx);
1855 
1856   // Done with setting up arguments and return types, create the call:
1857   SmallVector<Type *, 6> ArgTys;
1858   for (Value *Arg : Args)
1859     ArgTys.push_back(Arg->getType());
1860   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
1861   FunctionCallee LibcallFn =
1862       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
1863   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
1864   Call->setAttributes(Attr);
1865   Value *Result = Call;
1866 
1867   // And then, extract the results...
1868   if (ValueOperand && !UseSizedLibcall)
1869     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
1870 
1871   if (CASExpected) {
1872     // The final result from the CAS is {load of 'expected' alloca, bool result
1873     // from call}
1874     Type *FinalResultTy = I->getType();
1875     Value *V = UndefValue::get(FinalResultTy);
1876     Value *ExpectedOut = Builder.CreateAlignedLoad(
1877         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
1878     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
1879     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
1880     V = Builder.CreateInsertValue(V, Result, 1);
1881     I->replaceAllUsesWith(V);
1882   } else if (HasResult) {
1883     Value *V;
1884     if (UseSizedLibcall)
1885       V = Builder.CreateBitOrPointerCast(Result, I->getType());
1886     else {
1887       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
1888                                     AllocaAlignment);
1889       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
1890     }
1891     I->replaceAllUsesWith(V);
1892   }
1893   I->eraseFromParent();
1894   return true;
1895 }
1896