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