1 //===- OpenMPIRBuilder.cpp - Builder for LLVM-IR for OpenMP directives ----===//
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 /// \file
9 ///
10 /// This file implements the OpenMPIRBuilder class, which is used as a
11 /// convenient way to create LLVM instructions for OpenMP directives.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/PassManager.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/MC/TargetRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/CodeExtractor.h"
38 #include "llvm/Transforms/Utils/LoopPeel.h"
39 #include "llvm/Transforms/Utils/UnrollLoop.h"
40 
41 #include <cstdint>
42 
43 #define DEBUG_TYPE "openmp-ir-builder"
44 
45 using namespace llvm;
46 using namespace omp;
47 
48 static cl::opt<bool>
49     OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
50                          cl::desc("Use optimistic attributes describing "
51                                   "'as-if' properties of runtime calls."),
52                          cl::init(false));
53 
54 static cl::opt<double> UnrollThresholdFactor(
55     "openmp-ir-builder-unroll-threshold-factor", cl::Hidden,
56     cl::desc("Factor for the unroll threshold to account for code "
57              "simplifications still taking place"),
58     cl::init(1.5));
59 
60 #ifndef NDEBUG
61 /// Return whether IP1 and IP2 are ambiguous, i.e. that inserting instructions
62 /// at position IP1 may change the meaning of IP2 or vice-versa. This is because
63 /// an InsertPoint stores the instruction before something is inserted. For
64 /// instance, if both point to the same instruction, two IRBuilders alternating
65 /// creating instruction will cause the instructions to be interleaved.
66 static bool isConflictIP(IRBuilder<>::InsertPoint IP1,
67                          IRBuilder<>::InsertPoint IP2) {
68   if (!IP1.isSet() || !IP2.isSet())
69     return false;
70   return IP1.getBlock() == IP2.getBlock() && IP1.getPoint() == IP2.getPoint();
71 }
72 
73 static bool isValidWorkshareLoopScheduleType(OMPScheduleType SchedType) {
74   // Valid ordered/unordered and base algorithm combinations.
75   switch (SchedType & ~OMPScheduleType::MonotonicityMask) {
76   case OMPScheduleType::UnorderedStaticChunked:
77   case OMPScheduleType::UnorderedStatic:
78   case OMPScheduleType::UnorderedDynamicChunked:
79   case OMPScheduleType::UnorderedGuidedChunked:
80   case OMPScheduleType::UnorderedRuntime:
81   case OMPScheduleType::UnorderedAuto:
82   case OMPScheduleType::UnorderedTrapezoidal:
83   case OMPScheduleType::UnorderedGreedy:
84   case OMPScheduleType::UnorderedBalanced:
85   case OMPScheduleType::UnorderedGuidedIterativeChunked:
86   case OMPScheduleType::UnorderedGuidedAnalyticalChunked:
87   case OMPScheduleType::UnorderedSteal:
88   case OMPScheduleType::UnorderedStaticBalancedChunked:
89   case OMPScheduleType::UnorderedGuidedSimd:
90   case OMPScheduleType::UnorderedRuntimeSimd:
91   case OMPScheduleType::OrderedStaticChunked:
92   case OMPScheduleType::OrderedStatic:
93   case OMPScheduleType::OrderedDynamicChunked:
94   case OMPScheduleType::OrderedGuidedChunked:
95   case OMPScheduleType::OrderedRuntime:
96   case OMPScheduleType::OrderedAuto:
97   case OMPScheduleType::OrderdTrapezoidal:
98   case OMPScheduleType::NomergeUnorderedStaticChunked:
99   case OMPScheduleType::NomergeUnorderedStatic:
100   case OMPScheduleType::NomergeUnorderedDynamicChunked:
101   case OMPScheduleType::NomergeUnorderedGuidedChunked:
102   case OMPScheduleType::NomergeUnorderedRuntime:
103   case OMPScheduleType::NomergeUnorderedAuto:
104   case OMPScheduleType::NomergeUnorderedTrapezoidal:
105   case OMPScheduleType::NomergeUnorderedGreedy:
106   case OMPScheduleType::NomergeUnorderedBalanced:
107   case OMPScheduleType::NomergeUnorderedGuidedIterativeChunked:
108   case OMPScheduleType::NomergeUnorderedGuidedAnalyticalChunked:
109   case OMPScheduleType::NomergeUnorderedSteal:
110   case OMPScheduleType::NomergeOrderedStaticChunked:
111   case OMPScheduleType::NomergeOrderedStatic:
112   case OMPScheduleType::NomergeOrderedDynamicChunked:
113   case OMPScheduleType::NomergeOrderedGuidedChunked:
114   case OMPScheduleType::NomergeOrderedRuntime:
115   case OMPScheduleType::NomergeOrderedAuto:
116   case OMPScheduleType::NomergeOrderedTrapezoidal:
117     break;
118   default:
119     return false;
120   }
121 
122   // Must not set both monotonicity modifiers at the same time.
123   OMPScheduleType MonotonicityFlags =
124       SchedType & OMPScheduleType::MonotonicityMask;
125   if (MonotonicityFlags == OMPScheduleType::MonotonicityMask)
126     return false;
127 
128   return true;
129 }
130 #endif
131 
132 /// Determine which scheduling algorithm to use, determined from schedule clause
133 /// arguments.
134 static OMPScheduleType
135 getOpenMPBaseScheduleType(llvm::omp::ScheduleKind ClauseKind, bool HasChunks,
136                           bool HasSimdModifier) {
137   // Currently, the default schedule it static.
138   switch (ClauseKind) {
139   case OMP_SCHEDULE_Default:
140   case OMP_SCHEDULE_Static:
141     return HasChunks ? OMPScheduleType::BaseStaticChunked
142                      : OMPScheduleType::BaseStatic;
143   case OMP_SCHEDULE_Dynamic:
144     return OMPScheduleType::BaseDynamicChunked;
145   case OMP_SCHEDULE_Guided:
146     return HasSimdModifier ? OMPScheduleType::BaseGuidedSimd
147                            : OMPScheduleType::BaseGuidedChunked;
148   case OMP_SCHEDULE_Auto:
149     return llvm::omp::OMPScheduleType::BaseAuto;
150   case OMP_SCHEDULE_Runtime:
151     return HasSimdModifier ? OMPScheduleType::BaseRuntimeSimd
152                            : OMPScheduleType::BaseRuntime;
153   }
154   llvm_unreachable("unhandled schedule clause argument");
155 }
156 
157 /// Adds ordering modifier flags to schedule type.
158 static OMPScheduleType
159 getOpenMPOrderingScheduleType(OMPScheduleType BaseScheduleType,
160                               bool HasOrderedClause) {
161   assert((BaseScheduleType & OMPScheduleType::ModifierMask) ==
162              OMPScheduleType::None &&
163          "Must not have ordering nor monotonicity flags already set");
164 
165   OMPScheduleType OrderingModifier = HasOrderedClause
166                                          ? OMPScheduleType::ModifierOrdered
167                                          : OMPScheduleType::ModifierUnordered;
168   OMPScheduleType OrderingScheduleType = BaseScheduleType | OrderingModifier;
169 
170   // Unsupported combinations
171   if (OrderingScheduleType ==
172       (OMPScheduleType::BaseGuidedSimd | OMPScheduleType::ModifierOrdered))
173     return OMPScheduleType::OrderedGuidedChunked;
174   else if (OrderingScheduleType == (OMPScheduleType::BaseRuntimeSimd |
175                                     OMPScheduleType::ModifierOrdered))
176     return OMPScheduleType::OrderedRuntime;
177 
178   return OrderingScheduleType;
179 }
180 
181 /// Adds monotonicity modifier flags to schedule type.
182 static OMPScheduleType
183 getOpenMPMonotonicityScheduleType(OMPScheduleType ScheduleType,
184                                   bool HasSimdModifier, bool HasMonotonic,
185                                   bool HasNonmonotonic, bool HasOrderedClause) {
186   assert((ScheduleType & OMPScheduleType::MonotonicityMask) ==
187              OMPScheduleType::None &&
188          "Must not have monotonicity flags already set");
189   assert((!HasMonotonic || !HasNonmonotonic) &&
190          "Monotonic and Nonmonotonic are contradicting each other");
191 
192   if (HasMonotonic) {
193     return ScheduleType | OMPScheduleType::ModifierMonotonic;
194   } else if (HasNonmonotonic) {
195     return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
196   } else {
197     // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
198     // If the static schedule kind is specified or if the ordered clause is
199     // specified, and if the nonmonotonic modifier is not specified, the
200     // effect is as if the monotonic modifier is specified. Otherwise, unless
201     // the monotonic modifier is specified, the effect is as if the
202     // nonmonotonic modifier is specified.
203     OMPScheduleType BaseScheduleType =
204         ScheduleType & ~OMPScheduleType::ModifierMask;
205     if ((BaseScheduleType == OMPScheduleType::BaseStatic) ||
206         (BaseScheduleType == OMPScheduleType::BaseStaticChunked) ||
207         HasOrderedClause) {
208       // The monotonic is used by default in openmp runtime library, so no need
209       // to set it.
210       return ScheduleType;
211     } else {
212       return ScheduleType | OMPScheduleType::ModifierNonmonotonic;
213     }
214   }
215 }
216 
217 /// Determine the schedule type using schedule and ordering clause arguments.
218 static OMPScheduleType
219 computeOpenMPScheduleType(ScheduleKind ClauseKind, bool HasChunks,
220                           bool HasSimdModifier, bool HasMonotonicModifier,
221                           bool HasNonmonotonicModifier, bool HasOrderedClause) {
222   OMPScheduleType BaseSchedule =
223       getOpenMPBaseScheduleType(ClauseKind, HasChunks, HasSimdModifier);
224   OMPScheduleType OrderedSchedule =
225       getOpenMPOrderingScheduleType(BaseSchedule, HasOrderedClause);
226   OMPScheduleType Result = getOpenMPMonotonicityScheduleType(
227       OrderedSchedule, HasSimdModifier, HasMonotonicModifier,
228       HasNonmonotonicModifier, HasOrderedClause);
229 
230   assert(isValidWorkshareLoopScheduleType(Result));
231   return Result;
232 }
233 
234 /// Make \p Source branch to \p Target.
235 ///
236 /// Handles two situations:
237 /// * \p Source already has an unconditional branch.
238 /// * \p Source is a degenerate block (no terminator because the BB is
239 ///             the current head of the IR construction).
240 static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL) {
241   if (Instruction *Term = Source->getTerminator()) {
242     auto *Br = cast<BranchInst>(Term);
243     assert(!Br->isConditional() &&
244            "BB's terminator must be an unconditional branch (or degenerate)");
245     BasicBlock *Succ = Br->getSuccessor(0);
246     Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
247     Br->setSuccessor(0, Target);
248     return;
249   }
250 
251   auto *NewBr = BranchInst::Create(Target, Source);
252   NewBr->setDebugLoc(DL);
253 }
254 
255 void llvm::spliceBB(IRBuilderBase::InsertPoint IP, BasicBlock *New,
256                     bool CreateBranch) {
257   assert(New->getFirstInsertionPt() == New->begin() &&
258          "Target BB must not have PHI nodes");
259 
260   // Move instructions to new block.
261   BasicBlock *Old = IP.getBlock();
262   New->getInstList().splice(New->begin(), Old->getInstList(), IP.getPoint(),
263                             Old->end());
264 
265   if (CreateBranch)
266     BranchInst::Create(New, Old);
267 }
268 
269 void llvm::spliceBB(IRBuilder<> &Builder, BasicBlock *New, bool CreateBranch) {
270   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
271   BasicBlock *Old = Builder.GetInsertBlock();
272 
273   spliceBB(Builder.saveIP(), New, CreateBranch);
274   if (CreateBranch)
275     Builder.SetInsertPoint(Old->getTerminator());
276   else
277     Builder.SetInsertPoint(Old);
278 
279   // SetInsertPoint also updates the Builder's debug location, but we want to
280   // keep the one the Builder was configured to use.
281   Builder.SetCurrentDebugLocation(DebugLoc);
282 }
283 
284 BasicBlock *llvm::splitBB(IRBuilderBase::InsertPoint IP, bool CreateBranch,
285                           llvm::Twine Name) {
286   BasicBlock *Old = IP.getBlock();
287   BasicBlock *New = BasicBlock::Create(
288       Old->getContext(), Name.isTriviallyEmpty() ? Old->getName() : Name,
289       Old->getParent(), Old->getNextNode());
290   spliceBB(IP, New, CreateBranch);
291   New->replaceSuccessorsPhiUsesWith(Old, New);
292   return New;
293 }
294 
295 BasicBlock *llvm::splitBB(IRBuilderBase &Builder, bool CreateBranch,
296                           llvm::Twine Name) {
297   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
298   BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
299   if (CreateBranch)
300     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
301   else
302     Builder.SetInsertPoint(Builder.GetInsertBlock());
303   // SetInsertPoint also updates the Builder's debug location, but we want to
304   // keep the one the Builder was configured to use.
305   Builder.SetCurrentDebugLocation(DebugLoc);
306   return New;
307 }
308 
309 BasicBlock *llvm::splitBB(IRBuilder<> &Builder, bool CreateBranch,
310                           llvm::Twine Name) {
311   DebugLoc DebugLoc = Builder.getCurrentDebugLocation();
312   BasicBlock *New = splitBB(Builder.saveIP(), CreateBranch, Name);
313   if (CreateBranch)
314     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
315   else
316     Builder.SetInsertPoint(Builder.GetInsertBlock());
317   // SetInsertPoint also updates the Builder's debug location, but we want to
318   // keep the one the Builder was configured to use.
319   Builder.SetCurrentDebugLocation(DebugLoc);
320   return New;
321 }
322 
323 BasicBlock *llvm::splitBBWithSuffix(IRBuilderBase &Builder, bool CreateBranch,
324                                     llvm::Twine Suffix) {
325   BasicBlock *Old = Builder.GetInsertBlock();
326   return splitBB(Builder, CreateBranch, Old->getName() + Suffix);
327 }
328 
329 void OpenMPIRBuilder::addAttributes(omp::RuntimeFunction FnID, Function &Fn) {
330   LLVMContext &Ctx = Fn.getContext();
331 
332   // Get the function's current attributes.
333   auto Attrs = Fn.getAttributes();
334   auto FnAttrs = Attrs.getFnAttrs();
335   auto RetAttrs = Attrs.getRetAttrs();
336   SmallVector<AttributeSet, 4> ArgAttrs;
337   for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
338     ArgAttrs.emplace_back(Attrs.getParamAttrs(ArgNo));
339 
340 #define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
341 #include "llvm/Frontend/OpenMP/OMPKinds.def"
342 
343   // Add attributes to the function declaration.
344   switch (FnID) {
345 #define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets)                \
346   case Enum:                                                                   \
347     FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet);                           \
348     RetAttrs = RetAttrs.addAttributes(Ctx, RetAttrSet);                        \
349     for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo)                \
350       ArgAttrs[ArgNo] =                                                        \
351           ArgAttrs[ArgNo].addAttributes(Ctx, ArgAttrSets[ArgNo]);              \
352     Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs));    \
353     break;
354 #include "llvm/Frontend/OpenMP/OMPKinds.def"
355   default:
356     // Attributes are optional.
357     break;
358   }
359 }
360 
361 FunctionCallee
362 OpenMPIRBuilder::getOrCreateRuntimeFunction(Module &M, RuntimeFunction FnID) {
363   FunctionType *FnTy = nullptr;
364   Function *Fn = nullptr;
365 
366   // Try to find the declation in the module first.
367   switch (FnID) {
368 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...)                          \
369   case Enum:                                                                   \
370     FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__},        \
371                              IsVarArg);                                        \
372     Fn = M.getFunction(Str);                                                   \
373     break;
374 #include "llvm/Frontend/OpenMP/OMPKinds.def"
375   }
376 
377   if (!Fn) {
378     // Create a new declaration if we need one.
379     switch (FnID) {
380 #define OMP_RTL(Enum, Str, ...)                                                \
381   case Enum:                                                                   \
382     Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M);         \
383     break;
384 #include "llvm/Frontend/OpenMP/OMPKinds.def"
385     }
386 
387     // Add information if the runtime function takes a callback function
388     if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
389       if (!Fn->hasMetadata(LLVMContext::MD_callback)) {
390         LLVMContext &Ctx = Fn->getContext();
391         MDBuilder MDB(Ctx);
392         // Annotate the callback behavior of the runtime function:
393         //  - The callback callee is argument number 2 (microtask).
394         //  - The first two arguments of the callback callee are unknown (-1).
395         //  - All variadic arguments to the runtime function are passed to the
396         //    callback callee.
397         Fn->addMetadata(
398             LLVMContext::MD_callback,
399             *MDNode::get(Ctx, {MDB.createCallbackEncoding(
400                                   2, {-1, -1}, /* VarArgsArePassed */ true)}));
401       }
402     }
403 
404     LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()
405                       << " with type " << *Fn->getFunctionType() << "\n");
406     addAttributes(FnID, *Fn);
407 
408   } else {
409     LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()
410                       << " with type " << *Fn->getFunctionType() << "\n");
411   }
412 
413   assert(Fn && "Failed to create OpenMP runtime function");
414 
415   // Cast the function to the expected type if necessary
416   Constant *C = ConstantExpr::getBitCast(Fn, FnTy->getPointerTo());
417   return {FnTy, C};
418 }
419 
420 Function *OpenMPIRBuilder::getOrCreateRuntimeFunctionPtr(RuntimeFunction FnID) {
421   FunctionCallee RTLFn = getOrCreateRuntimeFunction(M, FnID);
422   auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
423   assert(Fn && "Failed to create OpenMP runtime function pointer");
424   return Fn;
425 }
426 
427 void OpenMPIRBuilder::initialize() { initializeTypes(M); }
428 
429 void OpenMPIRBuilder::finalize(Function *Fn) {
430   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
431   SmallVector<BasicBlock *, 32> Blocks;
432   SmallVector<OutlineInfo, 16> DeferredOutlines;
433   for (OutlineInfo &OI : OutlineInfos) {
434     // Skip functions that have not finalized yet; may happen with nested
435     // function generation.
436     if (Fn && OI.getFunction() != Fn) {
437       DeferredOutlines.push_back(OI);
438       continue;
439     }
440 
441     ParallelRegionBlockSet.clear();
442     Blocks.clear();
443     OI.collectBlocks(ParallelRegionBlockSet, Blocks);
444 
445     Function *OuterFn = OI.getFunction();
446     CodeExtractorAnalysisCache CEAC(*OuterFn);
447     CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
448                             /* AggregateArgs */ true,
449                             /* BlockFrequencyInfo */ nullptr,
450                             /* BranchProbabilityInfo */ nullptr,
451                             /* AssumptionCache */ nullptr,
452                             /* AllowVarArgs */ true,
453                             /* AllowAlloca */ true,
454                             /* AllocaBlock*/ OI.OuterAllocaBB,
455                             /* Suffix */ ".omp_par");
456 
457     LLVM_DEBUG(dbgs() << "Before     outlining: " << *OuterFn << "\n");
458     LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()
459                       << " Exit: " << OI.ExitBB->getName() << "\n");
460     assert(Extractor.isEligible() &&
461            "Expected OpenMP outlining to be possible!");
462 
463     for (auto *V : OI.ExcludeArgsFromAggregate)
464       Extractor.excludeArgFromAggregate(V);
465 
466     Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);
467 
468     LLVM_DEBUG(dbgs() << "After      outlining: " << *OuterFn << "\n");
469     LLVM_DEBUG(dbgs() << "   Outlined function: " << *OutlinedFn << "\n");
470     assert(OutlinedFn->getReturnType()->isVoidTy() &&
471            "OpenMP outlined functions should not return a value!");
472 
473     // For compability with the clang CG we move the outlined function after the
474     // one with the parallel region.
475     OutlinedFn->removeFromParent();
476     M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
477 
478     // Remove the artificial entry introduced by the extractor right away, we
479     // made our own entry block after all.
480     {
481       BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
482       assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);
483       assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);
484       // Move instructions from the to-be-deleted ArtificialEntry to the entry
485       // basic block of the parallel region. CodeExtractor generates
486       // instructions to unwrap the aggregate argument and may sink
487       // allocas/bitcasts for values that are solely used in the outlined region
488       // and do not escape.
489       assert(!ArtificialEntry.empty() &&
490              "Expected instructions to add in the outlined region entry");
491       for (BasicBlock::reverse_iterator It = ArtificialEntry.rbegin(),
492                                         End = ArtificialEntry.rend();
493            It != End;) {
494         Instruction &I = *It;
495         It++;
496 
497         if (I.isTerminator())
498           continue;
499 
500         I.moveBefore(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());
501       }
502 
503       OI.EntryBB->moveBefore(&ArtificialEntry);
504       ArtificialEntry.eraseFromParent();
505     }
506     assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);
507     assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
508 
509     // Run a user callback, e.g. to add attributes.
510     if (OI.PostOutlineCB)
511       OI.PostOutlineCB(*OutlinedFn);
512   }
513 
514   // Remove work items that have been completed.
515   OutlineInfos = std::move(DeferredOutlines);
516 }
517 
518 OpenMPIRBuilder::~OpenMPIRBuilder() {
519   assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
520 }
521 
522 GlobalValue *OpenMPIRBuilder::createGlobalFlag(unsigned Value, StringRef Name) {
523   IntegerType *I32Ty = Type::getInt32Ty(M.getContext());
524   auto *GV =
525       new GlobalVariable(M, I32Ty,
526                          /* isConstant = */ true, GlobalValue::WeakODRLinkage,
527                          ConstantInt::get(I32Ty, Value), Name);
528   GV->setVisibility(GlobalValue::HiddenVisibility);
529 
530   return GV;
531 }
532 
533 Constant *OpenMPIRBuilder::getOrCreateIdent(Constant *SrcLocStr,
534                                             uint32_t SrcLocStrSize,
535                                             IdentFlag LocFlags,
536                                             unsigned Reserve2Flags) {
537   // Enable "C-mode".
538   LocFlags |= OMP_IDENT_FLAG_KMPC;
539 
540   Constant *&Ident =
541       IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
542   if (!Ident) {
543     Constant *I32Null = ConstantInt::getNullValue(Int32);
544     Constant *IdentData[] = {I32Null,
545                              ConstantInt::get(Int32, uint32_t(LocFlags)),
546                              ConstantInt::get(Int32, Reserve2Flags),
547                              ConstantInt::get(Int32, SrcLocStrSize), SrcLocStr};
548     Constant *Initializer =
549         ConstantStruct::get(OpenMPIRBuilder::Ident, IdentData);
550 
551     // Look for existing encoding of the location + flags, not needed but
552     // minimizes the difference to the existing solution while we transition.
553     for (GlobalVariable &GV : M.getGlobalList())
554       if (GV.getValueType() == OpenMPIRBuilder::Ident && GV.hasInitializer())
555         if (GV.getInitializer() == Initializer)
556           Ident = &GV;
557 
558     if (!Ident) {
559       auto *GV = new GlobalVariable(
560           M, OpenMPIRBuilder::Ident,
561           /* isConstant = */ true, GlobalValue::PrivateLinkage, Initializer, "",
562           nullptr, GlobalValue::NotThreadLocal,
563           M.getDataLayout().getDefaultGlobalsAddressSpace());
564       GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
565       GV->setAlignment(Align(8));
566       Ident = GV;
567     }
568   }
569 
570   return ConstantExpr::getPointerBitCastOrAddrSpaceCast(Ident, IdentPtr);
571 }
572 
573 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef LocStr,
574                                                 uint32_t &SrcLocStrSize) {
575   SrcLocStrSize = LocStr.size();
576   Constant *&SrcLocStr = SrcLocStrMap[LocStr];
577   if (!SrcLocStr) {
578     Constant *Initializer =
579         ConstantDataArray::getString(M.getContext(), LocStr);
580 
581     // Look for existing encoding of the location, not needed but minimizes the
582     // difference to the existing solution while we transition.
583     for (GlobalVariable &GV : M.getGlobalList())
584       if (GV.isConstant() && GV.hasInitializer() &&
585           GV.getInitializer() == Initializer)
586         return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
587 
588     SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",
589                                               /* AddressSpace */ 0, &M);
590   }
591   return SrcLocStr;
592 }
593 
594 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef FunctionName,
595                                                 StringRef FileName,
596                                                 unsigned Line, unsigned Column,
597                                                 uint32_t &SrcLocStrSize) {
598   SmallString<128> Buffer;
599   Buffer.push_back(';');
600   Buffer.append(FileName);
601   Buffer.push_back(';');
602   Buffer.append(FunctionName);
603   Buffer.push_back(';');
604   Buffer.append(std::to_string(Line));
605   Buffer.push_back(';');
606   Buffer.append(std::to_string(Column));
607   Buffer.push_back(';');
608   Buffer.push_back(';');
609   return getOrCreateSrcLocStr(Buffer.str(), SrcLocStrSize);
610 }
611 
612 Constant *
613 OpenMPIRBuilder::getOrCreateDefaultSrcLocStr(uint32_t &SrcLocStrSize) {
614   StringRef UnknownLoc = ";unknown;unknown;0;0;;";
615   return getOrCreateSrcLocStr(UnknownLoc, SrcLocStrSize);
616 }
617 
618 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(DebugLoc DL,
619                                                 uint32_t &SrcLocStrSize,
620                                                 Function *F) {
621   DILocation *DIL = DL.get();
622   if (!DIL)
623     return getOrCreateDefaultSrcLocStr(SrcLocStrSize);
624   StringRef FileName = M.getName();
625   if (DIFile *DIF = DIL->getFile())
626     if (Optional<StringRef> Source = DIF->getSource())
627       FileName = *Source;
628   StringRef Function = DIL->getScope()->getSubprogram()->getName();
629   if (Function.empty() && F)
630     Function = F->getName();
631   return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
632                               DIL->getColumn(), SrcLocStrSize);
633 }
634 
635 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(const LocationDescription &Loc,
636                                                 uint32_t &SrcLocStrSize) {
637   return getOrCreateSrcLocStr(Loc.DL, SrcLocStrSize,
638                               Loc.IP.getBlock()->getParent());
639 }
640 
641 Value *OpenMPIRBuilder::getOrCreateThreadID(Value *Ident) {
642   return Builder.CreateCall(
643       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
644       "omp_global_thread_num");
645 }
646 
647 OpenMPIRBuilder::InsertPointTy
648 OpenMPIRBuilder::createBarrier(const LocationDescription &Loc, Directive DK,
649                                bool ForceSimpleCall, bool CheckCancelFlag) {
650   if (!updateToLocation(Loc))
651     return Loc.IP;
652   return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
653 }
654 
655 OpenMPIRBuilder::InsertPointTy
656 OpenMPIRBuilder::emitBarrierImpl(const LocationDescription &Loc, Directive Kind,
657                                  bool ForceSimpleCall, bool CheckCancelFlag) {
658   // Build call __kmpc_cancel_barrier(loc, thread_id) or
659   //            __kmpc_barrier(loc, thread_id);
660 
661   IdentFlag BarrierLocFlags;
662   switch (Kind) {
663   case OMPD_for:
664     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
665     break;
666   case OMPD_sections:
667     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
668     break;
669   case OMPD_single:
670     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
671     break;
672   case OMPD_barrier:
673     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
674     break;
675   default:
676     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
677     break;
678   }
679 
680   uint32_t SrcLocStrSize;
681   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
682   Value *Args[] = {
683       getOrCreateIdent(SrcLocStr, SrcLocStrSize, BarrierLocFlags),
684       getOrCreateThreadID(getOrCreateIdent(SrcLocStr, SrcLocStrSize))};
685 
686   // If we are in a cancellable parallel region, barriers are cancellation
687   // points.
688   // TODO: Check why we would force simple calls or to ignore the cancel flag.
689   bool UseCancelBarrier =
690       !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
691 
692   Value *Result =
693       Builder.CreateCall(getOrCreateRuntimeFunctionPtr(
694                              UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
695                                               : OMPRTL___kmpc_barrier),
696                          Args);
697 
698   if (UseCancelBarrier && CheckCancelFlag)
699     emitCancelationCheckImpl(Result, OMPD_parallel);
700 
701   return Builder.saveIP();
702 }
703 
704 OpenMPIRBuilder::InsertPointTy
705 OpenMPIRBuilder::createCancel(const LocationDescription &Loc,
706                               Value *IfCondition,
707                               omp::Directive CanceledDirective) {
708   if (!updateToLocation(Loc))
709     return Loc.IP;
710 
711   // LLVM utilities like blocks with terminators.
712   auto *UI = Builder.CreateUnreachable();
713 
714   Instruction *ThenTI = UI, *ElseTI = nullptr;
715   if (IfCondition)
716     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
717   Builder.SetInsertPoint(ThenTI);
718 
719   Value *CancelKind = nullptr;
720   switch (CanceledDirective) {
721 #define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value)                       \
722   case DirectiveEnum:                                                          \
723     CancelKind = Builder.getInt32(Value);                                      \
724     break;
725 #include "llvm/Frontend/OpenMP/OMPKinds.def"
726   default:
727     llvm_unreachable("Unknown cancel kind!");
728   }
729 
730   uint32_t SrcLocStrSize;
731   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
732   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
733   Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
734   Value *Result = Builder.CreateCall(
735       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
736   auto ExitCB = [this, CanceledDirective, Loc](InsertPointTy IP) {
737     if (CanceledDirective == OMPD_parallel) {
738       IRBuilder<>::InsertPointGuard IPG(Builder);
739       Builder.restoreIP(IP);
740       createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
741                     omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
742                     /* CheckCancelFlag */ false);
743     }
744   };
745 
746   // The actual cancel logic is shared with others, e.g., cancel_barriers.
747   emitCancelationCheckImpl(Result, CanceledDirective, ExitCB);
748 
749   // Update the insertion point and remove the terminator we introduced.
750   Builder.SetInsertPoint(UI->getParent());
751   UI->eraseFromParent();
752 
753   return Builder.saveIP();
754 }
755 
756 void OpenMPIRBuilder::emitOffloadingEntry(Constant *Addr, StringRef Name,
757                                           uint64_t Size, int32_t Flags,
758                                           StringRef SectionName) {
759   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
760   Type *Int32Ty = Type::getInt32Ty(M.getContext());
761   Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
762 
763   Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
764 
765   // Create the constant string used to look up the symbol in the device.
766   auto *Str =
767       new llvm::GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
768                                llvm::GlobalValue::InternalLinkage, AddrName,
769                                ".omp_offloading.entry_name");
770   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
771 
772   // Construct the offloading entry.
773   Constant *EntryData[] = {
774       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Addr, Int8PtrTy),
775       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, Int8PtrTy),
776       ConstantInt::get(SizeTy, Size),
777       ConstantInt::get(Int32Ty, Flags),
778       ConstantInt::get(Int32Ty, 0),
779   };
780   Constant *EntryInitializer =
781       ConstantStruct::get(OpenMPIRBuilder::OffloadEntry, EntryData);
782 
783   auto *Entry = new GlobalVariable(
784       M, OpenMPIRBuilder::OffloadEntry,
785       /* isConstant = */ true, GlobalValue::WeakAnyLinkage, EntryInitializer,
786       ".omp_offloading.entry." + Name, nullptr, GlobalValue::NotThreadLocal,
787       M.getDataLayout().getDefaultGlobalsAddressSpace());
788 
789   // The entry has to be created in the section the linker expects it to be.
790   Entry->setSection(SectionName);
791   Entry->setAlignment(Align(1));
792 }
793 
794 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitTargetKernel(
795     const LocationDescription &Loc, Value *&Return, Value *Ident,
796     Value *DeviceID, Value *NumTeams, Value *NumThreads, Value *HostPtr,
797     ArrayRef<Value *> KernelArgs, ArrayRef<Value *> NoWaitArgs) {
798   if (!updateToLocation(Loc))
799     return Loc.IP;
800 
801   auto *KernelArgsPtr =
802       Builder.CreateAlloca(OpenMPIRBuilder::KernelArgs, nullptr, "kernel_args");
803   for (unsigned I = 0, Size = KernelArgs.size(); I != Size; ++I) {
804     llvm::Value *Arg =
805         Builder.CreateStructGEP(OpenMPIRBuilder::KernelArgs, KernelArgsPtr, I);
806     Builder.CreateAlignedStore(
807         KernelArgs[I], Arg,
808         M.getDataLayout().getPrefTypeAlign(KernelArgs[I]->getType()));
809   }
810 
811   bool HasNoWait = !NoWaitArgs.empty();
812   SmallVector<Value *> OffloadingArgs{Ident,      DeviceID, NumTeams,
813                                       NumThreads, HostPtr,  KernelArgsPtr};
814   if (HasNoWait)
815     OffloadingArgs.append(NoWaitArgs.begin(), NoWaitArgs.end());
816 
817   Return = Builder.CreateCall(
818       HasNoWait
819           ? getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel_nowait)
820           : getOrCreateRuntimeFunction(M, OMPRTL___tgt_target_kernel),
821       OffloadingArgs);
822 
823   return Builder.saveIP();
824 }
825 
826 void OpenMPIRBuilder::emitCancelationCheckImpl(Value *CancelFlag,
827                                                omp::Directive CanceledDirective,
828                                                FinalizeCallbackTy ExitCB) {
829   assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
830          "Unexpected cancellation!");
831 
832   // For a cancel barrier we create two new blocks.
833   BasicBlock *BB = Builder.GetInsertBlock();
834   BasicBlock *NonCancellationBlock;
835   if (Builder.GetInsertPoint() == BB->end()) {
836     // TODO: This branch will not be needed once we moved to the
837     // OpenMPIRBuilder codegen completely.
838     NonCancellationBlock = BasicBlock::Create(
839         BB->getContext(), BB->getName() + ".cont", BB->getParent());
840   } else {
841     NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
842     BB->getTerminator()->eraseFromParent();
843     Builder.SetInsertPoint(BB);
844   }
845   BasicBlock *CancellationBlock = BasicBlock::Create(
846       BB->getContext(), BB->getName() + ".cncl", BB->getParent());
847 
848   // Jump to them based on the return value.
849   Value *Cmp = Builder.CreateIsNull(CancelFlag);
850   Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
851                        /* TODO weight */ nullptr, nullptr);
852 
853   // From the cancellation block we finalize all variables and go to the
854   // post finalization block that is known to the FiniCB callback.
855   Builder.SetInsertPoint(CancellationBlock);
856   if (ExitCB)
857     ExitCB(Builder.saveIP());
858   auto &FI = FinalizationStack.back();
859   FI.FiniCB(Builder.saveIP());
860 
861   // The continuation block is where code generation continues.
862   Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
863 }
864 
865 IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(
866     const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
867     BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
868     FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
869     omp::ProcBindKind ProcBind, bool IsCancellable) {
870   assert(!isConflictIP(Loc.IP, OuterAllocaIP) && "IPs must not be ambiguous");
871 
872   if (!updateToLocation(Loc))
873     return Loc.IP;
874 
875   uint32_t SrcLocStrSize;
876   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
877   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
878   Value *ThreadID = getOrCreateThreadID(Ident);
879 
880   if (NumThreads) {
881     // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
882     Value *Args[] = {
883         Ident, ThreadID,
884         Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
885     Builder.CreateCall(
886         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
887   }
888 
889   if (ProcBind != OMP_PROC_BIND_default) {
890     // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
891     Value *Args[] = {
892         Ident, ThreadID,
893         ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
894     Builder.CreateCall(
895         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
896   }
897 
898   BasicBlock *InsertBB = Builder.GetInsertBlock();
899   Function *OuterFn = InsertBB->getParent();
900 
901   // Save the outer alloca block because the insertion iterator may get
902   // invalidated and we still need this later.
903   BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
904 
905   // Vector to remember instructions we used only during the modeling but which
906   // we want to delete at the end.
907   SmallVector<Instruction *, 4> ToBeDeleted;
908 
909   // Change the location to the outer alloca insertion point to create and
910   // initialize the allocas we pass into the parallel region.
911   Builder.restoreIP(OuterAllocaIP);
912   AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
913   AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
914 
915   // If there is an if condition we actually use the TIDAddr and ZeroAddr in the
916   // program, otherwise we only need them for modeling purposes to get the
917   // associated arguments in the outlined function. In the former case,
918   // initialize the allocas properly, in the latter case, delete them later.
919   if (IfCondition) {
920     Builder.CreateStore(Constant::getNullValue(Int32), TIDAddr);
921     Builder.CreateStore(Constant::getNullValue(Int32), ZeroAddr);
922   } else {
923     ToBeDeleted.push_back(TIDAddr);
924     ToBeDeleted.push_back(ZeroAddr);
925   }
926 
927   // Create an artificial insertion point that will also ensure the blocks we
928   // are about to split are not degenerated.
929   auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
930 
931   Instruction *ThenTI = UI, *ElseTI = nullptr;
932   if (IfCondition)
933     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
934 
935   BasicBlock *ThenBB = ThenTI->getParent();
936   BasicBlock *PRegEntryBB = ThenBB->splitBasicBlock(ThenTI, "omp.par.entry");
937   BasicBlock *PRegBodyBB =
938       PRegEntryBB->splitBasicBlock(ThenTI, "omp.par.region");
939   BasicBlock *PRegPreFiniBB =
940       PRegBodyBB->splitBasicBlock(ThenTI, "omp.par.pre_finalize");
941   BasicBlock *PRegExitBB =
942       PRegPreFiniBB->splitBasicBlock(ThenTI, "omp.par.exit");
943 
944   auto FiniCBWrapper = [&](InsertPointTy IP) {
945     // Hide "open-ended" blocks from the given FiniCB by setting the right jump
946     // target to the region exit block.
947     if (IP.getBlock()->end() == IP.getPoint()) {
948       IRBuilder<>::InsertPointGuard IPG(Builder);
949       Builder.restoreIP(IP);
950       Instruction *I = Builder.CreateBr(PRegExitBB);
951       IP = InsertPointTy(I->getParent(), I->getIterator());
952     }
953     assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
954            IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
955            "Unexpected insertion point for finalization call!");
956     return FiniCB(IP);
957   };
958 
959   FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
960 
961   // Generate the privatization allocas in the block that will become the entry
962   // of the outlined function.
963   Builder.SetInsertPoint(PRegEntryBB->getTerminator());
964   InsertPointTy InnerAllocaIP = Builder.saveIP();
965 
966   AllocaInst *PrivTIDAddr =
967       Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
968   Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
969 
970   // Add some fake uses for OpenMP provided arguments.
971   ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
972   Instruction *ZeroAddrUse =
973       Builder.CreateLoad(Int32, ZeroAddr, "zero.addr.use");
974   ToBeDeleted.push_back(ZeroAddrUse);
975 
976   // ThenBB
977   //   |
978   //   V
979   // PRegionEntryBB         <- Privatization allocas are placed here.
980   //   |
981   //   V
982   // PRegionBodyBB          <- BodeGen is invoked here.
983   //   |
984   //   V
985   // PRegPreFiniBB          <- The block we will start finalization from.
986   //   |
987   //   V
988   // PRegionExitBB          <- A common exit to simplify block collection.
989   //
990 
991   LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
992 
993   // Let the caller create the body.
994   assert(BodyGenCB && "Expected body generation callback!");
995   InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
996   BodyGenCB(InnerAllocaIP, CodeGenIP);
997 
998   LLVM_DEBUG(dbgs() << "After  body codegen: " << *OuterFn << "\n");
999 
1000   FunctionCallee RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
1001   if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
1002     if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1003       llvm::LLVMContext &Ctx = F->getContext();
1004       MDBuilder MDB(Ctx);
1005       // Annotate the callback behavior of the __kmpc_fork_call:
1006       //  - The callback callee is argument number 2 (microtask).
1007       //  - The first two arguments of the callback callee are unknown (-1).
1008       //  - All variadic arguments to the __kmpc_fork_call are passed to the
1009       //    callback callee.
1010       F->addMetadata(
1011           llvm::LLVMContext::MD_callback,
1012           *llvm::MDNode::get(
1013               Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
1014                                                /* VarArgsArePassed */ true)}));
1015     }
1016   }
1017 
1018   OutlineInfo OI;
1019   OI.PostOutlineCB = [=](Function &OutlinedFn) {
1020     // Add some known attributes.
1021     OutlinedFn.addParamAttr(0, Attribute::NoAlias);
1022     OutlinedFn.addParamAttr(1, Attribute::NoAlias);
1023     OutlinedFn.addFnAttr(Attribute::NoUnwind);
1024     OutlinedFn.addFnAttr(Attribute::NoRecurse);
1025 
1026     assert(OutlinedFn.arg_size() >= 2 &&
1027            "Expected at least tid and bounded tid as arguments");
1028     unsigned NumCapturedVars =
1029         OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
1030 
1031     CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
1032     CI->getParent()->setName("omp_parallel");
1033     Builder.SetInsertPoint(CI);
1034 
1035     // Build call __kmpc_fork_call(Ident, n, microtask, var1, .., varn);
1036     Value *ForkCallArgs[] = {
1037         Ident, Builder.getInt32(NumCapturedVars),
1038         Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
1039 
1040     SmallVector<Value *, 16> RealArgs;
1041     RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
1042     RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
1043 
1044     Builder.CreateCall(RTLFn, RealArgs);
1045 
1046     LLVM_DEBUG(dbgs() << "With fork_call placed: "
1047                       << *Builder.GetInsertBlock()->getParent() << "\n");
1048 
1049     InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
1050 
1051     // Initialize the local TID stack location with the argument value.
1052     Builder.SetInsertPoint(PrivTID);
1053     Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
1054     Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
1055 
1056     // If no "if" clause was present we do not need the call created during
1057     // outlining, otherwise we reuse it in the serialized parallel region.
1058     if (!ElseTI) {
1059       CI->eraseFromParent();
1060     } else {
1061 
1062       // If an "if" clause was present we are now generating the serialized
1063       // version into the "else" branch.
1064       Builder.SetInsertPoint(ElseTI);
1065 
1066       // Build calls __kmpc_serialized_parallel(&Ident, GTid);
1067       Value *SerializedParallelCallArgs[] = {Ident, ThreadID};
1068       Builder.CreateCall(
1069           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_serialized_parallel),
1070           SerializedParallelCallArgs);
1071 
1072       // OutlinedFn(&GTid, &zero, CapturedStruct);
1073       CI->removeFromParent();
1074       Builder.Insert(CI);
1075 
1076       // __kmpc_end_serialized_parallel(&Ident, GTid);
1077       Value *EndArgs[] = {Ident, ThreadID};
1078       Builder.CreateCall(
1079           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_serialized_parallel),
1080           EndArgs);
1081 
1082       LLVM_DEBUG(dbgs() << "With serialized parallel region: "
1083                         << *Builder.GetInsertBlock()->getParent() << "\n");
1084     }
1085 
1086     for (Instruction *I : ToBeDeleted)
1087       I->eraseFromParent();
1088   };
1089 
1090   // Adjust the finalization stack, verify the adjustment, and call the
1091   // finalize function a last time to finalize values between the pre-fini
1092   // block and the exit block if we left the parallel "the normal way".
1093   auto FiniInfo = FinalizationStack.pop_back_val();
1094   (void)FiniInfo;
1095   assert(FiniInfo.DK == OMPD_parallel &&
1096          "Unexpected finalization stack state!");
1097 
1098   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
1099 
1100   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
1101   FiniCB(PreFiniIP);
1102 
1103   OI.OuterAllocaBB = OuterAllocaBlock;
1104   OI.EntryBB = PRegEntryBB;
1105   OI.ExitBB = PRegExitBB;
1106 
1107   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
1108   SmallVector<BasicBlock *, 32> Blocks;
1109   OI.collectBlocks(ParallelRegionBlockSet, Blocks);
1110 
1111   // Ensure a single exit node for the outlined region by creating one.
1112   // We might have multiple incoming edges to the exit now due to finalizations,
1113   // e.g., cancel calls that cause the control flow to leave the region.
1114   BasicBlock *PRegOutlinedExitBB = PRegExitBB;
1115   PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
1116   PRegOutlinedExitBB->setName("omp.par.outlined.exit");
1117   Blocks.push_back(PRegOutlinedExitBB);
1118 
1119   CodeExtractorAnalysisCache CEAC(*OuterFn);
1120   CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
1121                           /* AggregateArgs */ false,
1122                           /* BlockFrequencyInfo */ nullptr,
1123                           /* BranchProbabilityInfo */ nullptr,
1124                           /* AssumptionCache */ nullptr,
1125                           /* AllowVarArgs */ true,
1126                           /* AllowAlloca */ true,
1127                           /* AllocationBlock */ OuterAllocaBlock,
1128                           /* Suffix */ ".omp_par");
1129 
1130   // Find inputs to, outputs from the code region.
1131   BasicBlock *CommonExit = nullptr;
1132   SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
1133   Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1134   Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
1135 
1136   LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
1137 
1138   FunctionCallee TIDRTLFn =
1139       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
1140 
1141   auto PrivHelper = [&](Value &V) {
1142     if (&V == TIDAddr || &V == ZeroAddr) {
1143       OI.ExcludeArgsFromAggregate.push_back(&V);
1144       return;
1145     }
1146 
1147     SetVector<Use *> Uses;
1148     for (Use &U : V.uses())
1149       if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
1150         if (ParallelRegionBlockSet.count(UserI->getParent()))
1151           Uses.insert(&U);
1152 
1153     // __kmpc_fork_call expects extra arguments as pointers. If the input
1154     // already has a pointer type, everything is fine. Otherwise, store the
1155     // value onto stack and load it back inside the to-be-outlined region. This
1156     // will ensure only the pointer will be passed to the function.
1157     // FIXME: if there are more than 15 trailing arguments, they must be
1158     // additionally packed in a struct.
1159     Value *Inner = &V;
1160     if (!V.getType()->isPointerTy()) {
1161       IRBuilder<>::InsertPointGuard Guard(Builder);
1162       LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
1163 
1164       Builder.restoreIP(OuterAllocaIP);
1165       Value *Ptr =
1166           Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
1167 
1168       // Store to stack at end of the block that currently branches to the entry
1169       // block of the to-be-outlined region.
1170       Builder.SetInsertPoint(InsertBB,
1171                              InsertBB->getTerminator()->getIterator());
1172       Builder.CreateStore(&V, Ptr);
1173 
1174       // Load back next to allocations in the to-be-outlined region.
1175       Builder.restoreIP(InnerAllocaIP);
1176       Inner = Builder.CreateLoad(V.getType(), Ptr);
1177     }
1178 
1179     Value *ReplacementValue = nullptr;
1180     CallInst *CI = dyn_cast<CallInst>(&V);
1181     if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
1182       ReplacementValue = PrivTID;
1183     } else {
1184       Builder.restoreIP(
1185           PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
1186       assert(ReplacementValue &&
1187              "Expected copy/create callback to set replacement value!");
1188       if (ReplacementValue == &V)
1189         return;
1190     }
1191 
1192     for (Use *UPtr : Uses)
1193       UPtr->set(ReplacementValue);
1194   };
1195 
1196   // Reset the inner alloca insertion as it will be used for loading the values
1197   // wrapped into pointers before passing them into the to-be-outlined region.
1198   // Configure it to insert immediately after the fake use of zero address so
1199   // that they are available in the generated body and so that the
1200   // OpenMP-related values (thread ID and zero address pointers) remain leading
1201   // in the argument list.
1202   InnerAllocaIP = IRBuilder<>::InsertPoint(
1203       ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
1204 
1205   // Reset the outer alloca insertion point to the entry of the relevant block
1206   // in case it was invalidated.
1207   OuterAllocaIP = IRBuilder<>::InsertPoint(
1208       OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
1209 
1210   for (Value *Input : Inputs) {
1211     LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
1212     PrivHelper(*Input);
1213   }
1214   LLVM_DEBUG({
1215     for (Value *Output : Outputs)
1216       LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
1217   });
1218   assert(Outputs.empty() &&
1219          "OpenMP outlining should not produce live-out values!");
1220 
1221   LLVM_DEBUG(dbgs() << "After  privatization: " << *OuterFn << "\n");
1222   LLVM_DEBUG({
1223     for (auto *BB : Blocks)
1224       dbgs() << " PBR: " << BB->getName() << "\n";
1225   });
1226 
1227   // Register the outlined info.
1228   addOutlineInfo(std::move(OI));
1229 
1230   InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
1231   UI->eraseFromParent();
1232 
1233   return AfterIP;
1234 }
1235 
1236 void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {
1237   // Build call void __kmpc_flush(ident_t *loc)
1238   uint32_t SrcLocStrSize;
1239   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1240   Value *Args[] = {getOrCreateIdent(SrcLocStr, SrcLocStrSize)};
1241 
1242   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
1243 }
1244 
1245 void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {
1246   if (!updateToLocation(Loc))
1247     return;
1248   emitFlush(Loc);
1249 }
1250 
1251 void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {
1252   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
1253   // global_tid);
1254   uint32_t SrcLocStrSize;
1255   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1256   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1257   Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
1258 
1259   // Ignore return result until untied tasks are supported.
1260   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
1261                      Args);
1262 }
1263 
1264 void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {
1265   if (!updateToLocation(Loc))
1266     return;
1267   emitTaskwaitImpl(Loc);
1268 }
1269 
1270 void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {
1271   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1272   uint32_t SrcLocStrSize;
1273   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1274   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1275   Constant *I32Null = ConstantInt::getNullValue(Int32);
1276   Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
1277 
1278   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
1279                      Args);
1280 }
1281 
1282 void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {
1283   if (!updateToLocation(Loc))
1284     return;
1285   emitTaskyieldImpl(Loc);
1286 }
1287 
1288 OpenMPIRBuilder::InsertPointTy
1289 OpenMPIRBuilder::createTask(const LocationDescription &Loc,
1290                             InsertPointTy AllocaIP, BodyGenCallbackTy BodyGenCB,
1291                             bool Tied, Value *Final) {
1292   if (!updateToLocation(Loc))
1293     return InsertPointTy();
1294 
1295   uint32_t SrcLocStrSize;
1296   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1297   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1298   // The current basic block is split into four basic blocks. After outlining,
1299   // they will be mapped as follows:
1300   // ```
1301   // def current_fn() {
1302   //   current_basic_block:
1303   //     br label %task.exit
1304   //   task.exit:
1305   //     ; instructions after task
1306   // }
1307   // def outlined_fn() {
1308   //   task.alloca:
1309   //     br label %task.body
1310   //   task.body:
1311   //     ret void
1312   // }
1313   // ```
1314   BasicBlock *TaskExitBB = splitBB(Builder, /*CreateBranch=*/true, "task.exit");
1315   BasicBlock *TaskBodyBB = splitBB(Builder, /*CreateBranch=*/true, "task.body");
1316   BasicBlock *TaskAllocaBB =
1317       splitBB(Builder, /*CreateBranch=*/true, "task.alloca");
1318 
1319   OutlineInfo OI;
1320   OI.EntryBB = TaskAllocaBB;
1321   OI.OuterAllocaBB = AllocaIP.getBlock();
1322   OI.ExitBB = TaskExitBB;
1323   OI.PostOutlineCB = [this, Ident, Tied, Final](Function &OutlinedFn) {
1324     // The input IR here looks like the following-
1325     // ```
1326     // func @current_fn() {
1327     //   outlined_fn(%args)
1328     // }
1329     // func @outlined_fn(%args) { ... }
1330     // ```
1331     //
1332     // This is changed to the following-
1333     //
1334     // ```
1335     // func @current_fn() {
1336     //   runtime_call(..., wrapper_fn, ...)
1337     // }
1338     // func @wrapper_fn(..., %args) {
1339     //   outlined_fn(%args)
1340     // }
1341     // func @outlined_fn(%args) { ... }
1342     // ```
1343 
1344     // The stale call instruction will be replaced with a new call instruction
1345     // for runtime call with a wrapper function.
1346     assert(OutlinedFn.getNumUses() == 1 &&
1347            "there must be a single user for the outlined function");
1348     CallInst *StaleCI = cast<CallInst>(OutlinedFn.user_back());
1349 
1350     // HasTaskData is true if any variables are captured in the outlined region,
1351     // false otherwise.
1352     bool HasTaskData = StaleCI->arg_size() > 0;
1353     Builder.SetInsertPoint(StaleCI);
1354 
1355     // Gather the arguments for emitting the runtime call for
1356     // @__kmpc_omp_task_alloc
1357     Function *TaskAllocFn =
1358         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task_alloc);
1359 
1360     // Arguments - `loc_ref` (Ident) and `gtid` (ThreadID)
1361     // call.
1362     Value *ThreadID = getOrCreateThreadID(Ident);
1363 
1364     // Argument - `flags`
1365     // Task is tied iff (Flags & 1) == 1.
1366     // Task is untied iff (Flags & 1) == 0.
1367     // Task is final iff (Flags & 2) == 2.
1368     // Task is not final iff (Flags & 2) == 0.
1369     // TODO: Handle the other flags.
1370     Value *Flags = Builder.getInt32(Tied);
1371     if (Final) {
1372       Value *FinalFlag =
1373           Builder.CreateSelect(Final, Builder.getInt32(2), Builder.getInt32(0));
1374       Flags = Builder.CreateOr(FinalFlag, Flags);
1375     }
1376 
1377     // Argument - `sizeof_kmp_task_t` (TaskSize)
1378     // Tasksize refers to the size in bytes of kmp_task_t data structure
1379     // including private vars accessed in task.
1380     Value *TaskSize = Builder.getInt64(0);
1381     if (HasTaskData) {
1382       AllocaInst *ArgStructAlloca =
1383           dyn_cast<AllocaInst>(StaleCI->getArgOperand(0));
1384       assert(ArgStructAlloca &&
1385              "Unable to find the alloca instruction corresponding to arguments "
1386              "for extracted function");
1387       StructType *ArgStructType =
1388           dyn_cast<StructType>(ArgStructAlloca->getAllocatedType());
1389       assert(ArgStructType && "Unable to find struct type corresponding to "
1390                               "arguments for extracted function");
1391       TaskSize =
1392           Builder.getInt64(M.getDataLayout().getTypeStoreSize(ArgStructType));
1393     }
1394 
1395     // TODO: Argument - sizeof_shareds
1396 
1397     // Argument - task_entry (the wrapper function)
1398     // If the outlined function has some captured variables (i.e. HasTaskData is
1399     // true), then the wrapper function will have an additional argument (the
1400     // struct containing captured variables). Otherwise, no such argument will
1401     // be present.
1402     SmallVector<Type *> WrapperArgTys{Builder.getInt32Ty()};
1403     if (HasTaskData)
1404       WrapperArgTys.push_back(OutlinedFn.getArg(0)->getType());
1405     FunctionCallee WrapperFuncVal = M.getOrInsertFunction(
1406         (Twine(OutlinedFn.getName()) + ".wrapper").str(),
1407         FunctionType::get(Builder.getInt32Ty(), WrapperArgTys, false));
1408     Function *WrapperFunc = dyn_cast<Function>(WrapperFuncVal.getCallee());
1409     PointerType *WrapperFuncBitcastType =
1410         FunctionType::get(Builder.getInt32Ty(),
1411                           {Builder.getInt32Ty(), Builder.getInt8PtrTy()}, false)
1412             ->getPointerTo();
1413     Value *WrapperFuncBitcast =
1414         ConstantExpr::getBitCast(WrapperFunc, WrapperFuncBitcastType);
1415 
1416     // Emit the @__kmpc_omp_task_alloc runtime call
1417     // The runtime call returns a pointer to an area where the task captured
1418     // variables must be copied before the task is run (NewTaskData)
1419     CallInst *NewTaskData = Builder.CreateCall(
1420         TaskAllocFn,
1421         {/*loc_ref=*/Ident, /*gtid=*/ThreadID, /*flags=*/Flags,
1422          /*sizeof_task=*/TaskSize, /*sizeof_shared=*/Builder.getInt64(0),
1423          /*task_func=*/WrapperFuncBitcast});
1424 
1425     // Copy the arguments for outlined function
1426     if (HasTaskData) {
1427       Value *TaskData = StaleCI->getArgOperand(0);
1428       Align Alignment = TaskData->getPointerAlignment(M.getDataLayout());
1429       Builder.CreateMemCpy(NewTaskData, Alignment, TaskData, Alignment,
1430                            TaskSize);
1431     }
1432 
1433     // Emit the @__kmpc_omp_task runtime call to spawn the task
1434     Function *TaskFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_task);
1435     Builder.CreateCall(TaskFn, {Ident, ThreadID, NewTaskData});
1436 
1437     StaleCI->eraseFromParent();
1438 
1439     // Emit the body for wrapper function
1440     BasicBlock *WrapperEntryBB =
1441         BasicBlock::Create(M.getContext(), "", WrapperFunc);
1442     Builder.SetInsertPoint(WrapperEntryBB);
1443     if (HasTaskData)
1444       Builder.CreateCall(&OutlinedFn, {WrapperFunc->getArg(1)});
1445     else
1446       Builder.CreateCall(&OutlinedFn);
1447     Builder.CreateRet(Builder.getInt32(0));
1448   };
1449 
1450   addOutlineInfo(std::move(OI));
1451 
1452   InsertPointTy TaskAllocaIP =
1453       InsertPointTy(TaskAllocaBB, TaskAllocaBB->begin());
1454   InsertPointTy TaskBodyIP = InsertPointTy(TaskBodyBB, TaskBodyBB->begin());
1455   BodyGenCB(TaskAllocaIP, TaskBodyIP);
1456   Builder.SetInsertPoint(TaskExitBB);
1457 
1458   return Builder.saveIP();
1459 }
1460 
1461 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSections(
1462     const LocationDescription &Loc, InsertPointTy AllocaIP,
1463     ArrayRef<StorableBodyGenCallbackTy> SectionCBs, PrivatizeCallbackTy PrivCB,
1464     FinalizeCallbackTy FiniCB, bool IsCancellable, bool IsNowait) {
1465   assert(!isConflictIP(AllocaIP, Loc.IP) && "Dedicated IP allocas required");
1466 
1467   if (!updateToLocation(Loc))
1468     return Loc.IP;
1469 
1470   auto FiniCBWrapper = [&](InsertPointTy IP) {
1471     if (IP.getBlock()->end() != IP.getPoint())
1472       return FiniCB(IP);
1473     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1474     // will fail because that function requires the Finalization Basic Block to
1475     // have a terminator, which is already removed by EmitOMPRegionBody.
1476     // IP is currently at cancelation block.
1477     // We need to backtrack to the condition block to fetch
1478     // the exit block and create a branch from cancelation
1479     // to exit block.
1480     IRBuilder<>::InsertPointGuard IPG(Builder);
1481     Builder.restoreIP(IP);
1482     auto *CaseBB = IP.getBlock()->getSinglePredecessor();
1483     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1484     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1485     Instruction *I = Builder.CreateBr(ExitBB);
1486     IP = InsertPointTy(I->getParent(), I->getIterator());
1487     return FiniCB(IP);
1488   };
1489 
1490   FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});
1491 
1492   // Each section is emitted as a switch case
1493   // Each finalization callback is handled from clang.EmitOMPSectionDirective()
1494   // -> OMP.createSection() which generates the IR for each section
1495   // Iterate through all sections and emit a switch construct:
1496   // switch (IV) {
1497   //   case 0:
1498   //     <SectionStmt[0]>;
1499   //     break;
1500   // ...
1501   //   case <NumSection> - 1:
1502   //     <SectionStmt[<NumSection> - 1]>;
1503   //     break;
1504   // }
1505   // ...
1506   // section_loop.after:
1507   // <FiniCB>;
1508   auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {
1509     Builder.restoreIP(CodeGenIP);
1510     BasicBlock *Continue =
1511         splitBBWithSuffix(Builder, /*CreateBranch=*/false, ".sections.after");
1512     Function *CurFn = Continue->getParent();
1513     SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, Continue);
1514 
1515     unsigned CaseNumber = 0;
1516     for (auto SectionCB : SectionCBs) {
1517       BasicBlock *CaseBB = BasicBlock::Create(
1518           M.getContext(), "omp_section_loop.body.case", CurFn, Continue);
1519       SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
1520       Builder.SetInsertPoint(CaseBB);
1521       BranchInst *CaseEndBr = Builder.CreateBr(Continue);
1522       SectionCB(InsertPointTy(),
1523                 {CaseEndBr->getParent(), CaseEndBr->getIterator()});
1524       CaseNumber++;
1525     }
1526     // remove the existing terminator from body BB since there can be no
1527     // terminators after switch/case
1528   };
1529   // Loop body ends here
1530   // LowerBound, UpperBound, and STride for createCanonicalLoop
1531   Type *I32Ty = Type::getInt32Ty(M.getContext());
1532   Value *LB = ConstantInt::get(I32Ty, 0);
1533   Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
1534   Value *ST = ConstantInt::get(I32Ty, 1);
1535   llvm::CanonicalLoopInfo *LoopInfo = createCanonicalLoop(
1536       Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
1537   InsertPointTy AfterIP =
1538       applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);
1539 
1540   // Apply the finalization callback in LoopAfterBB
1541   auto FiniInfo = FinalizationStack.pop_back_val();
1542   assert(FiniInfo.DK == OMPD_sections &&
1543          "Unexpected finalization stack state!");
1544   if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {
1545     Builder.restoreIP(AfterIP);
1546     BasicBlock *FiniBB =
1547         splitBBWithSuffix(Builder, /*CreateBranch=*/true, "sections.fini");
1548     CB(Builder.saveIP());
1549     AfterIP = {FiniBB, FiniBB->begin()};
1550   }
1551 
1552   return AfterIP;
1553 }
1554 
1555 OpenMPIRBuilder::InsertPointTy
1556 OpenMPIRBuilder::createSection(const LocationDescription &Loc,
1557                                BodyGenCallbackTy BodyGenCB,
1558                                FinalizeCallbackTy FiniCB) {
1559   if (!updateToLocation(Loc))
1560     return Loc.IP;
1561 
1562   auto FiniCBWrapper = [&](InsertPointTy IP) {
1563     if (IP.getBlock()->end() != IP.getPoint())
1564       return FiniCB(IP);
1565     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1566     // will fail because that function requires the Finalization Basic Block to
1567     // have a terminator, which is already removed by EmitOMPRegionBody.
1568     // IP is currently at cancelation block.
1569     // We need to backtrack to the condition block to fetch
1570     // the exit block and create a branch from cancelation
1571     // to exit block.
1572     IRBuilder<>::InsertPointGuard IPG(Builder);
1573     Builder.restoreIP(IP);
1574     auto *CaseBB = Loc.IP.getBlock();
1575     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1576     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1577     Instruction *I = Builder.CreateBr(ExitBB);
1578     IP = InsertPointTy(I->getParent(), I->getIterator());
1579     return FiniCB(IP);
1580   };
1581 
1582   Directive OMPD = Directive::OMPD_sections;
1583   // Since we are using Finalization Callback here, HasFinalize
1584   // and IsCancellable have to be true
1585   return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
1586                               /*Conditional*/ false, /*hasFinalize*/ true,
1587                               /*IsCancellable*/ true);
1588 }
1589 
1590 /// Create a function with a unique name and a "void (i8*, i8*)" signature in
1591 /// the given module and return it.
1592 Function *getFreshReductionFunc(Module &M) {
1593   Type *VoidTy = Type::getVoidTy(M.getContext());
1594   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1595   auto *FuncTy =
1596       FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
1597   return Function::Create(FuncTy, GlobalVariable::InternalLinkage,
1598                           M.getDataLayout().getDefaultGlobalsAddressSpace(),
1599                           ".omp.reduction.func", &M);
1600 }
1601 
1602 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createReductions(
1603     const LocationDescription &Loc, InsertPointTy AllocaIP,
1604     ArrayRef<ReductionInfo> ReductionInfos, bool IsNoWait) {
1605   for (const ReductionInfo &RI : ReductionInfos) {
1606     (void)RI;
1607     assert(RI.Variable && "expected non-null variable");
1608     assert(RI.PrivateVariable && "expected non-null private variable");
1609     assert(RI.ReductionGen && "expected non-null reduction generator callback");
1610     assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&
1611            "expected variables and their private equivalents to have the same "
1612            "type");
1613     assert(RI.Variable->getType()->isPointerTy() &&
1614            "expected variables to be pointers");
1615   }
1616 
1617   if (!updateToLocation(Loc))
1618     return InsertPointTy();
1619 
1620   BasicBlock *InsertBlock = Loc.IP.getBlock();
1621   BasicBlock *ContinuationBlock =
1622       InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");
1623   InsertBlock->getTerminator()->eraseFromParent();
1624 
1625   // Create and populate array of type-erased pointers to private reduction
1626   // values.
1627   unsigned NumReductions = ReductionInfos.size();
1628   Type *RedArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumReductions);
1629   Builder.restoreIP(AllocaIP);
1630   Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
1631 
1632   Builder.SetInsertPoint(InsertBlock, InsertBlock->end());
1633 
1634   for (auto En : enumerate(ReductionInfos)) {
1635     unsigned Index = En.index();
1636     const ReductionInfo &RI = En.value();
1637     Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
1638         RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
1639     Value *Casted =
1640         Builder.CreateBitCast(RI.PrivateVariable, Builder.getInt8PtrTy(),
1641                               "private.red.var." + Twine(Index) + ".casted");
1642     Builder.CreateStore(Casted, RedArrayElemPtr);
1643   }
1644 
1645   // Emit a call to the runtime function that orchestrates the reduction.
1646   // Declare the reduction function in the process.
1647   Function *Func = Builder.GetInsertBlock()->getParent();
1648   Module *Module = Func->getParent();
1649   Value *RedArrayPtr =
1650       Builder.CreateBitCast(RedArray, Builder.getInt8PtrTy(), "red.array.ptr");
1651   uint32_t SrcLocStrSize;
1652   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1653   bool CanGenerateAtomic =
1654       llvm::all_of(ReductionInfos, [](const ReductionInfo &RI) {
1655         return RI.AtomicReductionGen;
1656       });
1657   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
1658                                   CanGenerateAtomic
1659                                       ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
1660                                       : IdentFlag(0));
1661   Value *ThreadId = getOrCreateThreadID(Ident);
1662   Constant *NumVariables = Builder.getInt32(NumReductions);
1663   const DataLayout &DL = Module->getDataLayout();
1664   unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
1665   Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);
1666   Function *ReductionFunc = getFreshReductionFunc(*Module);
1667   Value *Lock = getOMPCriticalRegionLock(".reduction");
1668   Function *ReduceFunc = getOrCreateRuntimeFunctionPtr(
1669       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
1670                : RuntimeFunction::OMPRTL___kmpc_reduce);
1671   CallInst *ReduceCall =
1672       Builder.CreateCall(ReduceFunc,
1673                          {Ident, ThreadId, NumVariables, RedArraySize,
1674                           RedArrayPtr, ReductionFunc, Lock},
1675                          "reduce");
1676 
1677   // Create final reduction entry blocks for the atomic and non-atomic case.
1678   // Emit IR that dispatches control flow to one of the blocks based on the
1679   // reduction supporting the atomic mode.
1680   BasicBlock *NonAtomicRedBlock =
1681       BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
1682   BasicBlock *AtomicRedBlock =
1683       BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
1684   SwitchInst *Switch =
1685       Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
1686   Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
1687   Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
1688 
1689   // Populate the non-atomic reduction using the elementwise reduction function.
1690   // This loads the elements from the global and private variables and reduces
1691   // them before storing back the result to the global variable.
1692   Builder.SetInsertPoint(NonAtomicRedBlock);
1693   for (auto En : enumerate(ReductionInfos)) {
1694     const ReductionInfo &RI = En.value();
1695     Type *ValueType = RI.ElementType;
1696     Value *RedValue = Builder.CreateLoad(ValueType, RI.Variable,
1697                                          "red.value." + Twine(En.index()));
1698     Value *PrivateRedValue =
1699         Builder.CreateLoad(ValueType, RI.PrivateVariable,
1700                            "red.private.value." + Twine(En.index()));
1701     Value *Reduced;
1702     Builder.restoreIP(
1703         RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced));
1704     if (!Builder.GetInsertBlock())
1705       return InsertPointTy();
1706     Builder.CreateStore(Reduced, RI.Variable);
1707   }
1708   Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
1709       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
1710                : RuntimeFunction::OMPRTL___kmpc_end_reduce);
1711   Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});
1712   Builder.CreateBr(ContinuationBlock);
1713 
1714   // Populate the atomic reduction using the atomic elementwise reduction
1715   // function. There are no loads/stores here because they will be happening
1716   // inside the atomic elementwise reduction.
1717   Builder.SetInsertPoint(AtomicRedBlock);
1718   if (CanGenerateAtomic) {
1719     for (const ReductionInfo &RI : ReductionInfos) {
1720       Builder.restoreIP(RI.AtomicReductionGen(Builder.saveIP(), RI.ElementType,
1721                                               RI.Variable, RI.PrivateVariable));
1722       if (!Builder.GetInsertBlock())
1723         return InsertPointTy();
1724     }
1725     Builder.CreateBr(ContinuationBlock);
1726   } else {
1727     Builder.CreateUnreachable();
1728   }
1729 
1730   // Populate the outlined reduction function using the elementwise reduction
1731   // function. Partial values are extracted from the type-erased array of
1732   // pointers to private variables.
1733   BasicBlock *ReductionFuncBlock =
1734       BasicBlock::Create(Module->getContext(), "", ReductionFunc);
1735   Builder.SetInsertPoint(ReductionFuncBlock);
1736   Value *LHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(0),
1737                                              RedArrayTy->getPointerTo());
1738   Value *RHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(1),
1739                                              RedArrayTy->getPointerTo());
1740   for (auto En : enumerate(ReductionInfos)) {
1741     const ReductionInfo &RI = En.value();
1742     Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1743         RedArrayTy, LHSArrayPtr, 0, En.index());
1744     Value *LHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), LHSI8PtrPtr);
1745     Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());
1746     Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
1747     Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1748         RedArrayTy, RHSArrayPtr, 0, En.index());
1749     Value *RHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), RHSI8PtrPtr);
1750     Value *RHSPtr =
1751         Builder.CreateBitCast(RHSI8Ptr, RI.PrivateVariable->getType());
1752     Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
1753     Value *Reduced;
1754     Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced));
1755     if (!Builder.GetInsertBlock())
1756       return InsertPointTy();
1757     Builder.CreateStore(Reduced, LHSPtr);
1758   }
1759   Builder.CreateRetVoid();
1760 
1761   Builder.SetInsertPoint(ContinuationBlock);
1762   return Builder.saveIP();
1763 }
1764 
1765 OpenMPIRBuilder::InsertPointTy
1766 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
1767                               BodyGenCallbackTy BodyGenCB,
1768                               FinalizeCallbackTy FiniCB) {
1769 
1770   if (!updateToLocation(Loc))
1771     return Loc.IP;
1772 
1773   Directive OMPD = Directive::OMPD_master;
1774   uint32_t SrcLocStrSize;
1775   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1776   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1777   Value *ThreadId = getOrCreateThreadID(Ident);
1778   Value *Args[] = {Ident, ThreadId};
1779 
1780   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
1781   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1782 
1783   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
1784   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1785 
1786   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1787                               /*Conditional*/ true, /*hasFinalize*/ true);
1788 }
1789 
1790 OpenMPIRBuilder::InsertPointTy
1791 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
1792                               BodyGenCallbackTy BodyGenCB,
1793                               FinalizeCallbackTy FiniCB, Value *Filter) {
1794   if (!updateToLocation(Loc))
1795     return Loc.IP;
1796 
1797   Directive OMPD = Directive::OMPD_masked;
1798   uint32_t SrcLocStrSize;
1799   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1800   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1801   Value *ThreadId = getOrCreateThreadID(Ident);
1802   Value *Args[] = {Ident, ThreadId, Filter};
1803   Value *ArgsEnd[] = {Ident, ThreadId};
1804 
1805   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
1806   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1807 
1808   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
1809   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
1810 
1811   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1812                               /*Conditional*/ true, /*hasFinalize*/ true);
1813 }
1814 
1815 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
1816     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
1817     BasicBlock *PostInsertBefore, const Twine &Name) {
1818   Module *M = F->getParent();
1819   LLVMContext &Ctx = M->getContext();
1820   Type *IndVarTy = TripCount->getType();
1821 
1822   // Create the basic block structure.
1823   BasicBlock *Preheader =
1824       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
1825   BasicBlock *Header =
1826       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
1827   BasicBlock *Cond =
1828       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
1829   BasicBlock *Body =
1830       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
1831   BasicBlock *Latch =
1832       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
1833   BasicBlock *Exit =
1834       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
1835   BasicBlock *After =
1836       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
1837 
1838   // Use specified DebugLoc for new instructions.
1839   Builder.SetCurrentDebugLocation(DL);
1840 
1841   Builder.SetInsertPoint(Preheader);
1842   Builder.CreateBr(Header);
1843 
1844   Builder.SetInsertPoint(Header);
1845   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
1846   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
1847   Builder.CreateBr(Cond);
1848 
1849   Builder.SetInsertPoint(Cond);
1850   Value *Cmp =
1851       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
1852   Builder.CreateCondBr(Cmp, Body, Exit);
1853 
1854   Builder.SetInsertPoint(Body);
1855   Builder.CreateBr(Latch);
1856 
1857   Builder.SetInsertPoint(Latch);
1858   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
1859                                   "omp_" + Name + ".next", /*HasNUW=*/true);
1860   Builder.CreateBr(Header);
1861   IndVarPHI->addIncoming(Next, Latch);
1862 
1863   Builder.SetInsertPoint(Exit);
1864   Builder.CreateBr(After);
1865 
1866   // Remember and return the canonical control flow.
1867   LoopInfos.emplace_front();
1868   CanonicalLoopInfo *CL = &LoopInfos.front();
1869 
1870   CL->Header = Header;
1871   CL->Cond = Cond;
1872   CL->Latch = Latch;
1873   CL->Exit = Exit;
1874 
1875 #ifndef NDEBUG
1876   CL->assertOK();
1877 #endif
1878   return CL;
1879 }
1880 
1881 CanonicalLoopInfo *
1882 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
1883                                      LoopBodyGenCallbackTy BodyGenCB,
1884                                      Value *TripCount, const Twine &Name) {
1885   BasicBlock *BB = Loc.IP.getBlock();
1886   BasicBlock *NextBB = BB->getNextNode();
1887 
1888   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
1889                                              NextBB, NextBB, Name);
1890   BasicBlock *After = CL->getAfter();
1891 
1892   // If location is not set, don't connect the loop.
1893   if (updateToLocation(Loc)) {
1894     // Split the loop at the insertion point: Branch to the preheader and move
1895     // every following instruction to after the loop (the After BB). Also, the
1896     // new successor is the loop's after block.
1897     spliceBB(Builder, After, /*CreateBranch=*/false);
1898     Builder.CreateBr(CL->getPreheader());
1899   }
1900 
1901   // Emit the body content. We do it after connecting the loop to the CFG to
1902   // avoid that the callback encounters degenerate BBs.
1903   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
1904 
1905 #ifndef NDEBUG
1906   CL->assertOK();
1907 #endif
1908   return CL;
1909 }
1910 
1911 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
1912     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
1913     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
1914     InsertPointTy ComputeIP, const Twine &Name) {
1915 
1916   // Consider the following difficulties (assuming 8-bit signed integers):
1917   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
1918   //      DO I = 1, 100, 50
1919   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
1920   //      DO I = 100, 0, -128
1921 
1922   // Start, Stop and Step must be of the same integer type.
1923   auto *IndVarTy = cast<IntegerType>(Start->getType());
1924   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
1925   assert(IndVarTy == Step->getType() && "Step type mismatch");
1926 
1927   LocationDescription ComputeLoc =
1928       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
1929   updateToLocation(ComputeLoc);
1930 
1931   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
1932   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
1933 
1934   // Like Step, but always positive.
1935   Value *Incr = Step;
1936 
1937   // Distance between Start and Stop; always positive.
1938   Value *Span;
1939 
1940   // Condition whether there are no iterations are executed at all, e.g. because
1941   // UB < LB.
1942   Value *ZeroCmp;
1943 
1944   if (IsSigned) {
1945     // Ensure that increment is positive. If not, negate and invert LB and UB.
1946     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
1947     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
1948     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
1949     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
1950     Span = Builder.CreateSub(UB, LB, "", false, true);
1951     ZeroCmp = Builder.CreateICmp(
1952         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
1953   } else {
1954     Span = Builder.CreateSub(Stop, Start, "", true);
1955     ZeroCmp = Builder.CreateICmp(
1956         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
1957   }
1958 
1959   Value *CountIfLooping;
1960   if (InclusiveStop) {
1961     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
1962   } else {
1963     // Avoid incrementing past stop since it could overflow.
1964     Value *CountIfTwo = Builder.CreateAdd(
1965         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
1966     Value *OneCmp = Builder.CreateICmp(
1967         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Span, Incr);
1968     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
1969   }
1970   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
1971                                           "omp_" + Name + ".tripcount");
1972 
1973   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
1974     Builder.restoreIP(CodeGenIP);
1975     Value *Span = Builder.CreateMul(IV, Step);
1976     Value *IndVar = Builder.CreateAdd(Span, Start);
1977     BodyGenCB(Builder.saveIP(), IndVar);
1978   };
1979   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
1980   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
1981 }
1982 
1983 // Returns an LLVM function to call for initializing loop bounds using OpenMP
1984 // static scheduling depending on `type`. Only i32 and i64 are supported by the
1985 // runtime. Always interpret integers as unsigned similarly to
1986 // CanonicalLoopInfo.
1987 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
1988                                                   OpenMPIRBuilder &OMPBuilder) {
1989   unsigned Bitwidth = Ty->getIntegerBitWidth();
1990   if (Bitwidth == 32)
1991     return OMPBuilder.getOrCreateRuntimeFunction(
1992         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
1993   if (Bitwidth == 64)
1994     return OMPBuilder.getOrCreateRuntimeFunction(
1995         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
1996   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1997 }
1998 
1999 OpenMPIRBuilder::InsertPointTy
2000 OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
2001                                           InsertPointTy AllocaIP,
2002                                           bool NeedsBarrier) {
2003   assert(CLI->isValid() && "Requires a valid canonical loop");
2004   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2005          "Require dedicated allocate IP");
2006 
2007   // Set up the source location value for OpenMP runtime.
2008   Builder.restoreIP(CLI->getPreheaderIP());
2009   Builder.SetCurrentDebugLocation(DL);
2010 
2011   uint32_t SrcLocStrSize;
2012   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2013   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2014 
2015   // Declare useful OpenMP runtime functions.
2016   Value *IV = CLI->getIndVar();
2017   Type *IVTy = IV->getType();
2018   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
2019   FunctionCallee StaticFini =
2020       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2021 
2022   // Allocate space for computed loop bounds as expected by the "init" function.
2023   Builder.restoreIP(AllocaIP);
2024   Type *I32Type = Type::getInt32Ty(M.getContext());
2025   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2026   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2027   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2028   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2029 
2030   // At the end of the preheader, prepare for calling the "init" function by
2031   // storing the current loop bounds into the allocated space. A canonical loop
2032   // always iterates from 0 to trip-count with step 1. Note that "init" expects
2033   // and produces an inclusive upper bound.
2034   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2035   Constant *Zero = ConstantInt::get(IVTy, 0);
2036   Constant *One = ConstantInt::get(IVTy, 1);
2037   Builder.CreateStore(Zero, PLowerBound);
2038   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
2039   Builder.CreateStore(UpperBound, PUpperBound);
2040   Builder.CreateStore(One, PStride);
2041 
2042   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2043 
2044   Constant *SchedulingType = ConstantInt::get(
2045       I32Type, static_cast<int>(OMPScheduleType::UnorderedStatic));
2046 
2047   // Call the "init" function and update the trip count of the loop with the
2048   // value it produced.
2049   Builder.CreateCall(StaticInit,
2050                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
2051                       PUpperBound, PStride, One, Zero});
2052   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
2053   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
2054   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
2055   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
2056   CLI->setTripCount(TripCount);
2057 
2058   // Update all uses of the induction variable except the one in the condition
2059   // block that compares it with the actual upper bound, and the increment in
2060   // the latch block.
2061 
2062   CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
2063     Builder.SetInsertPoint(CLI->getBody(),
2064                            CLI->getBody()->getFirstInsertionPt());
2065     Builder.SetCurrentDebugLocation(DL);
2066     return Builder.CreateAdd(OldIV, LowerBound);
2067   });
2068 
2069   // In the "exit" block, call the "fini" function.
2070   Builder.SetInsertPoint(CLI->getExit(),
2071                          CLI->getExit()->getTerminator()->getIterator());
2072   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2073 
2074   // Add the barrier if requested.
2075   if (NeedsBarrier)
2076     createBarrier(LocationDescription(Builder.saveIP(), DL),
2077                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2078                   /* CheckCancelFlag */ false);
2079 
2080   InsertPointTy AfterIP = CLI->getAfterIP();
2081   CLI->invalidate();
2082 
2083   return AfterIP;
2084 }
2085 
2086 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
2087     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2088     bool NeedsBarrier, Value *ChunkSize) {
2089   assert(CLI->isValid() && "Requires a valid canonical loop");
2090   assert(ChunkSize && "Chunk size is required");
2091 
2092   LLVMContext &Ctx = CLI->getFunction()->getContext();
2093   Value *IV = CLI->getIndVar();
2094   Value *OrigTripCount = CLI->getTripCount();
2095   Type *IVTy = IV->getType();
2096   assert(IVTy->getIntegerBitWidth() <= 64 &&
2097          "Max supported tripcount bitwidth is 64 bits");
2098   Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
2099                                                         : Type::getInt64Ty(Ctx);
2100   Type *I32Type = Type::getInt32Ty(M.getContext());
2101   Constant *Zero = ConstantInt::get(InternalIVTy, 0);
2102   Constant *One = ConstantInt::get(InternalIVTy, 1);
2103 
2104   // Declare useful OpenMP runtime functions.
2105   FunctionCallee StaticInit =
2106       getKmpcForStaticInitForType(InternalIVTy, M, *this);
2107   FunctionCallee StaticFini =
2108       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
2109 
2110   // Allocate space for computed loop bounds as expected by the "init" function.
2111   Builder.restoreIP(AllocaIP);
2112   Builder.SetCurrentDebugLocation(DL);
2113   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2114   Value *PLowerBound =
2115       Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
2116   Value *PUpperBound =
2117       Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
2118   Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
2119 
2120   // Set up the source location value for the OpenMP runtime.
2121   Builder.restoreIP(CLI->getPreheaderIP());
2122   Builder.SetCurrentDebugLocation(DL);
2123 
2124   // TODO: Detect overflow in ubsan or max-out with current tripcount.
2125   Value *CastedChunkSize =
2126       Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");
2127   Value *CastedTripCount =
2128       Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
2129 
2130   Constant *SchedulingType = ConstantInt::get(
2131       I32Type, static_cast<int>(OMPScheduleType::UnorderedStaticChunked));
2132   Builder.CreateStore(Zero, PLowerBound);
2133   Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
2134   Builder.CreateStore(OrigUpperBound, PUpperBound);
2135   Builder.CreateStore(One, PStride);
2136 
2137   // Call the "init" function and update the trip count of the loop with the
2138   // value it produced.
2139   uint32_t SrcLocStrSize;
2140   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2141   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2142   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2143   Builder.CreateCall(StaticInit,
2144                      {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
2145                       /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
2146                       /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
2147                       /*pstride=*/PStride, /*incr=*/One,
2148                       /*chunk=*/CastedChunkSize});
2149 
2150   // Load values written by the "init" function.
2151   Value *FirstChunkStart =
2152       Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
2153   Value *FirstChunkStop =
2154       Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
2155   Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
2156   Value *ChunkRange =
2157       Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
2158   Value *NextChunkStride =
2159       Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
2160 
2161   // Create outer "dispatch" loop for enumerating the chunks.
2162   BasicBlock *DispatchEnter = splitBB(Builder, true);
2163   Value *DispatchCounter;
2164   CanonicalLoopInfo *DispatchCLI = createCanonicalLoop(
2165       {Builder.saveIP(), DL},
2166       [&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },
2167       FirstChunkStart, CastedTripCount, NextChunkStride,
2168       /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
2169       "dispatch");
2170 
2171   // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
2172   // not have to preserve the canonical invariant.
2173   BasicBlock *DispatchBody = DispatchCLI->getBody();
2174   BasicBlock *DispatchLatch = DispatchCLI->getLatch();
2175   BasicBlock *DispatchExit = DispatchCLI->getExit();
2176   BasicBlock *DispatchAfter = DispatchCLI->getAfter();
2177   DispatchCLI->invalidate();
2178 
2179   // Rewire the original loop to become the chunk loop inside the dispatch loop.
2180   redirectTo(DispatchAfter, CLI->getAfter(), DL);
2181   redirectTo(CLI->getExit(), DispatchLatch, DL);
2182   redirectTo(DispatchBody, DispatchEnter, DL);
2183 
2184   // Prepare the prolog of the chunk loop.
2185   Builder.restoreIP(CLI->getPreheaderIP());
2186   Builder.SetCurrentDebugLocation(DL);
2187 
2188   // Compute the number of iterations of the chunk loop.
2189   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
2190   Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
2191   Value *IsLastChunk =
2192       Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
2193   Value *CountUntilOrigTripCount =
2194       Builder.CreateSub(CastedTripCount, DispatchCounter);
2195   Value *ChunkTripCount = Builder.CreateSelect(
2196       IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
2197   Value *BackcastedChunkTC =
2198       Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
2199   CLI->setTripCount(BackcastedChunkTC);
2200 
2201   // Update all uses of the induction variable except the one in the condition
2202   // block that compares it with the actual upper bound, and the increment in
2203   // the latch block.
2204   Value *BackcastedDispatchCounter =
2205       Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
2206   CLI->mapIndVar([&](Instruction *) -> Value * {
2207     Builder.restoreIP(CLI->getBodyIP());
2208     return Builder.CreateAdd(IV, BackcastedDispatchCounter);
2209   });
2210 
2211   // In the "exit" block, call the "fini" function.
2212   Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());
2213   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
2214 
2215   // Add the barrier if requested.
2216   if (NeedsBarrier)
2217     createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
2218                   /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
2219 
2220 #ifndef NDEBUG
2221   // Even though we currently do not support applying additional methods to it,
2222   // the chunk loop should remain a canonical loop.
2223   CLI->assertOK();
2224 #endif
2225 
2226   return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};
2227 }
2228 
2229 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyWorkshareLoop(
2230     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2231     bool NeedsBarrier, llvm::omp::ScheduleKind SchedKind,
2232     llvm::Value *ChunkSize, bool HasSimdModifier, bool HasMonotonicModifier,
2233     bool HasNonmonotonicModifier, bool HasOrderedClause) {
2234   OMPScheduleType EffectiveScheduleType = computeOpenMPScheduleType(
2235       SchedKind, ChunkSize, HasSimdModifier, HasMonotonicModifier,
2236       HasNonmonotonicModifier, HasOrderedClause);
2237 
2238   bool IsOrdered = (EffectiveScheduleType & OMPScheduleType::ModifierOrdered) ==
2239                    OMPScheduleType::ModifierOrdered;
2240   switch (EffectiveScheduleType & ~OMPScheduleType::ModifierMask) {
2241   case OMPScheduleType::BaseStatic:
2242     assert(!ChunkSize && "No chunk size with static-chunked schedule");
2243     if (IsOrdered)
2244       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2245                                        NeedsBarrier, ChunkSize);
2246     // FIXME: Monotonicity ignored?
2247     return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);
2248 
2249   case OMPScheduleType::BaseStaticChunked:
2250     if (IsOrdered)
2251       return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2252                                        NeedsBarrier, ChunkSize);
2253     // FIXME: Monotonicity ignored?
2254     return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,
2255                                            ChunkSize);
2256 
2257   case OMPScheduleType::BaseRuntime:
2258   case OMPScheduleType::BaseAuto:
2259   case OMPScheduleType::BaseGreedy:
2260   case OMPScheduleType::BaseBalanced:
2261   case OMPScheduleType::BaseSteal:
2262   case OMPScheduleType::BaseGuidedSimd:
2263   case OMPScheduleType::BaseRuntimeSimd:
2264     assert(!ChunkSize &&
2265            "schedule type does not support user-defined chunk sizes");
2266     LLVM_FALLTHROUGH;
2267   case OMPScheduleType::BaseDynamicChunked:
2268   case OMPScheduleType::BaseGuidedChunked:
2269   case OMPScheduleType::BaseGuidedIterativeChunked:
2270   case OMPScheduleType::BaseGuidedAnalyticalChunked:
2271   case OMPScheduleType::BaseStaticBalancedChunked:
2272     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, EffectiveScheduleType,
2273                                      NeedsBarrier, ChunkSize);
2274 
2275   default:
2276     llvm_unreachable("Unknown/unimplemented schedule kind");
2277   }
2278 }
2279 
2280 /// Returns an LLVM function to call for initializing loop bounds using OpenMP
2281 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2282 /// the runtime. Always interpret integers as unsigned similarly to
2283 /// CanonicalLoopInfo.
2284 static FunctionCallee
2285 getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2286   unsigned Bitwidth = Ty->getIntegerBitWidth();
2287   if (Bitwidth == 32)
2288     return OMPBuilder.getOrCreateRuntimeFunction(
2289         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
2290   if (Bitwidth == 64)
2291     return OMPBuilder.getOrCreateRuntimeFunction(
2292         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
2293   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2294 }
2295 
2296 /// Returns an LLVM function to call for updating the next loop using OpenMP
2297 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
2298 /// the runtime. Always interpret integers as unsigned similarly to
2299 /// CanonicalLoopInfo.
2300 static FunctionCallee
2301 getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2302   unsigned Bitwidth = Ty->getIntegerBitWidth();
2303   if (Bitwidth == 32)
2304     return OMPBuilder.getOrCreateRuntimeFunction(
2305         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
2306   if (Bitwidth == 64)
2307     return OMPBuilder.getOrCreateRuntimeFunction(
2308         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
2309   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2310 }
2311 
2312 /// Returns an LLVM function to call for finalizing the dynamic loop using
2313 /// depending on `type`. Only i32 and i64 are supported by the runtime. Always
2314 /// interpret integers as unsigned similarly to CanonicalLoopInfo.
2315 static FunctionCallee
2316 getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
2317   unsigned Bitwidth = Ty->getIntegerBitWidth();
2318   if (Bitwidth == 32)
2319     return OMPBuilder.getOrCreateRuntimeFunction(
2320         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
2321   if (Bitwidth == 64)
2322     return OMPBuilder.getOrCreateRuntimeFunction(
2323         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
2324   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
2325 }
2326 
2327 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
2328     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
2329     OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {
2330   assert(CLI->isValid() && "Requires a valid canonical loop");
2331   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
2332          "Require dedicated allocate IP");
2333   assert(isValidWorkshareLoopScheduleType(SchedType) &&
2334          "Require valid schedule type");
2335 
2336   bool Ordered = (SchedType & OMPScheduleType::ModifierOrdered) ==
2337                  OMPScheduleType::ModifierOrdered;
2338 
2339   // Set up the source location value for OpenMP runtime.
2340   Builder.SetCurrentDebugLocation(DL);
2341 
2342   uint32_t SrcLocStrSize;
2343   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
2344   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2345 
2346   // Declare useful OpenMP runtime functions.
2347   Value *IV = CLI->getIndVar();
2348   Type *IVTy = IV->getType();
2349   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
2350   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
2351 
2352   // Allocate space for computed loop bounds as expected by the "init" function.
2353   Builder.restoreIP(AllocaIP);
2354   Type *I32Type = Type::getInt32Ty(M.getContext());
2355   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
2356   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
2357   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
2358   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
2359 
2360   // At the end of the preheader, prepare for calling the "init" function by
2361   // storing the current loop bounds into the allocated space. A canonical loop
2362   // always iterates from 0 to trip-count with step 1. Note that "init" expects
2363   // and produces an inclusive upper bound.
2364   BasicBlock *PreHeader = CLI->getPreheader();
2365   Builder.SetInsertPoint(PreHeader->getTerminator());
2366   Constant *One = ConstantInt::get(IVTy, 1);
2367   Builder.CreateStore(One, PLowerBound);
2368   Value *UpperBound = CLI->getTripCount();
2369   Builder.CreateStore(UpperBound, PUpperBound);
2370   Builder.CreateStore(One, PStride);
2371 
2372   BasicBlock *Header = CLI->getHeader();
2373   BasicBlock *Exit = CLI->getExit();
2374   BasicBlock *Cond = CLI->getCond();
2375   BasicBlock *Latch = CLI->getLatch();
2376   InsertPointTy AfterIP = CLI->getAfterIP();
2377 
2378   // The CLI will be "broken" in the code below, as the loop is no longer
2379   // a valid canonical loop.
2380 
2381   if (!Chunk)
2382     Chunk = One;
2383 
2384   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
2385 
2386   Constant *SchedulingType =
2387       ConstantInt::get(I32Type, static_cast<int>(SchedType));
2388 
2389   // Call the "init" function.
2390   Builder.CreateCall(DynamicInit,
2391                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
2392                       UpperBound, /* step */ One, Chunk});
2393 
2394   // An outer loop around the existing one.
2395   BasicBlock *OuterCond = BasicBlock::Create(
2396       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
2397       PreHeader->getParent());
2398   // This needs to be 32-bit always, so can't use the IVTy Zero above.
2399   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
2400   Value *Res =
2401       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
2402                                        PLowerBound, PUpperBound, PStride});
2403   Constant *Zero32 = ConstantInt::get(I32Type, 0);
2404   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
2405   Value *LowerBound =
2406       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
2407   Builder.CreateCondBr(MoreWork, Header, Exit);
2408 
2409   // Change PHI-node in loop header to use outer cond rather than preheader,
2410   // and set IV to the LowerBound.
2411   Instruction *Phi = &Header->front();
2412   auto *PI = cast<PHINode>(Phi);
2413   PI->setIncomingBlock(0, OuterCond);
2414   PI->setIncomingValue(0, LowerBound);
2415 
2416   // Then set the pre-header to jump to the OuterCond
2417   Instruction *Term = PreHeader->getTerminator();
2418   auto *Br = cast<BranchInst>(Term);
2419   Br->setSuccessor(0, OuterCond);
2420 
2421   // Modify the inner condition:
2422   // * Use the UpperBound returned from the DynamicNext call.
2423   // * jump to the loop outer loop when done with one of the inner loops.
2424   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
2425   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
2426   Instruction *Comp = &*Builder.GetInsertPoint();
2427   auto *CI = cast<CmpInst>(Comp);
2428   CI->setOperand(1, UpperBound);
2429   // Redirect the inner exit to branch to outer condition.
2430   Instruction *Branch = &Cond->back();
2431   auto *BI = cast<BranchInst>(Branch);
2432   assert(BI->getSuccessor(1) == Exit);
2433   BI->setSuccessor(1, OuterCond);
2434 
2435   // Call the "fini" function if "ordered" is present in wsloop directive.
2436   if (Ordered) {
2437     Builder.SetInsertPoint(&Latch->back());
2438     FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
2439     Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});
2440   }
2441 
2442   // Add the barrier if requested.
2443   if (NeedsBarrier) {
2444     Builder.SetInsertPoint(&Exit->back());
2445     createBarrier(LocationDescription(Builder.saveIP(), DL),
2446                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2447                   /* CheckCancelFlag */ false);
2448   }
2449 
2450   CLI->invalidate();
2451   return AfterIP;
2452 }
2453 
2454 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2455 /// after this \p OldTarget will be orphaned.
2456 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
2457                                       BasicBlock *NewTarget, DebugLoc DL) {
2458   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2459     redirectTo(Pred, NewTarget, DL);
2460 }
2461 
2462 /// Determine which blocks in \p BBs are reachable from outside and remove the
2463 /// ones that are not reachable from the function.
2464 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
2465   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2466   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2467     for (Use &U : BB->uses()) {
2468       auto *UseInst = dyn_cast<Instruction>(U.getUser());
2469       if (!UseInst)
2470         continue;
2471       if (BBsToErase.count(UseInst->getParent()))
2472         continue;
2473       return true;
2474     }
2475     return false;
2476   };
2477 
2478   while (true) {
2479     bool Changed = false;
2480     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2481       if (HasRemainingUses(BB)) {
2482         BBsToErase.erase(BB);
2483         Changed = true;
2484       }
2485     }
2486     if (!Changed)
2487       break;
2488   }
2489 
2490   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2491   DeleteDeadBlocks(BBVec);
2492 }
2493 
2494 CanonicalLoopInfo *
2495 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2496                                InsertPointTy ComputeIP) {
2497   assert(Loops.size() >= 1 && "At least one loop required");
2498   size_t NumLoops = Loops.size();
2499 
2500   // Nothing to do if there is already just one loop.
2501   if (NumLoops == 1)
2502     return Loops.front();
2503 
2504   CanonicalLoopInfo *Outermost = Loops.front();
2505   CanonicalLoopInfo *Innermost = Loops.back();
2506   BasicBlock *OrigPreheader = Outermost->getPreheader();
2507   BasicBlock *OrigAfter = Outermost->getAfter();
2508   Function *F = OrigPreheader->getParent();
2509 
2510   // Loop control blocks that may become orphaned later.
2511   SmallVector<BasicBlock *, 12> OldControlBBs;
2512   OldControlBBs.reserve(6 * Loops.size());
2513   for (CanonicalLoopInfo *Loop : Loops)
2514     Loop->collectControlBlocks(OldControlBBs);
2515 
2516   // Setup the IRBuilder for inserting the trip count computation.
2517   Builder.SetCurrentDebugLocation(DL);
2518   if (ComputeIP.isSet())
2519     Builder.restoreIP(ComputeIP);
2520   else
2521     Builder.restoreIP(Outermost->getPreheaderIP());
2522 
2523   // Derive the collapsed' loop trip count.
2524   // TODO: Find common/largest indvar type.
2525   Value *CollapsedTripCount = nullptr;
2526   for (CanonicalLoopInfo *L : Loops) {
2527     assert(L->isValid() &&
2528            "All loops to collapse must be valid canonical loops");
2529     Value *OrigTripCount = L->getTripCount();
2530     if (!CollapsedTripCount) {
2531       CollapsedTripCount = OrigTripCount;
2532       continue;
2533     }
2534 
2535     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2536     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2537                                            {}, /*HasNUW=*/true);
2538   }
2539 
2540   // Create the collapsed loop control flow.
2541   CanonicalLoopInfo *Result =
2542       createLoopSkeleton(DL, CollapsedTripCount, F,
2543                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2544 
2545   // Build the collapsed loop body code.
2546   // Start with deriving the input loop induction variables from the collapsed
2547   // one, using a divmod scheme. To preserve the original loops' order, the
2548   // innermost loop use the least significant bits.
2549   Builder.restoreIP(Result->getBodyIP());
2550 
2551   Value *Leftover = Result->getIndVar();
2552   SmallVector<Value *> NewIndVars;
2553   NewIndVars.resize(NumLoops);
2554   for (int i = NumLoops - 1; i >= 1; --i) {
2555     Value *OrigTripCount = Loops[i]->getTripCount();
2556 
2557     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2558     NewIndVars[i] = NewIndVar;
2559 
2560     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2561   }
2562   // Outermost loop gets all the remaining bits.
2563   NewIndVars[0] = Leftover;
2564 
2565   // Construct the loop body control flow.
2566   // We progressively construct the branch structure following in direction of
2567   // the control flow, from the leading in-between code, the loop nest body, the
2568   // trailing in-between code, and rejoining the collapsed loop's latch.
2569   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2570   // the ContinueBlock is set, continue with that block. If ContinuePred, use
2571   // its predecessors as sources.
2572   BasicBlock *ContinueBlock = Result->getBody();
2573   BasicBlock *ContinuePred = nullptr;
2574   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2575                                                           BasicBlock *NextSrc) {
2576     if (ContinueBlock)
2577       redirectTo(ContinueBlock, Dest, DL);
2578     else
2579       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2580 
2581     ContinueBlock = nullptr;
2582     ContinuePred = NextSrc;
2583   };
2584 
2585   // The code before the nested loop of each level.
2586   // Because we are sinking it into the nest, it will be executed more often
2587   // that the original loop. More sophisticated schemes could keep track of what
2588   // the in-between code is and instantiate it only once per thread.
2589   for (size_t i = 0; i < NumLoops - 1; ++i)
2590     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2591 
2592   // Connect the loop nest body.
2593   ContinueWith(Innermost->getBody(), Innermost->getLatch());
2594 
2595   // The code after the nested loop at each level.
2596   for (size_t i = NumLoops - 1; i > 0; --i)
2597     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2598 
2599   // Connect the finished loop to the collapsed loop latch.
2600   ContinueWith(Result->getLatch(), nullptr);
2601 
2602   // Replace the input loops with the new collapsed loop.
2603   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2604   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2605 
2606   // Replace the input loop indvars with the derived ones.
2607   for (size_t i = 0; i < NumLoops; ++i)
2608     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2609 
2610   // Remove unused parts of the input loops.
2611   removeUnusedBlocksFromParent(OldControlBBs);
2612 
2613   for (CanonicalLoopInfo *L : Loops)
2614     L->invalidate();
2615 
2616 #ifndef NDEBUG
2617   Result->assertOK();
2618 #endif
2619   return Result;
2620 }
2621 
2622 std::vector<CanonicalLoopInfo *>
2623 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2624                            ArrayRef<Value *> TileSizes) {
2625   assert(TileSizes.size() == Loops.size() &&
2626          "Must pass as many tile sizes as there are loops");
2627   int NumLoops = Loops.size();
2628   assert(NumLoops >= 1 && "At least one loop to tile required");
2629 
2630   CanonicalLoopInfo *OutermostLoop = Loops.front();
2631   CanonicalLoopInfo *InnermostLoop = Loops.back();
2632   Function *F = OutermostLoop->getBody()->getParent();
2633   BasicBlock *InnerEnter = InnermostLoop->getBody();
2634   BasicBlock *InnerLatch = InnermostLoop->getLatch();
2635 
2636   // Loop control blocks that may become orphaned later.
2637   SmallVector<BasicBlock *, 12> OldControlBBs;
2638   OldControlBBs.reserve(6 * Loops.size());
2639   for (CanonicalLoopInfo *Loop : Loops)
2640     Loop->collectControlBlocks(OldControlBBs);
2641 
2642   // Collect original trip counts and induction variable to be accessible by
2643   // index. Also, the structure of the original loops is not preserved during
2644   // the construction of the tiled loops, so do it before we scavenge the BBs of
2645   // any original CanonicalLoopInfo.
2646   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2647   for (CanonicalLoopInfo *L : Loops) {
2648     assert(L->isValid() && "All input loops must be valid canonical loops");
2649     OrigTripCounts.push_back(L->getTripCount());
2650     OrigIndVars.push_back(L->getIndVar());
2651   }
2652 
2653   // Collect the code between loop headers. These may contain SSA definitions
2654   // that are used in the loop nest body. To be usable with in the innermost
2655   // body, these BasicBlocks will be sunk into the loop nest body. That is,
2656   // these instructions may be executed more often than before the tiling.
2657   // TODO: It would be sufficient to only sink them into body of the
2658   // corresponding tile loop.
2659   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
2660   for (int i = 0; i < NumLoops - 1; ++i) {
2661     CanonicalLoopInfo *Surrounding = Loops[i];
2662     CanonicalLoopInfo *Nested = Loops[i + 1];
2663 
2664     BasicBlock *EnterBB = Surrounding->getBody();
2665     BasicBlock *ExitBB = Nested->getHeader();
2666     InbetweenCode.emplace_back(EnterBB, ExitBB);
2667   }
2668 
2669   // Compute the trip counts of the floor loops.
2670   Builder.SetCurrentDebugLocation(DL);
2671   Builder.restoreIP(OutermostLoop->getPreheaderIP());
2672   SmallVector<Value *, 4> FloorCount, FloorRems;
2673   for (int i = 0; i < NumLoops; ++i) {
2674     Value *TileSize = TileSizes[i];
2675     Value *OrigTripCount = OrigTripCounts[i];
2676     Type *IVType = OrigTripCount->getType();
2677 
2678     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
2679     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
2680 
2681     // 0 if tripcount divides the tilesize, 1 otherwise.
2682     // 1 means we need an additional iteration for a partial tile.
2683     //
2684     // Unfortunately we cannot just use the roundup-formula
2685     //   (tripcount + tilesize - 1)/tilesize
2686     // because the summation might overflow. We do not want introduce undefined
2687     // behavior when the untiled loop nest did not.
2688     Value *FloorTripOverflow =
2689         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
2690 
2691     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
2692     FloorTripCount =
2693         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
2694                           "omp_floor" + Twine(i) + ".tripcount", true);
2695 
2696     // Remember some values for later use.
2697     FloorCount.push_back(FloorTripCount);
2698     FloorRems.push_back(FloorTripRem);
2699   }
2700 
2701   // Generate the new loop nest, from the outermost to the innermost.
2702   std::vector<CanonicalLoopInfo *> Result;
2703   Result.reserve(NumLoops * 2);
2704 
2705   // The basic block of the surrounding loop that enters the nest generated
2706   // loop.
2707   BasicBlock *Enter = OutermostLoop->getPreheader();
2708 
2709   // The basic block of the surrounding loop where the inner code should
2710   // continue.
2711   BasicBlock *Continue = OutermostLoop->getAfter();
2712 
2713   // Where the next loop basic block should be inserted.
2714   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
2715 
2716   auto EmbeddNewLoop =
2717       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
2718           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
2719     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
2720         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
2721     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
2722     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
2723 
2724     // Setup the position where the next embedded loop connects to this loop.
2725     Enter = EmbeddedLoop->getBody();
2726     Continue = EmbeddedLoop->getLatch();
2727     OutroInsertBefore = EmbeddedLoop->getLatch();
2728     return EmbeddedLoop;
2729   };
2730 
2731   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
2732                                                   const Twine &NameBase) {
2733     for (auto P : enumerate(TripCounts)) {
2734       CanonicalLoopInfo *EmbeddedLoop =
2735           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
2736       Result.push_back(EmbeddedLoop);
2737     }
2738   };
2739 
2740   EmbeddNewLoops(FloorCount, "floor");
2741 
2742   // Within the innermost floor loop, emit the code that computes the tile
2743   // sizes.
2744   Builder.SetInsertPoint(Enter->getTerminator());
2745   SmallVector<Value *, 4> TileCounts;
2746   for (int i = 0; i < NumLoops; ++i) {
2747     CanonicalLoopInfo *FloorLoop = Result[i];
2748     Value *TileSize = TileSizes[i];
2749 
2750     Value *FloorIsEpilogue =
2751         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
2752     Value *TileTripCount =
2753         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
2754 
2755     TileCounts.push_back(TileTripCount);
2756   }
2757 
2758   // Create the tile loops.
2759   EmbeddNewLoops(TileCounts, "tile");
2760 
2761   // Insert the inbetween code into the body.
2762   BasicBlock *BodyEnter = Enter;
2763   BasicBlock *BodyEntered = nullptr;
2764   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
2765     BasicBlock *EnterBB = P.first;
2766     BasicBlock *ExitBB = P.second;
2767 
2768     if (BodyEnter)
2769       redirectTo(BodyEnter, EnterBB, DL);
2770     else
2771       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
2772 
2773     BodyEnter = nullptr;
2774     BodyEntered = ExitBB;
2775   }
2776 
2777   // Append the original loop nest body into the generated loop nest body.
2778   if (BodyEnter)
2779     redirectTo(BodyEnter, InnerEnter, DL);
2780   else
2781     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
2782   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
2783 
2784   // Replace the original induction variable with an induction variable computed
2785   // from the tile and floor induction variables.
2786   Builder.restoreIP(Result.back()->getBodyIP());
2787   for (int i = 0; i < NumLoops; ++i) {
2788     CanonicalLoopInfo *FloorLoop = Result[i];
2789     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
2790     Value *OrigIndVar = OrigIndVars[i];
2791     Value *Size = TileSizes[i];
2792 
2793     Value *Scale =
2794         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
2795     Value *Shift =
2796         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
2797     OrigIndVar->replaceAllUsesWith(Shift);
2798   }
2799 
2800   // Remove unused parts of the original loops.
2801   removeUnusedBlocksFromParent(OldControlBBs);
2802 
2803   for (CanonicalLoopInfo *L : Loops)
2804     L->invalidate();
2805 
2806 #ifndef NDEBUG
2807   for (CanonicalLoopInfo *GenL : Result)
2808     GenL->assertOK();
2809 #endif
2810   return Result;
2811 }
2812 
2813 /// Attach loop metadata \p Properties to the loop described by \p Loop. If the
2814 /// loop already has metadata, the loop properties are appended.
2815 static void addLoopMetadata(CanonicalLoopInfo *Loop,
2816                             ArrayRef<Metadata *> Properties) {
2817   assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
2818 
2819   // Nothing to do if no property to attach.
2820   if (Properties.empty())
2821     return;
2822 
2823   LLVMContext &Ctx = Loop->getFunction()->getContext();
2824   SmallVector<Metadata *> NewLoopProperties;
2825   NewLoopProperties.push_back(nullptr);
2826 
2827   // If the loop already has metadata, prepend it to the new metadata.
2828   BasicBlock *Latch = Loop->getLatch();
2829   assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
2830   MDNode *Existing = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
2831   if (Existing)
2832     append_range(NewLoopProperties, drop_begin(Existing->operands(), 1));
2833 
2834   append_range(NewLoopProperties, Properties);
2835   MDNode *LoopID = MDNode::getDistinct(Ctx, NewLoopProperties);
2836   LoopID->replaceOperandWith(0, LoopID);
2837 
2838   Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
2839 }
2840 
2841 /// Attach llvm.access.group metadata to the memref instructions of \p Block
2842 static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
2843                             LoopInfo &LI) {
2844   for (Instruction &I : *Block) {
2845     if (I.mayReadOrWriteMemory()) {
2846       // TODO: This instruction may already have access group from
2847       // other pragmas e.g. #pragma clang loop vectorize.  Append
2848       // so that the existing metadata is not overwritten.
2849       I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
2850     }
2851   }
2852 }
2853 
2854 void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {
2855   LLVMContext &Ctx = Builder.getContext();
2856   addLoopMetadata(
2857       Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2858              MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
2859 }
2860 
2861 void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {
2862   LLVMContext &Ctx = Builder.getContext();
2863   addLoopMetadata(
2864       Loop, {
2865                 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2866             });
2867 }
2868 
2869 void OpenMPIRBuilder::applySimd(CanonicalLoopInfo *CanonicalLoop,
2870                                 ConstantInt *Simdlen) {
2871   LLVMContext &Ctx = Builder.getContext();
2872 
2873   Function *F = CanonicalLoop->getFunction();
2874 
2875   FunctionAnalysisManager FAM;
2876   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2877   FAM.registerPass([]() { return LoopAnalysis(); });
2878   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2879 
2880   LoopAnalysis LIA;
2881   LoopInfo &&LI = LIA.run(*F, FAM);
2882 
2883   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
2884 
2885   SmallSet<BasicBlock *, 8> Reachable;
2886 
2887   // Get the basic blocks from the loop in which memref instructions
2888   // can be found.
2889   // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
2890   // preferably without running any passes.
2891   for (BasicBlock *Block : L->getBlocks()) {
2892     if (Block == CanonicalLoop->getCond() ||
2893         Block == CanonicalLoop->getHeader())
2894       continue;
2895     Reachable.insert(Block);
2896   }
2897 
2898   // Add access group metadata to memory-access instructions.
2899   MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
2900   for (BasicBlock *BB : Reachable)
2901     addSimdMetadata(BB, AccessGroup, LI);
2902 
2903   // Use the above access group metadata to create loop level
2904   // metadata, which should be distinct for each loop.
2905   ConstantAsMetadata *BoolConst =
2906       ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));
2907   // TODO:  If the loop has existing parallel access metadata, have
2908   // to combine two lists.
2909   addLoopMetadata(
2910       CanonicalLoop,
2911       {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"),
2912                          AccessGroup}),
2913        MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
2914                          BoolConst})});
2915   if (Simdlen != nullptr)
2916     addLoopMetadata(
2917         CanonicalLoop,
2918         MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.width"),
2919                           ConstantAsMetadata::get(Simdlen)}));
2920 }
2921 
2922 /// Create the TargetMachine object to query the backend for optimization
2923 /// preferences.
2924 ///
2925 /// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
2926 /// e.g. Clang does not pass it to its CodeGen layer and creates it only when
2927 /// needed for the LLVM pass pipline. We use some default options to avoid
2928 /// having to pass too many settings from the frontend that probably do not
2929 /// matter.
2930 ///
2931 /// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
2932 /// method. If we are going to use TargetMachine for more purposes, especially
2933 /// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
2934 /// might become be worth requiring front-ends to pass on their TargetMachine,
2935 /// or at least cache it between methods. Note that while fontends such as Clang
2936 /// have just a single main TargetMachine per translation unit, "target-cpu" and
2937 /// "target-features" that determine the TargetMachine are per-function and can
2938 /// be overrided using __attribute__((target("OPTIONS"))).
2939 static std::unique_ptr<TargetMachine>
2940 createTargetMachine(Function *F, CodeGenOpt::Level OptLevel) {
2941   Module *M = F->getParent();
2942 
2943   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
2944   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
2945   const std::string &Triple = M->getTargetTriple();
2946 
2947   std::string Error;
2948   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
2949   if (!TheTarget)
2950     return {};
2951 
2952   llvm::TargetOptions Options;
2953   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
2954       Triple, CPU, Features, Options, /*RelocModel=*/None, /*CodeModel=*/None,
2955       OptLevel));
2956 }
2957 
2958 /// Heuristically determine the best-performant unroll factor for \p CLI. This
2959 /// depends on the target processor. We are re-using the same heuristics as the
2960 /// LoopUnrollPass.
2961 static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {
2962   Function *F = CLI->getFunction();
2963 
2964   // Assume the user requests the most aggressive unrolling, even if the rest of
2965   // the code is optimized using a lower setting.
2966   CodeGenOpt::Level OptLevel = CodeGenOpt::Aggressive;
2967   std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
2968 
2969   FunctionAnalysisManager FAM;
2970   FAM.registerPass([]() { return TargetLibraryAnalysis(); });
2971   FAM.registerPass([]() { return AssumptionAnalysis(); });
2972   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2973   FAM.registerPass([]() { return LoopAnalysis(); });
2974   FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
2975   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2976   TargetIRAnalysis TIRA;
2977   if (TM)
2978     TIRA = TargetIRAnalysis(
2979         [&](const Function &F) { return TM->getTargetTransformInfo(F); });
2980   FAM.registerPass([&]() { return TIRA; });
2981 
2982   TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
2983   ScalarEvolutionAnalysis SEA;
2984   ScalarEvolution &&SE = SEA.run(*F, FAM);
2985   DominatorTreeAnalysis DTA;
2986   DominatorTree &&DT = DTA.run(*F, FAM);
2987   LoopAnalysis LIA;
2988   LoopInfo &&LI = LIA.run(*F, FAM);
2989   AssumptionAnalysis ACT;
2990   AssumptionCache &&AC = ACT.run(*F, FAM);
2991   OptimizationRemarkEmitter ORE{F};
2992 
2993   Loop *L = LI.getLoopFor(CLI->getHeader());
2994   assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
2995 
2996   TargetTransformInfo::UnrollingPreferences UP =
2997       gatherUnrollingPreferences(L, SE, TTI,
2998                                  /*BlockFrequencyInfo=*/nullptr,
2999                                  /*ProfileSummaryInfo=*/nullptr, ORE, OptLevel,
3000                                  /*UserThreshold=*/None,
3001                                  /*UserCount=*/None,
3002                                  /*UserAllowPartial=*/true,
3003                                  /*UserAllowRuntime=*/true,
3004                                  /*UserUpperBound=*/None,
3005                                  /*UserFullUnrollMaxCount=*/None);
3006 
3007   UP.Force = true;
3008 
3009   // Account for additional optimizations taking place before the LoopUnrollPass
3010   // would unroll the loop.
3011   UP.Threshold *= UnrollThresholdFactor;
3012   UP.PartialThreshold *= UnrollThresholdFactor;
3013 
3014   // Use normal unroll factors even if the rest of the code is optimized for
3015   // size.
3016   UP.OptSizeThreshold = UP.Threshold;
3017   UP.PartialOptSizeThreshold = UP.PartialThreshold;
3018 
3019   LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
3020                     << "  Threshold=" << UP.Threshold << "\n"
3021                     << "  PartialThreshold=" << UP.PartialThreshold << "\n"
3022                     << "  OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
3023                     << "  PartialOptSizeThreshold="
3024                     << UP.PartialOptSizeThreshold << "\n");
3025 
3026   // Disable peeling.
3027   TargetTransformInfo::PeelingPreferences PP =
3028       gatherPeelingPreferences(L, SE, TTI,
3029                                /*UserAllowPeeling=*/false,
3030                                /*UserAllowProfileBasedPeeling=*/false,
3031                                /*UnrollingSpecficValues=*/false);
3032 
3033   SmallPtrSet<const Value *, 32> EphValues;
3034   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
3035 
3036   // Assume that reads and writes to stack variables can be eliminated by
3037   // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
3038   // size.
3039   for (BasicBlock *BB : L->blocks()) {
3040     for (Instruction &I : *BB) {
3041       Value *Ptr;
3042       if (auto *Load = dyn_cast<LoadInst>(&I)) {
3043         Ptr = Load->getPointerOperand();
3044       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
3045         Ptr = Store->getPointerOperand();
3046       } else
3047         continue;
3048 
3049       Ptr = Ptr->stripPointerCasts();
3050 
3051       if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
3052         if (Alloca->getParent() == &F->getEntryBlock())
3053           EphValues.insert(&I);
3054       }
3055     }
3056   }
3057 
3058   unsigned NumInlineCandidates;
3059   bool NotDuplicatable;
3060   bool Convergent;
3061   InstructionCost LoopSizeIC =
3062       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
3063                           TTI, EphValues, UP.BEInsns);
3064   LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSizeIC << "\n");
3065 
3066   // Loop is not unrollable if the loop contains certain instructions.
3067   if (NotDuplicatable || Convergent || !LoopSizeIC.isValid()) {
3068     LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
3069     return 1;
3070   }
3071   unsigned LoopSize = *LoopSizeIC.getValue();
3072 
3073   // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
3074   // be able to use it.
3075   int TripCount = 0;
3076   int MaxTripCount = 0;
3077   bool MaxOrZero = false;
3078   unsigned TripMultiple = 0;
3079 
3080   bool UseUpperBound = false;
3081   computeUnrollCount(L, TTI, DT, &LI, SE, EphValues, &ORE, TripCount,
3082                      MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
3083                      UseUpperBound);
3084   unsigned Factor = UP.Count;
3085   LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
3086 
3087   // This function returns 1 to signal to not unroll a loop.
3088   if (Factor == 0)
3089     return 1;
3090   return Factor;
3091 }
3092 
3093 void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
3094                                         int32_t Factor,
3095                                         CanonicalLoopInfo **UnrolledCLI) {
3096   assert(Factor >= 0 && "Unroll factor must not be negative");
3097 
3098   Function *F = Loop->getFunction();
3099   LLVMContext &Ctx = F->getContext();
3100 
3101   // If the unrolled loop is not used for another loop-associated directive, it
3102   // is sufficient to add metadata for the LoopUnrollPass.
3103   if (!UnrolledCLI) {
3104     SmallVector<Metadata *, 2> LoopMetadata;
3105     LoopMetadata.push_back(
3106         MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
3107 
3108     if (Factor >= 1) {
3109       ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3110           ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3111       LoopMetadata.push_back(MDNode::get(
3112           Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
3113     }
3114 
3115     addLoopMetadata(Loop, LoopMetadata);
3116     return;
3117   }
3118 
3119   // Heuristically determine the unroll factor.
3120   if (Factor == 0)
3121     Factor = computeHeuristicUnrollFactor(Loop);
3122 
3123   // No change required with unroll factor 1.
3124   if (Factor == 1) {
3125     *UnrolledCLI = Loop;
3126     return;
3127   }
3128 
3129   assert(Factor >= 2 &&
3130          "unrolling only makes sense with a factor of 2 or larger");
3131 
3132   Type *IndVarTy = Loop->getIndVarType();
3133 
3134   // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
3135   // unroll the inner loop.
3136   Value *FactorVal =
3137       ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
3138                                        /*isSigned=*/false));
3139   std::vector<CanonicalLoopInfo *> LoopNest =
3140       tileLoops(DL, {Loop}, {FactorVal});
3141   assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
3142   *UnrolledCLI = LoopNest[0];
3143   CanonicalLoopInfo *InnerLoop = LoopNest[1];
3144 
3145   // LoopUnrollPass can only fully unroll loops with constant trip count.
3146   // Unroll by the unroll factor with a fallback epilog for the remainder
3147   // iterations if necessary.
3148   ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
3149       ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
3150   addLoopMetadata(
3151       InnerLoop,
3152       {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
3153        MDNode::get(
3154            Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
3155 
3156 #ifndef NDEBUG
3157   (*UnrolledCLI)->assertOK();
3158 #endif
3159 }
3160 
3161 OpenMPIRBuilder::InsertPointTy
3162 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
3163                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
3164                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
3165   if (!updateToLocation(Loc))
3166     return Loc.IP;
3167 
3168   uint32_t SrcLocStrSize;
3169   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3170   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3171   Value *ThreadId = getOrCreateThreadID(Ident);
3172 
3173   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
3174 
3175   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
3176 
3177   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
3178   Builder.CreateCall(Fn, Args);
3179 
3180   return Builder.saveIP();
3181 }
3182 
3183 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(
3184     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3185     FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
3186 
3187   if (!updateToLocation(Loc))
3188     return Loc.IP;
3189 
3190   // If needed (i.e. not null), initialize `DidIt` with 0
3191   if (DidIt) {
3192     Builder.CreateStore(Builder.getInt32(0), DidIt);
3193   }
3194 
3195   Directive OMPD = Directive::OMPD_single;
3196   uint32_t SrcLocStrSize;
3197   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3198   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3199   Value *ThreadId = getOrCreateThreadID(Ident);
3200   Value *Args[] = {Ident, ThreadId};
3201 
3202   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
3203   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3204 
3205   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
3206   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3207 
3208   // generates the following:
3209   // if (__kmpc_single()) {
3210   //		.... single region ...
3211   // 		__kmpc_end_single
3212   // }
3213   // __kmpc_barrier
3214 
3215   EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3216                        /*Conditional*/ true,
3217                        /*hasFinalize*/ true);
3218   if (!IsNowait)
3219     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
3220                   omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
3221                   /* CheckCancelFlag */ false);
3222   return Builder.saveIP();
3223 }
3224 
3225 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
3226     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3227     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
3228 
3229   if (!updateToLocation(Loc))
3230     return Loc.IP;
3231 
3232   Directive OMPD = Directive::OMPD_critical;
3233   uint32_t SrcLocStrSize;
3234   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3235   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3236   Value *ThreadId = getOrCreateThreadID(Ident);
3237   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
3238   Value *Args[] = {Ident, ThreadId, LockVar};
3239 
3240   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
3241   Function *RTFn = nullptr;
3242   if (HintInst) {
3243     // Add Hint to entry Args and create call
3244     EnterArgs.push_back(HintInst);
3245     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
3246   } else {
3247     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
3248   }
3249   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
3250 
3251   Function *ExitRTLFn =
3252       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
3253   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3254 
3255   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3256                               /*Conditional*/ false, /*hasFinalize*/ true);
3257 }
3258 
3259 OpenMPIRBuilder::InsertPointTy
3260 OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,
3261                                      InsertPointTy AllocaIP, unsigned NumLoops,
3262                                      ArrayRef<llvm::Value *> StoreValues,
3263                                      const Twine &Name, bool IsDependSource) {
3264   for (size_t I = 0; I < StoreValues.size(); I++)
3265     assert(StoreValues[I]->getType()->isIntegerTy(64) &&
3266            "OpenMP runtime requires depend vec with i64 type");
3267 
3268   if (!updateToLocation(Loc))
3269     return Loc.IP;
3270 
3271   // Allocate space for vector and generate alloc instruction.
3272   auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
3273   Builder.restoreIP(AllocaIP);
3274   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
3275   ArgsBase->setAlignment(Align(8));
3276   Builder.restoreIP(Loc.IP);
3277 
3278   // Store the index value with offset in depend vector.
3279   for (unsigned I = 0; I < NumLoops; ++I) {
3280     Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
3281         ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
3282     StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
3283     STInst->setAlignment(Align(8));
3284   }
3285 
3286   Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
3287       ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
3288 
3289   uint32_t SrcLocStrSize;
3290   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3291   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3292   Value *ThreadId = getOrCreateThreadID(Ident);
3293   Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
3294 
3295   Function *RTLFn = nullptr;
3296   if (IsDependSource)
3297     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
3298   else
3299     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
3300   Builder.CreateCall(RTLFn, Args);
3301 
3302   return Builder.saveIP();
3303 }
3304 
3305 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(
3306     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
3307     FinalizeCallbackTy FiniCB, bool IsThreads) {
3308   if (!updateToLocation(Loc))
3309     return Loc.IP;
3310 
3311   Directive OMPD = Directive::OMPD_ordered;
3312   Instruction *EntryCall = nullptr;
3313   Instruction *ExitCall = nullptr;
3314 
3315   if (IsThreads) {
3316     uint32_t SrcLocStrSize;
3317     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3318     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3319     Value *ThreadId = getOrCreateThreadID(Ident);
3320     Value *Args[] = {Ident, ThreadId};
3321 
3322     Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
3323     EntryCall = Builder.CreateCall(EntryRTLFn, Args);
3324 
3325     Function *ExitRTLFn =
3326         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
3327     ExitCall = Builder.CreateCall(ExitRTLFn, Args);
3328   }
3329 
3330   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
3331                               /*Conditional*/ false, /*hasFinalize*/ true);
3332 }
3333 
3334 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
3335     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
3336     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
3337     bool HasFinalize, bool IsCancellable) {
3338 
3339   if (HasFinalize)
3340     FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
3341 
3342   // Create inlined region's entry and body blocks, in preparation
3343   // for conditional creation
3344   BasicBlock *EntryBB = Builder.GetInsertBlock();
3345   Instruction *SplitPos = EntryBB->getTerminator();
3346   if (!isa_and_nonnull<BranchInst>(SplitPos))
3347     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
3348   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
3349   BasicBlock *FiniBB =
3350       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
3351 
3352   Builder.SetInsertPoint(EntryBB->getTerminator());
3353   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
3354 
3355   // generate body
3356   BodyGenCB(/* AllocaIP */ InsertPointTy(),
3357             /* CodeGenIP */ Builder.saveIP());
3358 
3359   // emit exit call and do any needed finalization.
3360   auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
3361   assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
3362          FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
3363          "Unexpected control flow graph state!!");
3364   emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
3365   assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
3366          "Unexpected Control Flow State!");
3367   MergeBlockIntoPredecessor(FiniBB);
3368 
3369   // If we are skipping the region of a non conditional, remove the exit
3370   // block, and clear the builder's insertion point.
3371   assert(SplitPos->getParent() == ExitBB &&
3372          "Unexpected Insertion point location!");
3373   auto merged = MergeBlockIntoPredecessor(ExitBB);
3374   BasicBlock *ExitPredBB = SplitPos->getParent();
3375   auto InsertBB = merged ? ExitPredBB : ExitBB;
3376   if (!isa_and_nonnull<BranchInst>(SplitPos))
3377     SplitPos->eraseFromParent();
3378   Builder.SetInsertPoint(InsertBB);
3379 
3380   return Builder.saveIP();
3381 }
3382 
3383 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
3384     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
3385   // if nothing to do, Return current insertion point.
3386   if (!Conditional || !EntryCall)
3387     return Builder.saveIP();
3388 
3389   BasicBlock *EntryBB = Builder.GetInsertBlock();
3390   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
3391   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
3392   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
3393 
3394   // Emit thenBB and set the Builder's insertion point there for
3395   // body generation next. Place the block after the current block.
3396   Function *CurFn = EntryBB->getParent();
3397   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
3398 
3399   // Move Entry branch to end of ThenBB, and replace with conditional
3400   // branch (If-stmt)
3401   Instruction *EntryBBTI = EntryBB->getTerminator();
3402   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
3403   EntryBBTI->removeFromParent();
3404   Builder.SetInsertPoint(UI);
3405   Builder.Insert(EntryBBTI);
3406   UI->eraseFromParent();
3407   Builder.SetInsertPoint(ThenBB->getTerminator());
3408 
3409   // return an insertion point to ExitBB.
3410   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
3411 }
3412 
3413 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
3414     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
3415     bool HasFinalize) {
3416 
3417   Builder.restoreIP(FinIP);
3418 
3419   // If there is finalization to do, emit it before the exit call
3420   if (HasFinalize) {
3421     assert(!FinalizationStack.empty() &&
3422            "Unexpected finalization stack state!");
3423 
3424     FinalizationInfo Fi = FinalizationStack.pop_back_val();
3425     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3426 
3427     Fi.FiniCB(FinIP);
3428 
3429     BasicBlock *FiniBB = FinIP.getBlock();
3430     Instruction *FiniBBTI = FiniBB->getTerminator();
3431 
3432     // set Builder IP for call creation
3433     Builder.SetInsertPoint(FiniBBTI);
3434   }
3435 
3436   if (!ExitCall)
3437     return Builder.saveIP();
3438 
3439   // place the Exitcall as last instruction before Finalization block terminator
3440   ExitCall->removeFromParent();
3441   Builder.Insert(ExitCall);
3442 
3443   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3444                                   ExitCall->getIterator());
3445 }
3446 
3447 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
3448     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3449     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3450   if (!IP.isSet())
3451     return IP;
3452 
3453   IRBuilder<>::InsertPointGuard IPG(Builder);
3454 
3455   // creates the following CFG structure
3456   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
3457   //       F     T
3458   //       |      \
3459   //       |     copin.not.master
3460   //       |      /
3461   //       v     /
3462   //   copyin.not.master.end
3463   //		     |
3464   //         v
3465   //   OMP.Entry.Next
3466 
3467   BasicBlock *OMP_Entry = IP.getBlock();
3468   Function *CurFn = OMP_Entry->getParent();
3469   BasicBlock *CopyBegin =
3470       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3471   BasicBlock *CopyEnd = nullptr;
3472 
3473   // If entry block is terminated, split to preserve the branch to following
3474   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3475   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3476     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3477                                          "copyin.not.master.end");
3478     OMP_Entry->getTerminator()->eraseFromParent();
3479   } else {
3480     CopyEnd =
3481         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3482   }
3483 
3484   Builder.SetInsertPoint(OMP_Entry);
3485   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3486   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3487   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3488   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3489 
3490   Builder.SetInsertPoint(CopyBegin);
3491   if (BranchtoEnd)
3492     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
3493 
3494   return Builder.saveIP();
3495 }
3496 
3497 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
3498                                           Value *Size, Value *Allocator,
3499                                           std::string Name) {
3500   IRBuilder<>::InsertPointGuard IPG(Builder);
3501   Builder.restoreIP(Loc.IP);
3502 
3503   uint32_t SrcLocStrSize;
3504   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3505   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3506   Value *ThreadId = getOrCreateThreadID(Ident);
3507   Value *Args[] = {ThreadId, Size, Allocator};
3508 
3509   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3510 
3511   return Builder.CreateCall(Fn, Args, Name);
3512 }
3513 
3514 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
3515                                          Value *Addr, Value *Allocator,
3516                                          std::string Name) {
3517   IRBuilder<>::InsertPointGuard IPG(Builder);
3518   Builder.restoreIP(Loc.IP);
3519 
3520   uint32_t SrcLocStrSize;
3521   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3522   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3523   Value *ThreadId = getOrCreateThreadID(Ident);
3524   Value *Args[] = {ThreadId, Addr, Allocator};
3525   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3526   return Builder.CreateCall(Fn, Args, Name);
3527 }
3528 
3529 CallInst *OpenMPIRBuilder::createOMPInteropInit(
3530     const LocationDescription &Loc, Value *InteropVar,
3531     omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3532     Value *DependenceAddress, bool HaveNowaitClause) {
3533   IRBuilder<>::InsertPointGuard IPG(Builder);
3534   Builder.restoreIP(Loc.IP);
3535 
3536   uint32_t SrcLocStrSize;
3537   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3538   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3539   Value *ThreadId = getOrCreateThreadID(Ident);
3540   if (Device == nullptr)
3541     Device = ConstantInt::get(Int32, -1);
3542   Constant *InteropTypeVal = ConstantInt::get(Int64, (int)InteropType);
3543   if (NumDependences == nullptr) {
3544     NumDependences = ConstantInt::get(Int32, 0);
3545     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3546     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3547   }
3548   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3549   Value *Args[] = {
3550       Ident,  ThreadId,       InteropVar,        InteropTypeVal,
3551       Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
3552 
3553   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
3554 
3555   return Builder.CreateCall(Fn, Args);
3556 }
3557 
3558 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
3559     const LocationDescription &Loc, Value *InteropVar, Value *Device,
3560     Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
3561   IRBuilder<>::InsertPointGuard IPG(Builder);
3562   Builder.restoreIP(Loc.IP);
3563 
3564   uint32_t SrcLocStrSize;
3565   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3566   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3567   Value *ThreadId = getOrCreateThreadID(Ident);
3568   if (Device == nullptr)
3569     Device = ConstantInt::get(Int32, -1);
3570   if (NumDependences == nullptr) {
3571     NumDependences = ConstantInt::get(Int32, 0);
3572     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3573     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3574   }
3575   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3576   Value *Args[] = {
3577       Ident,          ThreadId,          InteropVar,         Device,
3578       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3579 
3580   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
3581 
3582   return Builder.CreateCall(Fn, Args);
3583 }
3584 
3585 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
3586                                                Value *InteropVar, Value *Device,
3587                                                Value *NumDependences,
3588                                                Value *DependenceAddress,
3589                                                bool HaveNowaitClause) {
3590   IRBuilder<>::InsertPointGuard IPG(Builder);
3591   Builder.restoreIP(Loc.IP);
3592   uint32_t SrcLocStrSize;
3593   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3594   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3595   Value *ThreadId = getOrCreateThreadID(Ident);
3596   if (Device == nullptr)
3597     Device = ConstantInt::get(Int32, -1);
3598   if (NumDependences == nullptr) {
3599     NumDependences = ConstantInt::get(Int32, 0);
3600     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3601     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3602   }
3603   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3604   Value *Args[] = {
3605       Ident,          ThreadId,          InteropVar,         Device,
3606       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3607 
3608   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
3609 
3610   return Builder.CreateCall(Fn, Args);
3611 }
3612 
3613 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
3614     const LocationDescription &Loc, llvm::Value *Pointer,
3615     llvm::ConstantInt *Size, const llvm::Twine &Name) {
3616   IRBuilder<>::InsertPointGuard IPG(Builder);
3617   Builder.restoreIP(Loc.IP);
3618 
3619   uint32_t SrcLocStrSize;
3620   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3621   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3622   Value *ThreadId = getOrCreateThreadID(Ident);
3623   Constant *ThreadPrivateCache =
3624       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
3625   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
3626 
3627   Function *Fn =
3628       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
3629 
3630   return Builder.CreateCall(Fn, Args);
3631 }
3632 
3633 OpenMPIRBuilder::InsertPointTy
3634 OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
3635                                   bool RequiresFullRuntime) {
3636   if (!updateToLocation(Loc))
3637     return Loc.IP;
3638 
3639   uint32_t SrcLocStrSize;
3640   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3641   Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3642   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3643       IntegerType::getInt8Ty(Int8->getContext()),
3644       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3645   ConstantInt *UseGenericStateMachine =
3646       ConstantInt::getBool(Int32->getContext(), !IsSPMD);
3647   ConstantInt *RequiresFullRuntimeVal =
3648       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3649 
3650   Function *Fn = getOrCreateRuntimeFunctionPtr(
3651       omp::RuntimeFunction::OMPRTL___kmpc_target_init);
3652 
3653   CallInst *ThreadKind = Builder.CreateCall(
3654       Fn, {Ident, IsSPMDVal, UseGenericStateMachine, RequiresFullRuntimeVal});
3655 
3656   Value *ExecUserCode = Builder.CreateICmpEQ(
3657       ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
3658       "exec_user_code");
3659 
3660   // ThreadKind = __kmpc_target_init(...)
3661   // if (ThreadKind == -1)
3662   //   user_code
3663   // else
3664   //   return;
3665 
3666   auto *UI = Builder.CreateUnreachable();
3667   BasicBlock *CheckBB = UI->getParent();
3668   BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
3669 
3670   BasicBlock *WorkerExitBB = BasicBlock::Create(
3671       CheckBB->getContext(), "worker.exit", CheckBB->getParent());
3672   Builder.SetInsertPoint(WorkerExitBB);
3673   Builder.CreateRetVoid();
3674 
3675   auto *CheckBBTI = CheckBB->getTerminator();
3676   Builder.SetInsertPoint(CheckBBTI);
3677   Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
3678 
3679   CheckBBTI->eraseFromParent();
3680   UI->eraseFromParent();
3681 
3682   // Continue in the "user_code" block, see diagram above and in
3683   // openmp/libomptarget/deviceRTLs/common/include/target.h .
3684   return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
3685 }
3686 
3687 void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,
3688                                          bool IsSPMD,
3689                                          bool RequiresFullRuntime) {
3690   if (!updateToLocation(Loc))
3691     return;
3692 
3693   uint32_t SrcLocStrSize;
3694   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3695   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3696   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3697       IntegerType::getInt8Ty(Int8->getContext()),
3698       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3699   ConstantInt *RequiresFullRuntimeVal =
3700       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3701 
3702   Function *Fn = getOrCreateRuntimeFunctionPtr(
3703       omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
3704 
3705   Builder.CreateCall(Fn, {Ident, IsSPMDVal, RequiresFullRuntimeVal});
3706 }
3707 
3708 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
3709                                                    StringRef FirstSeparator,
3710                                                    StringRef Separator) {
3711   SmallString<128> Buffer;
3712   llvm::raw_svector_ostream OS(Buffer);
3713   StringRef Sep = FirstSeparator;
3714   for (StringRef Part : Parts) {
3715     OS << Sep << Part;
3716     Sep = Separator;
3717   }
3718   return OS.str().str();
3719 }
3720 
3721 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
3722     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
3723   // TODO: Replace the twine arg with stringref to get rid of the conversion
3724   // logic. However This is taken from current implementation in clang as is.
3725   // Since this method is used in many places exclusively for OMP internal use
3726   // we will keep it as is for temporarily until we move all users to the
3727   // builder and then, if possible, fix it everywhere in one go.
3728   SmallString<256> Buffer;
3729   llvm::raw_svector_ostream Out(Buffer);
3730   Out << Name;
3731   StringRef RuntimeName = Out.str();
3732   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
3733   if (Elem.second) {
3734     assert(cast<PointerType>(Elem.second->getType())
3735                ->isOpaqueOrPointeeTypeMatches(Ty) &&
3736            "OMP internal variable has different type than requested");
3737   } else {
3738     // TODO: investigate the appropriate linkage type used for the global
3739     // variable for possibly changing that to internal or private, or maybe
3740     // create different versions of the function for different OMP internal
3741     // variables.
3742     Elem.second = new llvm::GlobalVariable(
3743         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
3744         llvm::Constant::getNullValue(Ty), Elem.first(),
3745         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3746         AddressSpace);
3747   }
3748 
3749   return Elem.second;
3750 }
3751 
3752 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
3753   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
3754   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
3755   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
3756 }
3757 
3758 GlobalVariable *
3759 OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
3760                                        std::string VarName) {
3761   llvm::Constant *MaptypesArrayInit =
3762       llvm::ConstantDataArray::get(M.getContext(), Mappings);
3763   auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
3764       M, MaptypesArrayInit->getType(),
3765       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
3766       VarName);
3767   MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3768   return MaptypesArrayGlobal;
3769 }
3770 
3771 void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,
3772                                           InsertPointTy AllocaIP,
3773                                           unsigned NumOperands,
3774                                           struct MapperAllocas &MapperAllocas) {
3775   if (!updateToLocation(Loc))
3776     return;
3777 
3778   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3779   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3780   Builder.restoreIP(AllocaIP);
3781   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI8PtrTy);
3782   AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy);
3783   AllocaInst *ArgSizes = Builder.CreateAlloca(ArrI64Ty);
3784   Builder.restoreIP(Loc.IP);
3785   MapperAllocas.ArgsBase = ArgsBase;
3786   MapperAllocas.Args = Args;
3787   MapperAllocas.ArgSizes = ArgSizes;
3788 }
3789 
3790 void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,
3791                                      Function *MapperFunc, Value *SrcLocInfo,
3792                                      Value *MaptypesArg, Value *MapnamesArg,
3793                                      struct MapperAllocas &MapperAllocas,
3794                                      int64_t DeviceID, unsigned NumOperands) {
3795   if (!updateToLocation(Loc))
3796     return;
3797 
3798   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3799   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3800   Value *ArgsBaseGEP =
3801       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
3802                                 {Builder.getInt32(0), Builder.getInt32(0)});
3803   Value *ArgsGEP =
3804       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
3805                                 {Builder.getInt32(0), Builder.getInt32(0)});
3806   Value *ArgSizesGEP =
3807       Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
3808                                 {Builder.getInt32(0), Builder.getInt32(0)});
3809   Value *NullPtr = Constant::getNullValue(Int8Ptr->getPointerTo());
3810   Builder.CreateCall(MapperFunc,
3811                      {SrcLocInfo, Builder.getInt64(DeviceID),
3812                       Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,
3813                       ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
3814 }
3815 
3816 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
3817     const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
3818   assert(!(AO == AtomicOrdering::NotAtomic ||
3819            AO == llvm::AtomicOrdering::Unordered) &&
3820          "Unexpected Atomic Ordering.");
3821 
3822   bool Flush = false;
3823   llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;
3824 
3825   switch (AK) {
3826   case Read:
3827     if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||
3828         AO == AtomicOrdering::SequentiallyConsistent) {
3829       FlushAO = AtomicOrdering::Acquire;
3830       Flush = true;
3831     }
3832     break;
3833   case Write:
3834   case Compare:
3835   case Update:
3836     if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||
3837         AO == AtomicOrdering::SequentiallyConsistent) {
3838       FlushAO = AtomicOrdering::Release;
3839       Flush = true;
3840     }
3841     break;
3842   case Capture:
3843     switch (AO) {
3844     case AtomicOrdering::Acquire:
3845       FlushAO = AtomicOrdering::Acquire;
3846       Flush = true;
3847       break;
3848     case AtomicOrdering::Release:
3849       FlushAO = AtomicOrdering::Release;
3850       Flush = true;
3851       break;
3852     case AtomicOrdering::AcquireRelease:
3853     case AtomicOrdering::SequentiallyConsistent:
3854       FlushAO = AtomicOrdering::AcquireRelease;
3855       Flush = true;
3856       break;
3857     default:
3858       // do nothing - leave silently.
3859       break;
3860     }
3861   }
3862 
3863   if (Flush) {
3864     // Currently Flush RT call still doesn't take memory_ordering, so for when
3865     // that happens, this tries to do the resolution of which atomic ordering
3866     // to use with but issue the flush call
3867     // TODO: pass `FlushAO` after memory ordering support is added
3868     (void)FlushAO;
3869     emitFlush(Loc);
3870   }
3871 
3872   // for AO == AtomicOrdering::Monotonic and  all other case combinations
3873   // do nothing
3874   return Flush;
3875 }
3876 
3877 OpenMPIRBuilder::InsertPointTy
3878 OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,
3879                                   AtomicOpValue &X, AtomicOpValue &V,
3880                                   AtomicOrdering AO) {
3881   if (!updateToLocation(Loc))
3882     return Loc.IP;
3883 
3884   Type *XTy = X.Var->getType();
3885   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3886   Type *XElemTy = X.ElemTy;
3887   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3888           XElemTy->isPointerTy()) &&
3889          "OMP atomic read expected a scalar type");
3890 
3891   Value *XRead = nullptr;
3892 
3893   if (XElemTy->isIntegerTy()) {
3894     LoadInst *XLD =
3895         Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
3896     XLD->setAtomic(AO);
3897     XRead = cast<Value>(XLD);
3898   } else {
3899     // We need to bitcast and perform atomic op as integer
3900     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3901     IntegerType *IntCastTy =
3902         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3903     Value *XBCast = Builder.CreateBitCast(
3904         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.src.int.cast");
3905     LoadInst *XLoad =
3906         Builder.CreateLoad(IntCastTy, XBCast, X.IsVolatile, "omp.atomic.load");
3907     XLoad->setAtomic(AO);
3908     if (XElemTy->isFloatingPointTy()) {
3909       XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
3910     } else {
3911       XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
3912     }
3913   }
3914   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);
3915   Builder.CreateStore(XRead, V.Var, V.IsVolatile);
3916   return Builder.saveIP();
3917 }
3918 
3919 OpenMPIRBuilder::InsertPointTy
3920 OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,
3921                                    AtomicOpValue &X, Value *Expr,
3922                                    AtomicOrdering AO) {
3923   if (!updateToLocation(Loc))
3924     return Loc.IP;
3925 
3926   Type *XTy = X.Var->getType();
3927   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3928   Type *XElemTy = X.ElemTy;
3929   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3930           XElemTy->isPointerTy()) &&
3931          "OMP atomic write expected a scalar type");
3932 
3933   if (XElemTy->isIntegerTy()) {
3934     StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
3935     XSt->setAtomic(AO);
3936   } else {
3937     // We need to bitcast and perform atomic op as integers
3938     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3939     IntegerType *IntCastTy =
3940         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3941     Value *XBCast = Builder.CreateBitCast(
3942         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.dst.int.cast");
3943     Value *ExprCast =
3944         Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
3945     StoreInst *XSt = Builder.CreateStore(ExprCast, XBCast, X.IsVolatile);
3946     XSt->setAtomic(AO);
3947   }
3948 
3949   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);
3950   return Builder.saveIP();
3951 }
3952 
3953 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(
3954     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3955     Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3956     AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {
3957   assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
3958   if (!updateToLocation(Loc))
3959     return Loc.IP;
3960 
3961   LLVM_DEBUG({
3962     Type *XTy = X.Var->getType();
3963     assert(XTy->isPointerTy() &&
3964            "OMP Atomic expects a pointer to target memory");
3965     Type *XElemTy = X.ElemTy;
3966     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3967             XElemTy->isPointerTy()) &&
3968            "OMP atomic update expected a scalar type");
3969     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3970            (RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&
3971            "OpenMP atomic does not support LT or GT operations");
3972   });
3973 
3974   emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,
3975                    X.IsVolatile, IsXBinopExpr);
3976   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);
3977   return Builder.saveIP();
3978 }
3979 
3980 Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3981                                                AtomicRMWInst::BinOp RMWOp) {
3982   switch (RMWOp) {
3983   case AtomicRMWInst::Add:
3984     return Builder.CreateAdd(Src1, Src2);
3985   case AtomicRMWInst::Sub:
3986     return Builder.CreateSub(Src1, Src2);
3987   case AtomicRMWInst::And:
3988     return Builder.CreateAnd(Src1, Src2);
3989   case AtomicRMWInst::Nand:
3990     return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
3991   case AtomicRMWInst::Or:
3992     return Builder.CreateOr(Src1, Src2);
3993   case AtomicRMWInst::Xor:
3994     return Builder.CreateXor(Src1, Src2);
3995   case AtomicRMWInst::Xchg:
3996   case AtomicRMWInst::FAdd:
3997   case AtomicRMWInst::FSub:
3998   case AtomicRMWInst::BAD_BINOP:
3999   case AtomicRMWInst::Max:
4000   case AtomicRMWInst::Min:
4001   case AtomicRMWInst::UMax:
4002   case AtomicRMWInst::UMin:
4003   case AtomicRMWInst::FMax:
4004   case AtomicRMWInst::FMin:
4005     llvm_unreachable("Unsupported atomic update operation");
4006   }
4007   llvm_unreachable("Unsupported atomic update operation");
4008 }
4009 
4010 std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(
4011     InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
4012     AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
4013     AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {
4014   // TODO: handle the case where XElemTy is not byte-sized or not a power of 2
4015   // or a complex datatype.
4016   bool emitRMWOp = false;
4017   switch (RMWOp) {
4018   case AtomicRMWInst::Add:
4019   case AtomicRMWInst::And:
4020   case AtomicRMWInst::Nand:
4021   case AtomicRMWInst::Or:
4022   case AtomicRMWInst::Xor:
4023   case AtomicRMWInst::Xchg:
4024     emitRMWOp = XElemTy;
4025     break;
4026   case AtomicRMWInst::Sub:
4027     emitRMWOp = (IsXBinopExpr && XElemTy);
4028     break;
4029   default:
4030     emitRMWOp = false;
4031   }
4032   emitRMWOp &= XElemTy->isIntegerTy();
4033 
4034   std::pair<Value *, Value *> Res;
4035   if (emitRMWOp) {
4036     Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
4037     // not needed except in case of postfix captures. Generate anyway for
4038     // consistency with the else part. Will be removed with any DCE pass.
4039     // AtomicRMWInst::Xchg does not have a coressponding instruction.
4040     if (RMWOp == AtomicRMWInst::Xchg)
4041       Res.second = Res.first;
4042     else
4043       Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
4044   } else {
4045     unsigned Addrspace = cast<PointerType>(X->getType())->getAddressSpace();
4046     IntegerType *IntCastTy =
4047         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
4048     Value *XBCast =
4049         Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
4050     LoadInst *OldVal =
4051         Builder.CreateLoad(IntCastTy, XBCast, X->getName() + ".atomic.load");
4052     OldVal->setAtomic(AO);
4053     // CurBB
4054     // |     /---\
4055 		// ContBB    |
4056     // |     \---/
4057     // ExitBB
4058     BasicBlock *CurBB = Builder.GetInsertBlock();
4059     Instruction *CurBBTI = CurBB->getTerminator();
4060     CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
4061     BasicBlock *ExitBB =
4062         CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
4063     BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
4064                                                 X->getName() + ".atomic.cont");
4065     ContBB->getTerminator()->eraseFromParent();
4066     Builder.restoreIP(AllocaIP);
4067     AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
4068     NewAtomicAddr->setName(X->getName() + "x.new.val");
4069     Builder.SetInsertPoint(ContBB);
4070     llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
4071     PHI->addIncoming(OldVal, CurBB);
4072     IntegerType *NewAtomicCastTy =
4073         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
4074     bool IsIntTy = XElemTy->isIntegerTy();
4075     Value *NewAtomicIntAddr =
4076         (IsIntTy)
4077             ? NewAtomicAddr
4078             : Builder.CreateBitCast(NewAtomicAddr,
4079                                     NewAtomicCastTy->getPointerTo(Addrspace));
4080     Value *OldExprVal = PHI;
4081     if (!IsIntTy) {
4082       if (XElemTy->isFloatingPointTy()) {
4083         OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
4084                                            X->getName() + ".atomic.fltCast");
4085       } else {
4086         OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
4087                                             X->getName() + ".atomic.ptrCast");
4088       }
4089     }
4090 
4091     Value *Upd = UpdateOp(OldExprVal, Builder);
4092     Builder.CreateStore(Upd, NewAtomicAddr);
4093     LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicIntAddr);
4094     Value *XAddr =
4095         (IsIntTy)
4096             ? X
4097             : Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
4098     AtomicOrdering Failure =
4099         llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
4100     AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
4101         XAddr, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
4102     Result->setVolatile(VolatileX);
4103     Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
4104     Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4105     PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
4106     Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
4107 
4108     Res.first = OldExprVal;
4109     Res.second = Upd;
4110 
4111     // set Insertion point in exit block
4112     if (UnreachableInst *ExitTI =
4113             dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
4114       CurBBTI->eraseFromParent();
4115       Builder.SetInsertPoint(ExitBB);
4116     } else {
4117       Builder.SetInsertPoint(ExitTI);
4118     }
4119   }
4120 
4121   return Res;
4122 }
4123 
4124 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(
4125     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
4126     AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
4127     AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
4128     bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {
4129   if (!updateToLocation(Loc))
4130     return Loc.IP;
4131 
4132   LLVM_DEBUG({
4133     Type *XTy = X.Var->getType();
4134     assert(XTy->isPointerTy() &&
4135            "OMP Atomic expects a pointer to target memory");
4136     Type *XElemTy = X.ElemTy;
4137     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
4138             XElemTy->isPointerTy()) &&
4139            "OMP atomic capture expected a scalar type");
4140     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
4141            "OpenMP atomic does not support LT or GT operations");
4142   });
4143 
4144   // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
4145   // 'x' is simply atomically rewritten with 'expr'.
4146   AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
4147   std::pair<Value *, Value *> Result =
4148       emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
4149                        X.IsVolatile, IsXBinopExpr);
4150 
4151   Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);
4152   Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
4153 
4154   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);
4155   return Builder.saveIP();
4156 }
4157 
4158 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(
4159     const LocationDescription &Loc, AtomicOpValue &X, AtomicOpValue &V,
4160     AtomicOpValue &R, Value *E, Value *D, AtomicOrdering AO,
4161     omp::OMPAtomicCompareOp Op, bool IsXBinopExpr, bool IsPostfixUpdate,
4162     bool IsFailOnly) {
4163 
4164   if (!updateToLocation(Loc))
4165     return Loc.IP;
4166 
4167   assert(X.Var->getType()->isPointerTy() &&
4168          "OMP atomic expects a pointer to target memory");
4169   // compare capture
4170   if (V.Var) {
4171     assert(V.Var->getType()->isPointerTy() && "v.var must be of pointer type");
4172     assert(V.ElemTy == X.ElemTy && "x and v must be of same type");
4173   }
4174 
4175   bool IsInteger = E->getType()->isIntegerTy();
4176 
4177   if (Op == OMPAtomicCompareOp::EQ) {
4178     AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
4179     AtomicCmpXchgInst *Result = nullptr;
4180     if (!IsInteger) {
4181       unsigned Addrspace =
4182           cast<PointerType>(X.Var->getType())->getAddressSpace();
4183       IntegerType *IntCastTy =
4184           IntegerType::get(M.getContext(), X.ElemTy->getScalarSizeInBits());
4185       Value *XBCast =
4186           Builder.CreateBitCast(X.Var, IntCastTy->getPointerTo(Addrspace));
4187       Value *EBCast = Builder.CreateBitCast(E, IntCastTy);
4188       Value *DBCast = Builder.CreateBitCast(D, IntCastTy);
4189       Result = Builder.CreateAtomicCmpXchg(XBCast, EBCast, DBCast, MaybeAlign(),
4190                                            AO, Failure);
4191     } else {
4192       Result =
4193           Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
4194     }
4195 
4196     if (V.Var) {
4197       Value *OldValue = Builder.CreateExtractValue(Result, /*Idxs=*/0);
4198       if (!IsInteger)
4199         OldValue = Builder.CreateBitCast(OldValue, X.ElemTy);
4200       assert(OldValue->getType() == V.ElemTy &&
4201              "OldValue and V must be of same type");
4202       if (IsPostfixUpdate) {
4203         Builder.CreateStore(OldValue, V.Var, V.IsVolatile);
4204       } else {
4205         Value *SuccessOrFail = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4206         if (IsFailOnly) {
4207           // CurBB----
4208           //   |     |
4209           //   v     |
4210           // ContBB  |
4211           //   |     |
4212           //   v     |
4213           // ExitBB <-
4214           //
4215           // where ContBB only contains the store of old value to 'v'.
4216           BasicBlock *CurBB = Builder.GetInsertBlock();
4217           Instruction *CurBBTI = CurBB->getTerminator();
4218           CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
4219           BasicBlock *ExitBB = CurBB->splitBasicBlock(
4220               CurBBTI, X.Var->getName() + ".atomic.exit");
4221           BasicBlock *ContBB = CurBB->splitBasicBlock(
4222               CurBB->getTerminator(), X.Var->getName() + ".atomic.cont");
4223           ContBB->getTerminator()->eraseFromParent();
4224           CurBB->getTerminator()->eraseFromParent();
4225 
4226           Builder.CreateCondBr(SuccessOrFail, ExitBB, ContBB);
4227 
4228           Builder.SetInsertPoint(ContBB);
4229           Builder.CreateStore(OldValue, V.Var);
4230           Builder.CreateBr(ExitBB);
4231 
4232           if (UnreachableInst *ExitTI =
4233                   dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
4234             CurBBTI->eraseFromParent();
4235             Builder.SetInsertPoint(ExitBB);
4236           } else {
4237             Builder.SetInsertPoint(ExitTI);
4238           }
4239         } else {
4240           Value *CapturedValue =
4241               Builder.CreateSelect(SuccessOrFail, E, OldValue);
4242           Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
4243         }
4244       }
4245     }
4246     // The comparison result has to be stored.
4247     if (R.Var) {
4248       assert(R.Var->getType()->isPointerTy() &&
4249              "r.var must be of pointer type");
4250       assert(R.ElemTy->isIntegerTy() && "r must be of integral type");
4251 
4252       Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
4253       Value *ResultCast = R.IsSigned
4254                               ? Builder.CreateSExt(SuccessFailureVal, R.ElemTy)
4255                               : Builder.CreateZExt(SuccessFailureVal, R.ElemTy);
4256       Builder.CreateStore(ResultCast, R.Var, R.IsVolatile);
4257     }
4258   } else {
4259     assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
4260            "Op should be either max or min at this point");
4261     assert(!IsFailOnly && "IsFailOnly is only valid when the comparison is ==");
4262 
4263     // Reverse the ordop as the OpenMP forms are different from LLVM forms.
4264     // Let's take max as example.
4265     // OpenMP form:
4266     // x = x > expr ? expr : x;
4267     // LLVM form:
4268     // *ptr = *ptr > val ? *ptr : val;
4269     // We need to transform to LLVM form.
4270     // x = x <= expr ? x : expr;
4271     AtomicRMWInst::BinOp NewOp;
4272     if (IsXBinopExpr) {
4273       if (IsInteger) {
4274         if (X.IsSigned)
4275           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
4276                                                 : AtomicRMWInst::Max;
4277         else
4278           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
4279                                                 : AtomicRMWInst::UMax;
4280       } else {
4281         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMin
4282                                               : AtomicRMWInst::FMax;
4283       }
4284     } else {
4285       if (IsInteger) {
4286         if (X.IsSigned)
4287           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
4288                                                 : AtomicRMWInst::Min;
4289         else
4290           NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
4291                                                 : AtomicRMWInst::UMin;
4292       } else {
4293         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::FMax
4294                                               : AtomicRMWInst::FMin;
4295       }
4296     }
4297 
4298     AtomicRMWInst *OldValue =
4299         Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
4300     if (V.Var) {
4301       Value *CapturedValue = nullptr;
4302       if (IsPostfixUpdate) {
4303         CapturedValue = OldValue;
4304       } else {
4305         CmpInst::Predicate Pred;
4306         switch (NewOp) {
4307         case AtomicRMWInst::Max:
4308           Pred = CmpInst::ICMP_SGT;
4309           break;
4310         case AtomicRMWInst::UMax:
4311           Pred = CmpInst::ICMP_UGT;
4312           break;
4313         case AtomicRMWInst::FMax:
4314           Pred = CmpInst::FCMP_OGT;
4315           break;
4316         case AtomicRMWInst::Min:
4317           Pred = CmpInst::ICMP_SLT;
4318           break;
4319         case AtomicRMWInst::UMin:
4320           Pred = CmpInst::ICMP_ULT;
4321           break;
4322         case AtomicRMWInst::FMin:
4323           Pred = CmpInst::FCMP_OLT;
4324           break;
4325         default:
4326           llvm_unreachable("unexpected comparison op");
4327         }
4328         Value *NonAtomicCmp = Builder.CreateCmp(Pred, OldValue, E);
4329         CapturedValue = Builder.CreateSelect(NonAtomicCmp, E, OldValue);
4330       }
4331       Builder.CreateStore(CapturedValue, V.Var, V.IsVolatile);
4332     }
4333   }
4334 
4335   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);
4336 
4337   return Builder.saveIP();
4338 }
4339 
4340 GlobalVariable *
4341 OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
4342                                        std::string VarName) {
4343   llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
4344       llvm::ArrayType::get(
4345           llvm::Type::getInt8Ty(M.getContext())->getPointerTo(), Names.size()),
4346       Names);
4347   auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
4348       M, MapNamesArrayInit->getType(),
4349       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
4350       VarName);
4351   return MapNamesArrayGlobal;
4352 }
4353 
4354 // Create all simple and struct types exposed by the runtime and remember
4355 // the llvm::PointerTypes of them for easy access later.
4356 void OpenMPIRBuilder::initializeTypes(Module &M) {
4357   LLVMContext &Ctx = M.getContext();
4358   StructType *T;
4359 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
4360 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
4361   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
4362   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
4363 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
4364   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
4365   VarName##Ptr = PointerType::getUnqual(VarName);
4366 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
4367   T = StructType::getTypeByName(Ctx, StructName);                              \
4368   if (!T)                                                                      \
4369     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
4370   VarName = T;                                                                 \
4371   VarName##Ptr = PointerType::getUnqual(T);
4372 #include "llvm/Frontend/OpenMP/OMPKinds.def"
4373 }
4374 
4375 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
4376     SmallPtrSetImpl<BasicBlock *> &BlockSet,
4377     SmallVectorImpl<BasicBlock *> &BlockVector) {
4378   SmallVector<BasicBlock *, 32> Worklist;
4379   BlockSet.insert(EntryBB);
4380   BlockSet.insert(ExitBB);
4381 
4382   Worklist.push_back(EntryBB);
4383   while (!Worklist.empty()) {
4384     BasicBlock *BB = Worklist.pop_back_val();
4385     BlockVector.push_back(BB);
4386     for (BasicBlock *SuccBB : successors(BB))
4387       if (BlockSet.insert(SuccBB).second)
4388         Worklist.push_back(SuccBB);
4389   }
4390 }
4391 
4392 void CanonicalLoopInfo::collectControlBlocks(
4393     SmallVectorImpl<BasicBlock *> &BBs) {
4394   // We only count those BBs as control block for which we do not need to
4395   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
4396   // flow. For consistency, this also means we do not add the Body block, which
4397   // is just the entry to the body code.
4398   BBs.reserve(BBs.size() + 6);
4399   BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
4400 }
4401 
4402 BasicBlock *CanonicalLoopInfo::getPreheader() const {
4403   assert(isValid() && "Requires a valid canonical loop");
4404   for (BasicBlock *Pred : predecessors(Header)) {
4405     if (Pred != Latch)
4406       return Pred;
4407   }
4408   llvm_unreachable("Missing preheader");
4409 }
4410 
4411 void CanonicalLoopInfo::setTripCount(Value *TripCount) {
4412   assert(isValid() && "Requires a valid canonical loop");
4413 
4414   Instruction *CmpI = &getCond()->front();
4415   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
4416   CmpI->setOperand(1, TripCount);
4417 
4418 #ifndef NDEBUG
4419   assertOK();
4420 #endif
4421 }
4422 
4423 void CanonicalLoopInfo::mapIndVar(
4424     llvm::function_ref<Value *(Instruction *)> Updater) {
4425   assert(isValid() && "Requires a valid canonical loop");
4426 
4427   Instruction *OldIV = getIndVar();
4428 
4429   // Record all uses excluding those introduced by the updater. Uses by the
4430   // CanonicalLoopInfo itself to keep track of the number of iterations are
4431   // excluded.
4432   SmallVector<Use *> ReplacableUses;
4433   for (Use &U : OldIV->uses()) {
4434     auto *User = dyn_cast<Instruction>(U.getUser());
4435     if (!User)
4436       continue;
4437     if (User->getParent() == getCond())
4438       continue;
4439     if (User->getParent() == getLatch())
4440       continue;
4441     ReplacableUses.push_back(&U);
4442   }
4443 
4444   // Run the updater that may introduce new uses
4445   Value *NewIV = Updater(OldIV);
4446 
4447   // Replace the old uses with the value returned by the updater.
4448   for (Use *U : ReplacableUses)
4449     U->set(NewIV);
4450 
4451 #ifndef NDEBUG
4452   assertOK();
4453 #endif
4454 }
4455 
4456 void CanonicalLoopInfo::assertOK() const {
4457 #ifndef NDEBUG
4458   // No constraints if this object currently does not describe a loop.
4459   if (!isValid())
4460     return;
4461 
4462   BasicBlock *Preheader = getPreheader();
4463   BasicBlock *Body = getBody();
4464   BasicBlock *After = getAfter();
4465 
4466   // Verify standard control-flow we use for OpenMP loops.
4467   assert(Preheader);
4468   assert(isa<BranchInst>(Preheader->getTerminator()) &&
4469          "Preheader must terminate with unconditional branch");
4470   assert(Preheader->getSingleSuccessor() == Header &&
4471          "Preheader must jump to header");
4472 
4473   assert(Header);
4474   assert(isa<BranchInst>(Header->getTerminator()) &&
4475          "Header must terminate with unconditional branch");
4476   assert(Header->getSingleSuccessor() == Cond &&
4477          "Header must jump to exiting block");
4478 
4479   assert(Cond);
4480   assert(Cond->getSinglePredecessor() == Header &&
4481          "Exiting block only reachable from header");
4482 
4483   assert(isa<BranchInst>(Cond->getTerminator()) &&
4484          "Exiting block must terminate with conditional branch");
4485   assert(size(successors(Cond)) == 2 &&
4486          "Exiting block must have two successors");
4487   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
4488          "Exiting block's first successor jump to the body");
4489   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
4490          "Exiting block's second successor must exit the loop");
4491 
4492   assert(Body);
4493   assert(Body->getSinglePredecessor() == Cond &&
4494          "Body only reachable from exiting block");
4495   assert(!isa<PHINode>(Body->front()));
4496 
4497   assert(Latch);
4498   assert(isa<BranchInst>(Latch->getTerminator()) &&
4499          "Latch must terminate with unconditional branch");
4500   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
4501   // TODO: To support simple redirecting of the end of the body code that has
4502   // multiple; introduce another auxiliary basic block like preheader and after.
4503   assert(Latch->getSinglePredecessor() != nullptr);
4504   assert(!isa<PHINode>(Latch->front()));
4505 
4506   assert(Exit);
4507   assert(isa<BranchInst>(Exit->getTerminator()) &&
4508          "Exit block must terminate with unconditional branch");
4509   assert(Exit->getSingleSuccessor() == After &&
4510          "Exit block must jump to after block");
4511 
4512   assert(After);
4513   assert(After->getSinglePredecessor() == Exit &&
4514          "After block only reachable from exit block");
4515   assert(After->empty() || !isa<PHINode>(After->front()));
4516 
4517   Instruction *IndVar = getIndVar();
4518   assert(IndVar && "Canonical induction variable not found?");
4519   assert(isa<IntegerType>(IndVar->getType()) &&
4520          "Induction variable must be an integer");
4521   assert(cast<PHINode>(IndVar)->getParent() == Header &&
4522          "Induction variable must be a PHI in the loop header");
4523   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
4524   assert(
4525       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
4526   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
4527 
4528   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
4529   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
4530   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
4531   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
4532   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
4533              ->isOne());
4534 
4535   Value *TripCount = getTripCount();
4536   assert(TripCount && "Loop trip count not found?");
4537   assert(IndVar->getType() == TripCount->getType() &&
4538          "Trip count and induction variable must have the same type");
4539 
4540   auto *CmpI = cast<CmpInst>(&Cond->front());
4541   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
4542          "Exit condition must be a signed less-than comparison");
4543   assert(CmpI->getOperand(0) == IndVar &&
4544          "Exit condition must compare the induction variable");
4545   assert(CmpI->getOperand(1) == TripCount &&
4546          "Exit condition must compare with the trip count");
4547 #endif
4548 }
4549 
4550 void CanonicalLoopInfo::invalidate() {
4551   Header = nullptr;
4552   Cond = nullptr;
4553   Latch = nullptr;
4554   Exit = nullptr;
4555 }
4556