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