LLVM API Documentation

AtomicExpandPass.cpp
Go to the documentation of this file.
00001 //===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a pass (at IR level) to replace atomic instructions with
00011 // either (intrinsic-based) ldrex/strex loops or AtomicCmpXchg.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/Passes.h"
00016 #include "llvm/IR/Function.h"
00017 #include "llvm/IR/IRBuilder.h"
00018 #include "llvm/IR/InstIterator.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/IR/Intrinsics.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/Support/Debug.h"
00023 #include "llvm/Target/TargetLowering.h"
00024 #include "llvm/Target/TargetMachine.h"
00025 #include "llvm/Target/TargetSubtargetInfo.h"
00026 
00027 using namespace llvm;
00028 
00029 #define DEBUG_TYPE "atomic-expand"
00030 
00031 namespace {
00032   class AtomicExpand: public FunctionPass {
00033     const TargetMachine *TM;
00034   public:
00035     static char ID; // Pass identification, replacement for typeid
00036     explicit AtomicExpand(const TargetMachine *TM = nullptr)
00037       : FunctionPass(ID), TM(TM) {
00038       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
00039     }
00040 
00041     bool runOnFunction(Function &F) override;
00042 
00043   private:
00044     bool expandAtomicLoad(LoadInst *LI);
00045     bool expandAtomicStore(StoreInst *SI);
00046     bool expandAtomicRMW(AtomicRMWInst *AI);
00047     bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
00048     bool expandAtomicRMWToCmpXchg(AtomicRMWInst *AI);
00049     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
00050   };
00051 }
00052 
00053 char AtomicExpand::ID = 0;
00054 char &llvm::AtomicExpandID = AtomicExpand::ID;
00055 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
00056     "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
00057     false, false)
00058 
00059 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
00060   return new AtomicExpand(TM);
00061 }
00062 
00063 bool AtomicExpand::runOnFunction(Function &F) {
00064   if (!TM || !TM->getSubtargetImpl()->enableAtomicExpand())
00065     return false;
00066   auto TargetLowering = TM->getSubtargetImpl()->getTargetLowering();
00067 
00068   SmallVector<Instruction *, 1> AtomicInsts;
00069 
00070   // Changing control-flow while iterating through it is a bad idea, so gather a
00071   // list of all atomic instructions before we start.
00072   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
00073     if (I->isAtomic())
00074       AtomicInsts.push_back(&*I);
00075   }
00076 
00077   bool MadeChange = false;
00078   for (auto I : AtomicInsts) {
00079     auto LI = dyn_cast<LoadInst>(I);
00080     auto SI = dyn_cast<StoreInst>(I);
00081     auto RMWI = dyn_cast<AtomicRMWInst>(I);
00082     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
00083 
00084     assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
00085            "Unknown atomic instruction");
00086 
00087     if (LI && TargetLowering->shouldExpandAtomicLoadInIR(LI)) {
00088       MadeChange |= expandAtomicLoad(LI);
00089     } else if (SI && TargetLowering->shouldExpandAtomicStoreInIR(SI)) {
00090       MadeChange |= expandAtomicStore(SI);
00091     } else if (RMWI && TargetLowering->shouldExpandAtomicRMWInIR(RMWI)) {
00092       MadeChange |= expandAtomicRMW(RMWI);
00093     } else if (CASI && TargetLowering->hasLoadLinkedStoreConditional()) {
00094       MadeChange |= expandAtomicCmpXchg(CASI);
00095     }
00096   }
00097   return MadeChange;
00098 }
00099 
00100 bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
00101   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
00102   // If getInsertFencesForAtomic() returns true, then the target does not want
00103   // to deal with memory orders, and emitLeading/TrailingFence should take care
00104   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
00105   // should preserve the ordering.
00106   AtomicOrdering MemOpOrder =
00107       TLI->getInsertFencesForAtomic() ? Monotonic : LI->getOrdering();
00108   IRBuilder<> Builder(LI);
00109 
00110   // Note that although no fence is required before atomic load on ARM, it is
00111   // required before SequentiallyConsistent loads for the recommended Power
00112   // mapping (see http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html).
00113   // So we let the target choose what to emit.
00114   TLI->emitLeadingFence(Builder, LI->getOrdering(),
00115                         /*IsStore=*/false, /*IsLoad=*/true);
00116 
00117   // The only 64-bit load guaranteed to be single-copy atomic by ARM is
00118   // an ldrexd (A3.5.3).
00119   Value *Val =
00120       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
00121 
00122   TLI->emitTrailingFence(Builder, LI->getOrdering(),
00123                          /*IsStore=*/false, /*IsLoad=*/true);
00124 
00125   LI->replaceAllUsesWith(Val);
00126   LI->eraseFromParent();
00127 
00128   return true;
00129 }
00130 
00131 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
00132   // This function is only called on atomic stores that are too large to be
00133   // atomic if implemented as a native store. So we replace them by an
00134   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
00135   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
00136   // It is the responsibility of the target to only return true in
00137   // shouldExpandAtomicRMW in cases where this is required and possible.
00138   IRBuilder<> Builder(SI);
00139   AtomicRMWInst *AI =
00140       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
00141                               SI->getValueOperand(), SI->getOrdering());
00142   SI->eraseFromParent();
00143 
00144   // Now we have an appropriate swap instruction, lower it as usual.
00145   return expandAtomicRMW(AI);
00146 }
00147 
00148 bool AtomicExpand::expandAtomicRMW(AtomicRMWInst *AI) {
00149   if (TM->getSubtargetImpl()
00150           ->getTargetLowering()
00151           ->hasLoadLinkedStoreConditional())
00152     return expandAtomicRMWToLLSC(AI);
00153   else
00154     return expandAtomicRMWToCmpXchg(AI);
00155 }
00156 
00157 /// Emit IR to implement the given atomicrmw operation on values in registers,
00158 /// returning the new value.
00159 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
00160                               Value *Loaded, Value *Inc) {
00161   Value *NewVal;
00162   switch (Op) {
00163   case AtomicRMWInst::Xchg:
00164     return Inc;
00165   case AtomicRMWInst::Add:
00166     return Builder.CreateAdd(Loaded, Inc, "new");
00167   case AtomicRMWInst::Sub:
00168     return Builder.CreateSub(Loaded, Inc, "new");
00169   case AtomicRMWInst::And:
00170     return Builder.CreateAnd(Loaded, Inc, "new");
00171   case AtomicRMWInst::Nand:
00172     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
00173   case AtomicRMWInst::Or:
00174     return Builder.CreateOr(Loaded, Inc, "new");
00175   case AtomicRMWInst::Xor:
00176     return Builder.CreateXor(Loaded, Inc, "new");
00177   case AtomicRMWInst::Max:
00178     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
00179     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
00180   case AtomicRMWInst::Min:
00181     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
00182     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
00183   case AtomicRMWInst::UMax:
00184     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
00185     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
00186   case AtomicRMWInst::UMin:
00187     NewVal = Builder.CreateICmpULE(Loaded, Inc);
00188     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
00189   default:
00190     llvm_unreachable("Unknown atomic op");
00191   }
00192 }
00193 
00194 bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
00195   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
00196   AtomicOrdering FenceOrder = AI->getOrdering();
00197   Value *Addr = AI->getPointerOperand();
00198   BasicBlock *BB = AI->getParent();
00199   Function *F = BB->getParent();
00200   LLVMContext &Ctx = F->getContext();
00201   // If getInsertFencesForAtomic() returns true, then the target does not want
00202   // to deal with memory orders, and emitLeading/TrailingFence should take care
00203   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
00204   // should preserve the ordering.
00205   AtomicOrdering MemOpOrder =
00206       TLI->getInsertFencesForAtomic() ? Monotonic : FenceOrder;
00207 
00208   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
00209   //
00210   // The standard expansion we produce is:
00211   //     [...]
00212   //     fence?
00213   // atomicrmw.start:
00214   //     %loaded = @load.linked(%addr)
00215   //     %new = some_op iN %loaded, %incr
00216   //     %stored = @store_conditional(%new, %addr)
00217   //     %try_again = icmp i32 ne %stored, 0
00218   //     br i1 %try_again, label %loop, label %atomicrmw.end
00219   // atomicrmw.end:
00220   //     fence?
00221   //     [...]
00222   BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
00223   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
00224 
00225   // This grabs the DebugLoc from AI.
00226   IRBuilder<> Builder(AI);
00227 
00228   // The split call above "helpfully" added a branch at the end of BB (to the
00229   // wrong place), but we might want a fence too. It's easiest to just remove
00230   // the branch entirely.
00231   std::prev(BB->end())->eraseFromParent();
00232   Builder.SetInsertPoint(BB);
00233   TLI->emitLeadingFence(Builder, FenceOrder, /*IsStore=*/true, /*IsLoad=*/true);
00234   Builder.CreateBr(LoopBB);
00235 
00236   // Start the main loop block now that we've taken care of the preliminaries.
00237   Builder.SetInsertPoint(LoopBB);
00238   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
00239 
00240   Value *NewVal =
00241       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
00242 
00243   Value *StoreSuccess =
00244       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
00245   Value *TryAgain = Builder.CreateICmpNE(
00246       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
00247   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
00248 
00249   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
00250   TLI->emitTrailingFence(Builder, FenceOrder, /*IsStore=*/true, /*IsLoad=*/true);
00251 
00252   AI->replaceAllUsesWith(Loaded);
00253   AI->eraseFromParent();
00254 
00255   return true;
00256 }
00257 
00258 bool AtomicExpand::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI) {
00259   auto TargetLowering = TM->getSubtargetImpl()->getTargetLowering();
00260   AtomicOrdering FenceOrder =
00261       AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
00262   AtomicOrdering MemOpOrder =
00263       TargetLowering->getInsertFencesForAtomic() ? Monotonic : FenceOrder;
00264   Value *Addr = AI->getPointerOperand();
00265   BasicBlock *BB = AI->getParent();
00266   Function *F = BB->getParent();
00267   LLVMContext &Ctx = F->getContext();
00268 
00269   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
00270   //
00271   // The standard expansion we produce is:
00272   //     [...]
00273   //     %init_loaded = load atomic iN* %addr
00274   //     br label %loop
00275   // loop:
00276   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
00277   //     %new = some_op iN %loaded, %incr
00278   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
00279   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
00280   //     %success = extractvalue { iN, i1 } %pair, 1
00281   //     br i1 %success, label %atomicrmw.end, label %loop
00282   // atomicrmw.end:
00283   //     [...]
00284   BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
00285   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
00286 
00287   // This grabs the DebugLoc from AI.
00288   IRBuilder<> Builder(AI);
00289 
00290   // The split call above "helpfully" added a branch at the end of BB (to the
00291   // wrong place), but we want a load. It's easiest to just remove
00292   // the branch entirely.
00293   std::prev(BB->end())->eraseFromParent();
00294   Builder.SetInsertPoint(BB);
00295   TargetLowering->emitLeadingFence(Builder, FenceOrder,
00296                                    /*IsStore=*/true, /*IsLoad=*/true);
00297   LoadInst *InitLoaded = Builder.CreateLoad(Addr);
00298   // Atomics require at least natural alignment.
00299   InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits());
00300   Builder.CreateBr(LoopBB);
00301 
00302   // Start the main loop block now that we've taken care of the preliminaries.
00303   Builder.SetInsertPoint(LoopBB);
00304   PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
00305   Loaded->addIncoming(InitLoaded, BB);
00306 
00307   Value *NewVal =
00308       performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
00309 
00310   Value *Pair = Builder.CreateAtomicCmpXchg(
00311       Addr, Loaded, NewVal, MemOpOrder,
00312       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
00313   Value *NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
00314   Loaded->addIncoming(NewLoaded, LoopBB);
00315 
00316   Value *Success = Builder.CreateExtractValue(Pair, 1, "success");
00317   Builder.CreateCondBr(Success, ExitBB, LoopBB);
00318 
00319   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
00320   TargetLowering->emitTrailingFence(Builder, FenceOrder,
00321                                     /*IsStore=*/true, /*IsLoad=*/true);
00322 
00323   AI->replaceAllUsesWith(NewLoaded);
00324   AI->eraseFromParent();
00325 
00326   return true;
00327 }
00328 
00329 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
00330   auto TLI = TM->getSubtargetImpl()->getTargetLowering();
00331   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
00332   AtomicOrdering FailureOrder = CI->getFailureOrdering();
00333   Value *Addr = CI->getPointerOperand();
00334   BasicBlock *BB = CI->getParent();
00335   Function *F = BB->getParent();
00336   LLVMContext &Ctx = F->getContext();
00337   // If getInsertFencesForAtomic() returns true, then the target does not want
00338   // to deal with memory orders, and emitLeading/TrailingFence should take care
00339   // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
00340   // should preserve the ordering.
00341   AtomicOrdering MemOpOrder =
00342       TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
00343 
00344   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
00345   //
00346   // The full expansion we produce is:
00347   //     [...]
00348   //     fence?
00349   // cmpxchg.start:
00350   //     %loaded = @load.linked(%addr)
00351   //     %should_store = icmp eq %loaded, %desired
00352   //     br i1 %should_store, label %cmpxchg.trystore,
00353   //                          label %cmpxchg.failure
00354   // cmpxchg.trystore:
00355   //     %stored = @store_conditional(%new, %addr)
00356   //     %success = icmp eq i32 %stored, 0
00357   //     br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
00358   // cmpxchg.success:
00359   //     fence?
00360   //     br label %cmpxchg.end
00361   // cmpxchg.failure:
00362   //     fence?
00363   //     br label %cmpxchg.end
00364   // cmpxchg.end:
00365   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
00366   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
00367   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
00368   //     [...]
00369   BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
00370   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
00371   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
00372   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
00373   auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
00374 
00375   // This grabs the DebugLoc from CI
00376   IRBuilder<> Builder(CI);
00377 
00378   // The split call above "helpfully" added a branch at the end of BB (to the
00379   // wrong place), but we might want a fence too. It's easiest to just remove
00380   // the branch entirely.
00381   std::prev(BB->end())->eraseFromParent();
00382   Builder.SetInsertPoint(BB);
00383   TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
00384                         /*IsLoad=*/true);
00385   Builder.CreateBr(LoopBB);
00386 
00387   // Start the main loop block now that we've taken care of the preliminaries.
00388   Builder.SetInsertPoint(LoopBB);
00389   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
00390   Value *ShouldStore =
00391       Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
00392 
00393   // If the the cmpxchg doesn't actually need any ordering when it fails, we can
00394   // jump straight past that fence instruction (if it exists).
00395   Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
00396 
00397   Builder.SetInsertPoint(TryStoreBB);
00398   Value *StoreSuccess = TLI->emitStoreConditional(
00399       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
00400   StoreSuccess = Builder.CreateICmpEQ(
00401       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
00402   Builder.CreateCondBr(StoreSuccess, SuccessBB,
00403                        CI->isWeak() ? FailureBB : LoopBB);
00404 
00405   // Make sure later instructions don't get reordered with a fence if necessary.
00406   Builder.SetInsertPoint(SuccessBB);
00407   TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
00408                          /*IsLoad=*/true);
00409   Builder.CreateBr(ExitBB);
00410 
00411   Builder.SetInsertPoint(FailureBB);
00412   TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
00413                          /*IsLoad=*/true);
00414   Builder.CreateBr(ExitBB);
00415 
00416   // Finally, we have control-flow based knowledge of whether the cmpxchg
00417   // succeeded or not. We expose this to later passes by converting any
00418   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
00419 
00420   // Setup the builder so we can create any PHIs we need.
00421   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
00422   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
00423   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
00424   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
00425 
00426   // Look for any users of the cmpxchg that are just comparing the loaded value
00427   // against the desired one, and replace them with the CFG-derived version.
00428   SmallVector<ExtractValueInst *, 2> PrunedInsts;
00429   for (auto User : CI->users()) {
00430     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
00431     if (!EV)
00432       continue;
00433 
00434     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
00435            "weird extraction from { iN, i1 }");
00436 
00437     if (EV->getIndices()[0] == 0)
00438       EV->replaceAllUsesWith(Loaded);
00439     else
00440       EV->replaceAllUsesWith(Success);
00441 
00442     PrunedInsts.push_back(EV);
00443   }
00444 
00445   // We can remove the instructions now we're no longer iterating through them.
00446   for (auto EV : PrunedInsts)
00447     EV->eraseFromParent();
00448 
00449   if (!CI->use_empty()) {
00450     // Some use of the full struct return that we don't understand has happened,
00451     // so we've got to reconstruct it properly.
00452     Value *Res;
00453     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
00454     Res = Builder.CreateInsertValue(Res, Success, 1);
00455 
00456     CI->replaceAllUsesWith(Res);
00457   }
00458 
00459   CI->eraseFromParent();
00460   return true;
00461 }