Don't taint relaxed loads that immediately comes before an AcqRel read-modify-write op
[oota-llvm.git] / lib / CodeGen / AtomicExpandPass.cpp
1 //===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass (at IR level) to replace atomic instructions with
11 // target specific instruction which implement the same semantics in a way
12 // which better fits the target backend.  This can include the use of either
13 // (intrinsic-based) load-linked/store-conditional loops, AtomicCmpXchg, or
14 // type coercions.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/MemoryLocation.h"
23 #include "llvm/CodeGen/AtomicExpandUtils.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstIterator.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/NoFolder.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38
39 using namespace llvm;
40
41 #define DEBUG_TYPE "atomic-expand"
42
43 namespace {
44   class AtomicExpand: public FunctionPass {
45     const TargetMachine *TM;
46     const TargetLowering *TLI;
47   public:
48     static char ID; // Pass identification, replacement for typeid
49     explicit AtomicExpand(const TargetMachine *TM = nullptr)
50       : FunctionPass(ID), TM(TM), TLI(nullptr) {
51       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
52     }
53
54     bool runOnFunction(Function &F) override;
55
56   private:
57     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
58                                bool IsStore, bool IsLoad);
59     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
60     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
61     bool tryExpandAtomicLoad(LoadInst *LI);
62     bool expandAtomicLoadToLL(LoadInst *LI);
63     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
64     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
65     bool expandAtomicStore(StoreInst *SI);
66     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
67     bool expandAtomicOpToLLSC(
68         Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
69         std::function<Value *(IRBuilder<> &, Value *)> PerformOp);
70     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
71     bool isIdempotentRMW(AtomicRMWInst *AI);
72     bool simplifyIdempotentRMW(AtomicRMWInst *AI);
73   };
74
75
76   // If 'LI' is a relaxed load, and it is immediately followed by a
77 // atomic read-modify-write that has acq_rel parameter, we don't have to do
78 // anything since the rmw serves as a natural barrier.
79 void MarkRelaxedLoadBeforeAcqrelRMW(LoadInst* LI) {
80   auto* BB = LI->getParent();
81   auto BBI = LI->getIterator();
82   for (BBI++; BBI != BB->end(); BBI++) {
83     Instruction* CurInst = &*BBI;
84     if (!CurInst) {
85       return;
86     }
87     if (!CurInst->isAtomic()) {
88       continue;
89     }
90     auto* RMW = dyn_cast<AtomicRMWInst>(CurInst);
91     if (!RMW) {
92       return;
93     }
94     if (RMW->getOrdering() == AcquireRelease ||
95         RMW->getOrdering() == SequentiallyConsistent) {
96       LI->setHasSubsequentAcqlRMW(true);
97     }
98   }
99 }
100
101 }
102
103 char AtomicExpand::ID = 0;
104 char &llvm::AtomicExpandID = AtomicExpand::ID;
105 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
106     "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
107     false, false)
108
109 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
110   return new AtomicExpand(TM);
111 }
112
113 bool AtomicExpand::runOnFunction(Function &F) {
114   if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
115     return false;
116   TLI = TM->getSubtargetImpl(F)->getTargetLowering();
117
118   SmallVector<Instruction *, 1> AtomicInsts;
119   SmallVector<LoadInst*, 1> MonotonicLoadInsts;
120
121   // Changing control-flow while iterating through it is a bad idea, so gather a
122   // list of all atomic instructions before we start.
123   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
124     // XXX-update: For relaxed loads, change them to acquire. This includes
125     // relaxed loads, relaxed atomic RMW & relaxed atomic compare exchange.
126     if (I->isAtomic()) {
127       switch (I->getOpcode()) {
128         case Instruction::AtomicCmpXchg: {
129           // XXX-comment: AtomicCmpXchg in AArch64 will be translated to a
130           // conditional branch that contains the value of the load anyway, so
131           // we don't need to do anything.
132           /*
133           auto* CmpXchg = dyn_cast<AtomicCmpXchgInst>(&*I);
134           auto SuccOrdering = CmpXchg->getSuccessOrdering();
135           if (SuccOrdering == Monotonic) {
136             CmpXchg->setSuccessOrdering(Acquire);
137           } else if (SuccOrdering == Release) {
138             CmpXchg->setSuccessOrdering(AcquireRelease);
139           }
140           */
141           break;
142         }
143         case Instruction::AtomicRMW: {
144           // XXX-comment: Similar to AtomicCmpXchg. These instructions in
145           // AArch64 will be translated to a loop whose condition depends on the
146           // store status, which further depends on the load value.
147           /*
148           auto* RMW = dyn_cast<AtomicRMWInst>(&*I);
149           if (RMW->getOrdering() == Monotonic) {
150             RMW->setOrdering(Acquire);
151           }
152           */
153           break;
154         }
155         case Instruction::Load: {
156           auto* LI = dyn_cast<LoadInst>(&*I);
157           if (LI->getOrdering() == Monotonic) {
158             /*
159             DEBUG(dbgs() << "Transforming relaxed loads to acquire loads: "
160                          << *LI << '\n');
161             LI->setOrdering(Acquire);
162             */
163 //            MonotonicLoadInsts.push_back(LI);
164             MarkRelaxedLoadBeforeAcqrelRMW(LI);
165           }
166           break;
167         }
168         default: {
169           break;
170         }
171       }
172       AtomicInsts.push_back(&*I);
173     }
174   }
175
176   bool MadeChange = false;
177   for (auto I : AtomicInsts) {
178     auto LI = dyn_cast<LoadInst>(I);
179     auto SI = dyn_cast<StoreInst>(I);
180     auto RMWI = dyn_cast<AtomicRMWInst>(I);
181     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
182     assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
183            "Unknown atomic instruction");
184
185     auto FenceOrdering = Monotonic;
186     bool IsStore, IsLoad;
187     if (TLI->getInsertFencesForAtomic()) {
188       if (LI && isAtLeastAcquire(LI->getOrdering())) {
189         FenceOrdering = LI->getOrdering();
190 //        AddFakeConditionalBranch(
191         IsStore = false;
192         IsLoad = true;
193       } else if (SI && isAtLeastRelease(SI->getOrdering())) {
194         FenceOrdering = SI->getOrdering();
195         SI->setOrdering(Monotonic);
196         IsStore = true;
197         IsLoad = false;
198       } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
199                           isAtLeastAcquire(RMWI->getOrdering()))) {
200         FenceOrdering = RMWI->getOrdering();
201         RMWI->setOrdering(Monotonic);
202         IsStore = IsLoad = true;
203       } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
204                  (isAtLeastRelease(CASI->getSuccessOrdering()) ||
205                   isAtLeastAcquire(CASI->getSuccessOrdering()))) {
206         // If a compare and swap is lowered to LL/SC, we can do smarter fence
207         // insertion, with a stronger one on the success path than on the
208         // failure path. As a result, fence insertion is directly done by
209         // expandAtomicCmpXchg in that case.
210         FenceOrdering = CASI->getSuccessOrdering();
211         CASI->setSuccessOrdering(Monotonic);
212         CASI->setFailureOrdering(Monotonic);
213         IsStore = IsLoad = true;
214       }
215
216       if (FenceOrdering != Monotonic) {
217         MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
218       }
219     }
220
221     if (LI) {
222       if (LI->getType()->isFloatingPointTy()) {
223         // TODO: add a TLI hook to control this so that each target can
224         // convert to lowering the original type one at a time.
225         LI = convertAtomicLoadToIntegerType(LI);
226         assert(LI->getType()->isIntegerTy() && "invariant broken");
227         MadeChange = true;
228       }
229       
230       MadeChange |= tryExpandAtomicLoad(LI);
231     } else if (SI) {
232       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
233         // TODO: add a TLI hook to control this so that each target can
234         // convert to lowering the original type one at a time.
235         SI = convertAtomicStoreToIntegerType(SI);
236         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
237                "invariant broken");
238         MadeChange = true;
239       }
240
241       if (TLI->shouldExpandAtomicStoreInIR(SI))
242         MadeChange |= expandAtomicStore(SI);
243     } else if (RMWI) {
244       // There are two different ways of expanding RMW instructions:
245       // - into a load if it is idempotent
246       // - into a Cmpxchg/LL-SC loop otherwise
247       // we try them in that order.
248
249       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
250         MadeChange = true;
251       } else {
252         MadeChange |= tryExpandAtomicRMW(RMWI);
253       }
254     } else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI)) {
255       MadeChange |= expandAtomicCmpXchg(CASI);
256     }
257   }
258
259   return MadeChange;
260 }
261
262 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
263                                          bool IsStore, bool IsLoad) {
264   IRBuilder<> Builder(I);
265
266   auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
267
268   auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
269   // The trailing fence is emitted before the instruction instead of after
270   // because there is no easy way of setting Builder insertion point after
271   // an instruction. So we must erase it from the BB, and insert it back
272   // in the right place.
273   // We have a guard here because not every atomic operation generates a
274   // trailing fence.
275   if (TrailingFence) {
276     TrailingFence->removeFromParent();
277     TrailingFence->insertAfter(I);
278   }
279
280   return (LeadingFence || TrailingFence);
281 }
282
283 /// Get the iX type with the same bitwidth as T.
284 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
285                                                        const DataLayout &DL) {
286   EVT VT = TLI->getValueType(DL, T);
287   unsigned BitWidth = VT.getStoreSizeInBits();
288   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
289   return IntegerType::get(T->getContext(), BitWidth);
290 }
291
292 /// Convert an atomic load of a non-integral type to an integer load of the
293 /// equivelent bitwidth.  See the function comment on
294 /// convertAtomicStoreToIntegerType for background.  
295 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
296   auto *M = LI->getModule();
297   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
298                                             M->getDataLayout());
299
300   IRBuilder<> Builder(LI);
301   
302   Value *Addr = LI->getPointerOperand();
303   Type *PT = PointerType::get(NewTy,
304                               Addr->getType()->getPointerAddressSpace());
305   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
306   
307   auto *NewLI = Builder.CreateLoad(NewAddr);
308   NewLI->setAlignment(LI->getAlignment());
309   NewLI->setVolatile(LI->isVolatile());
310   NewLI->setAtomic(LI->getOrdering(), LI->getSynchScope());
311   DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
312   
313   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
314   LI->replaceAllUsesWith(NewVal);
315   LI->eraseFromParent();
316   return NewLI;
317 }
318
319 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
320   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
321   case TargetLoweringBase::AtomicExpansionKind::None:
322     return false;
323   case TargetLoweringBase::AtomicExpansionKind::LLSC:
324     return expandAtomicOpToLLSC(
325         LI, LI->getPointerOperand(), LI->getOrdering(),
326         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
327   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
328     return expandAtomicLoadToLL(LI);
329   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
330     return expandAtomicLoadToCmpXchg(LI);
331   }
332   llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
333 }
334
335 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
336   IRBuilder<> Builder(LI);
337
338   // On some architectures, load-linked instructions are atomic for larger
339   // sizes than normal loads. For example, the only 64-bit load guaranteed
340   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
341   Value *Val =
342       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
343   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
344
345   LI->replaceAllUsesWith(Val);
346   LI->eraseFromParent();
347
348   return true;
349 }
350
351 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
352   IRBuilder<> Builder(LI);
353   AtomicOrdering Order = LI->getOrdering();
354   Value *Addr = LI->getPointerOperand();
355   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
356   Constant *DummyVal = Constant::getNullValue(Ty);
357
358   Value *Pair = Builder.CreateAtomicCmpXchg(
359       Addr, DummyVal, DummyVal, Order,
360       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
361   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
362
363   LI->replaceAllUsesWith(Loaded);
364   LI->eraseFromParent();
365
366   return true;
367 }
368
369 /// Convert an atomic store of a non-integral type to an integer store of the
370 /// equivelent bitwidth.  We used to not support floating point or vector
371 /// atomics in the IR at all.  The backends learned to deal with the bitcast
372 /// idiom because that was the only way of expressing the notion of a atomic
373 /// float or vector store.  The long term plan is to teach each backend to
374 /// instruction select from the original atomic store, but as a migration
375 /// mechanism, we convert back to the old format which the backends understand.
376 /// Each backend will need individual work to recognize the new format.
377 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
378   IRBuilder<> Builder(SI);
379   auto *M = SI->getModule();
380   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
381                                             M->getDataLayout());
382   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
383   
384   Value *Addr = SI->getPointerOperand();
385   Type *PT = PointerType::get(NewTy,
386                               Addr->getType()->getPointerAddressSpace());
387   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
388
389   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
390   NewSI->setAlignment(SI->getAlignment());
391   NewSI->setVolatile(SI->isVolatile());
392   NewSI->setAtomic(SI->getOrdering(), SI->getSynchScope());
393   DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
394   SI->eraseFromParent();
395   return NewSI;
396 }
397
398 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
399   // This function is only called on atomic stores that are too large to be
400   // atomic if implemented as a native store. So we replace them by an
401   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
402   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
403   // It is the responsibility of the target to only signal expansion via
404   // shouldExpandAtomicRMW in cases where this is required and possible.
405   IRBuilder<> Builder(SI);
406   AtomicRMWInst *AI =
407       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
408                               SI->getValueOperand(), SI->getOrdering());
409   SI->eraseFromParent();
410
411   // Now we have an appropriate swap instruction, lower it as usual.
412   return tryExpandAtomicRMW(AI);
413 }
414
415 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
416                                  Value *Loaded, Value *NewVal,
417                                  AtomicOrdering MemOpOrder,
418                                  Value *&Success, Value *&NewLoaded) {
419   Value* Pair = Builder.CreateAtomicCmpXchg(
420       Addr, Loaded, NewVal, MemOpOrder,
421       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
422   Success = Builder.CreateExtractValue(Pair, 1, "success");
423   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
424 }
425
426 /// Emit IR to implement the given atomicrmw operation on values in registers,
427 /// returning the new value.
428 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
429                               Value *Loaded, Value *Inc) {
430   Value *NewVal;
431   switch (Op) {
432   case AtomicRMWInst::Xchg:
433     return Inc;
434   case AtomicRMWInst::Add:
435     return Builder.CreateAdd(Loaded, Inc, "new");
436   case AtomicRMWInst::Sub:
437     return Builder.CreateSub(Loaded, Inc, "new");
438   case AtomicRMWInst::And:
439     return Builder.CreateAnd(Loaded, Inc, "new");
440   case AtomicRMWInst::Nand:
441     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
442   case AtomicRMWInst::Or:
443     return Builder.CreateOr(Loaded, Inc, "new");
444   case AtomicRMWInst::Xor:
445     return Builder.CreateXor(Loaded, Inc, "new");
446   case AtomicRMWInst::Max:
447     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
448     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
449   case AtomicRMWInst::Min:
450     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
451     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
452   case AtomicRMWInst::UMax:
453     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
454     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
455   case AtomicRMWInst::UMin:
456     NewVal = Builder.CreateICmpULE(Loaded, Inc);
457     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
458   default:
459     llvm_unreachable("Unknown atomic op");
460   }
461 }
462
463 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
464   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
465   case TargetLoweringBase::AtomicExpansionKind::None:
466     return false;
467   case TargetLoweringBase::AtomicExpansionKind::LLSC:
468     return expandAtomicOpToLLSC(AI, AI->getPointerOperand(), AI->getOrdering(),
469                                 [&](IRBuilder<> &Builder, Value *Loaded) {
470                                   return performAtomicOp(AI->getOperation(),
471                                                          Builder, Loaded,
472                                                          AI->getValOperand());
473                                 });
474   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
475     return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
476   default:
477     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
478   }
479 }
480
481 bool AtomicExpand::expandAtomicOpToLLSC(
482     Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
483     std::function<Value *(IRBuilder<> &, Value *)> PerformOp) {
484   BasicBlock *BB = I->getParent();
485   Function *F = BB->getParent();
486   LLVMContext &Ctx = F->getContext();
487
488   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
489   //
490   // The standard expansion we produce is:
491   //     [...]
492   //     fence?
493   // atomicrmw.start:
494   //     %loaded = @load.linked(%addr)
495   //     %new = some_op iN %loaded, %incr
496   //     %stored = @store_conditional(%new, %addr)
497   //     %try_again = icmp i32 ne %stored, 0
498   //     br i1 %try_again, label %loop, label %atomicrmw.end
499   // atomicrmw.end:
500   //     fence?
501   //     [...]
502   BasicBlock *ExitBB = BB->splitBasicBlock(I->getIterator(), "atomicrmw.end");
503   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
504
505   // This grabs the DebugLoc from I.
506   IRBuilder<> Builder(I);
507
508   // The split call above "helpfully" added a branch at the end of BB (to the
509   // wrong place), but we might want a fence too. It's easiest to just remove
510   // the branch entirely.
511   std::prev(BB->end())->eraseFromParent();
512   Builder.SetInsertPoint(BB);
513   Builder.CreateBr(LoopBB);
514
515   // Start the main loop block now that we've taken care of the preliminaries.
516   Builder.SetInsertPoint(LoopBB);
517   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
518
519   Value *NewVal = PerformOp(Builder, Loaded);
520
521   Value *StoreSuccess =
522       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
523   Value *TryAgain = Builder.CreateICmpNE(
524       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
525   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
526
527   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
528
529   I->replaceAllUsesWith(Loaded);
530   I->eraseFromParent();
531
532   return true;
533 }
534
535 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
536   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
537   AtomicOrdering FailureOrder = CI->getFailureOrdering();
538   Value *Addr = CI->getPointerOperand();
539   BasicBlock *BB = CI->getParent();
540   Function *F = BB->getParent();
541   LLVMContext &Ctx = F->getContext();
542   // If getInsertFencesForAtomic() returns true, then the target does not want
543   // to deal with memory orders, and emitLeading/TrailingFence should take care
544   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
545   // should preserve the ordering.
546   AtomicOrdering MemOpOrder =
547       TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
548
549   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
550   //
551   // The full expansion we produce is:
552   //     [...]
553   //     fence?
554   // cmpxchg.start:
555   //     %loaded = @load.linked(%addr)
556   //     %should_store = icmp eq %loaded, %desired
557   //     br i1 %should_store, label %cmpxchg.trystore,
558   //                          label %cmpxchg.nostore
559   // cmpxchg.trystore:
560   //     %stored = @store_conditional(%new, %addr)
561   //     %success = icmp eq i32 %stored, 0
562   //     br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
563   // cmpxchg.success:
564   //     fence?
565   //     br label %cmpxchg.end
566   // cmpxchg.nostore:
567   //     @load_linked_fail_balance()?
568   //     br label %cmpxchg.failure
569   // cmpxchg.failure:
570   //     fence?
571   //     br label %cmpxchg.end
572   // cmpxchg.end:
573   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
574   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
575   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
576   //     [...]
577   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
578   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
579   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
580   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
581   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
582   auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
583
584   // This grabs the DebugLoc from CI
585   IRBuilder<> Builder(CI);
586
587   // The split call above "helpfully" added a branch at the end of BB (to the
588   // wrong place), but we might want a fence too. It's easiest to just remove
589   // the branch entirely.
590   std::prev(BB->end())->eraseFromParent();
591   Builder.SetInsertPoint(BB);
592   TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
593                         /*IsLoad=*/true);
594   Builder.CreateBr(LoopBB);
595
596   // Start the main loop block now that we've taken care of the preliminaries.
597   Builder.SetInsertPoint(LoopBB);
598   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
599   Value *ShouldStore =
600       Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
601
602   // If the cmpxchg doesn't actually need any ordering when it fails, we can
603   // jump straight past that fence instruction (if it exists).
604   Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
605
606   Builder.SetInsertPoint(TryStoreBB);
607   Value *StoreSuccess = TLI->emitStoreConditional(
608       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
609   StoreSuccess = Builder.CreateICmpEQ(
610       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
611   Builder.CreateCondBr(StoreSuccess, SuccessBB,
612                        CI->isWeak() ? FailureBB : LoopBB);
613
614   // Make sure later instructions don't get reordered with a fence if necessary.
615   Builder.SetInsertPoint(SuccessBB);
616   TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
617                          /*IsLoad=*/true);
618   Builder.CreateBr(ExitBB);
619
620   Builder.SetInsertPoint(NoStoreBB);
621   // In the failing case, where we don't execute the store-conditional, the
622   // target might want to balance out the load-linked with a dedicated
623   // instruction (e.g., on ARM, clearing the exclusive monitor).
624   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
625   Builder.CreateBr(FailureBB);
626
627   Builder.SetInsertPoint(FailureBB);
628   TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
629                          /*IsLoad=*/true);
630   Builder.CreateBr(ExitBB);
631
632   // Finally, we have control-flow based knowledge of whether the cmpxchg
633   // succeeded or not. We expose this to later passes by converting any
634   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
635
636   // Setup the builder so we can create any PHIs we need.
637   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
638   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
639   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
640   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
641
642   // Look for any users of the cmpxchg that are just comparing the loaded value
643   // against the desired one, and replace them with the CFG-derived version.
644   SmallVector<ExtractValueInst *, 2> PrunedInsts;
645   for (auto User : CI->users()) {
646     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
647     if (!EV)
648       continue;
649
650     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
651            "weird extraction from { iN, i1 }");
652
653     if (EV->getIndices()[0] == 0)
654       EV->replaceAllUsesWith(Loaded);
655     else
656       EV->replaceAllUsesWith(Success);
657
658     PrunedInsts.push_back(EV);
659   }
660
661   // We can remove the instructions now we're no longer iterating through them.
662   for (auto EV : PrunedInsts)
663     EV->eraseFromParent();
664
665   if (!CI->use_empty()) {
666     // Some use of the full struct return that we don't understand has happened,
667     // so we've got to reconstruct it properly.
668     Value *Res;
669     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
670     Res = Builder.CreateInsertValue(Res, Success, 1);
671
672     CI->replaceAllUsesWith(Res);
673   }
674
675   CI->eraseFromParent();
676   return true;
677 }
678
679 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
680   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
681   if(!C)
682     return false;
683
684   AtomicRMWInst::BinOp Op = RMWI->getOperation();
685   switch(Op) {
686     case AtomicRMWInst::Add:
687     case AtomicRMWInst::Sub:
688     case AtomicRMWInst::Or:
689     case AtomicRMWInst::Xor:
690       return C->isZero();
691     case AtomicRMWInst::And:
692       return C->isMinusOne();
693     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
694     default:
695       return false;
696   }
697 }
698
699 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
700   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
701     tryExpandAtomicLoad(ResultingLoad);
702     return true;
703   }
704   return false;
705 }
706
707 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
708                                     CreateCmpXchgInstFun CreateCmpXchg) {
709   assert(AI);
710
711   AtomicOrdering MemOpOrder =
712       AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
713   Value *Addr = AI->getPointerOperand();
714   BasicBlock *BB = AI->getParent();
715   Function *F = BB->getParent();
716   LLVMContext &Ctx = F->getContext();
717
718   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
719   //
720   // The standard expansion we produce is:
721   //     [...]
722   //     %init_loaded = load atomic iN* %addr
723   //     br label %loop
724   // loop:
725   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
726   //     %new = some_op iN %loaded, %incr
727   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
728   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
729   //     %success = extractvalue { iN, i1 } %pair, 1
730   //     br i1 %success, label %atomicrmw.end, label %loop
731   // atomicrmw.end:
732   //     [...]
733   BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
734   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
735
736   // This grabs the DebugLoc from AI.
737   IRBuilder<> Builder(AI);
738
739   // The split call above "helpfully" added a branch at the end of BB (to the
740   // wrong place), but we want a load. It's easiest to just remove
741   // the branch entirely.
742   std::prev(BB->end())->eraseFromParent();
743   Builder.SetInsertPoint(BB);
744   LoadInst *InitLoaded = Builder.CreateLoad(Addr);
745   // Atomics require at least natural alignment.
746   InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits() / 8);
747   Builder.CreateBr(LoopBB);
748
749   // Start the main loop block now that we've taken care of the preliminaries.
750   Builder.SetInsertPoint(LoopBB);
751   PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
752   Loaded->addIncoming(InitLoaded, BB);
753
754   Value *NewVal =
755       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
756
757   Value *NewLoaded = nullptr;
758   Value *Success = nullptr;
759
760   CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
761                 Success, NewLoaded);
762   assert(Success && NewLoaded);
763
764   Loaded->addIncoming(NewLoaded, LoopBB);
765
766   Builder.CreateCondBr(Success, ExitBB, LoopBB);
767
768   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
769
770   AI->replaceAllUsesWith(NewLoaded);
771   AI->eraseFromParent();
772
773   return true;
774 }