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   if (!updateToLocation(Loc))
1068     return Loc.IP;
1069 
1070   auto FiniCBWrapper = [&](InsertPointTy IP) {
1071     if (IP.getBlock()->end() != IP.getPoint())
1072       return FiniCB(IP);
1073     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1074     // will fail because that function requires the Finalization Basic Block to
1075     // have a terminator, which is already removed by EmitOMPRegionBody.
1076     // IP is currently at cancelation block.
1077     // We need to backtrack to the condition block to fetch
1078     // the exit block and create a branch from cancelation
1079     // to exit block.
1080     IRBuilder<>::InsertPointGuard IPG(Builder);
1081     Builder.restoreIP(IP);
1082     auto *CaseBB = IP.getBlock()->getSinglePredecessor();
1083     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1084     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1085     Instruction *I = Builder.CreateBr(ExitBB);
1086     IP = InsertPointTy(I->getParent(), I->getIterator());
1087     return FiniCB(IP);
1088   };
1089 
1090   FinalizationStack.push_back({FiniCBWrapper, OMPD_sections, IsCancellable});
1091 
1092   // Each section is emitted as a switch case
1093   // Each finalization callback is handled from clang.EmitOMPSectionDirective()
1094   // -> OMP.createSection() which generates the IR for each section
1095   // Iterate through all sections and emit a switch construct:
1096   // switch (IV) {
1097   //   case 0:
1098   //     <SectionStmt[0]>;
1099   //     break;
1100   // ...
1101   //   case <NumSection> - 1:
1102   //     <SectionStmt[<NumSection> - 1]>;
1103   //     break;
1104   // }
1105   // ...
1106   // section_loop.after:
1107   // <FiniCB>;
1108   auto LoopBodyGenCB = [&](InsertPointTy CodeGenIP, Value *IndVar) {
1109     auto *CurFn = CodeGenIP.getBlock()->getParent();
1110     auto *ForIncBB = CodeGenIP.getBlock()->getSingleSuccessor();
1111     auto *ForExitBB = CodeGenIP.getBlock()
1112                           ->getSinglePredecessor()
1113                           ->getTerminator()
1114                           ->getSuccessor(1);
1115     SwitchInst *SwitchStmt = Builder.CreateSwitch(IndVar, ForIncBB);
1116     Builder.restoreIP(CodeGenIP);
1117     unsigned CaseNumber = 0;
1118     for (auto SectionCB : SectionCBs) {
1119       auto *CaseBB = BasicBlock::Create(M.getContext(),
1120                                         "omp_section_loop.body.case", CurFn);
1121       SwitchStmt->addCase(Builder.getInt32(CaseNumber), CaseBB);
1122       Builder.SetInsertPoint(CaseBB);
1123       SectionCB(InsertPointTy(), Builder.saveIP(), *ForExitBB);
1124       CaseNumber++;
1125     }
1126     // remove the existing terminator from body BB since there can be no
1127     // terminators after switch/case
1128     CodeGenIP.getBlock()->getTerminator()->eraseFromParent();
1129   };
1130   // Loop body ends here
1131   // LowerBound, UpperBound, and STride for createCanonicalLoop
1132   Type *I32Ty = Type::getInt32Ty(M.getContext());
1133   Value *LB = ConstantInt::get(I32Ty, 0);
1134   Value *UB = ConstantInt::get(I32Ty, SectionCBs.size());
1135   Value *ST = ConstantInt::get(I32Ty, 1);
1136   llvm::CanonicalLoopInfo *LoopInfo = createCanonicalLoop(
1137       Loc, LoopBodyGenCB, LB, UB, ST, true, false, AllocaIP, "section_loop");
1138   Builder.SetInsertPoint(AllocaIP.getBlock()->getTerminator());
1139   AllocaIP = Builder.saveIP();
1140   InsertPointTy AfterIP =
1141       applyStaticWorkshareLoop(Loc.DL, LoopInfo, AllocaIP, !IsNowait);
1142   BasicBlock *LoopAfterBB = AfterIP.getBlock();
1143   Instruction *SplitPos = LoopAfterBB->getTerminator();
1144   if (!isa_and_nonnull<BranchInst>(SplitPos))
1145     SplitPos = new UnreachableInst(Builder.getContext(), LoopAfterBB);
1146   // ExitBB after LoopAfterBB because LoopAfterBB is used for FinalizationCB,
1147   // which requires a BB with branch
1148   BasicBlock *ExitBB =
1149       LoopAfterBB->splitBasicBlock(SplitPos, "omp_sections.end");
1150   SplitPos->eraseFromParent();
1151 
1152   // Apply the finalization callback in LoopAfterBB
1153   auto FiniInfo = FinalizationStack.pop_back_val();
1154   assert(FiniInfo.DK == OMPD_sections &&
1155          "Unexpected finalization stack state!");
1156   Builder.SetInsertPoint(LoopAfterBB->getTerminator());
1157   FiniInfo.FiniCB(Builder.saveIP());
1158   Builder.SetInsertPoint(ExitBB);
1159 
1160   return Builder.saveIP();
1161 }
1162 
1163 OpenMPIRBuilder::InsertPointTy
1164 OpenMPIRBuilder::createSection(const LocationDescription &Loc,
1165                                BodyGenCallbackTy BodyGenCB,
1166                                FinalizeCallbackTy FiniCB) {
1167   if (!updateToLocation(Loc))
1168     return Loc.IP;
1169 
1170   auto FiniCBWrapper = [&](InsertPointTy IP) {
1171     if (IP.getBlock()->end() != IP.getPoint())
1172       return FiniCB(IP);
1173     // This must be done otherwise any nested constructs using FinalizeOMPRegion
1174     // will fail because that function requires the Finalization Basic Block to
1175     // have a terminator, which is already removed by EmitOMPRegionBody.
1176     // IP is currently at cancelation block.
1177     // We need to backtrack to the condition block to fetch
1178     // the exit block and create a branch from cancelation
1179     // to exit block.
1180     IRBuilder<>::InsertPointGuard IPG(Builder);
1181     Builder.restoreIP(IP);
1182     auto *CaseBB = Loc.IP.getBlock();
1183     auto *CondBB = CaseBB->getSinglePredecessor()->getSinglePredecessor();
1184     auto *ExitBB = CondBB->getTerminator()->getSuccessor(1);
1185     Instruction *I = Builder.CreateBr(ExitBB);
1186     IP = InsertPointTy(I->getParent(), I->getIterator());
1187     return FiniCB(IP);
1188   };
1189 
1190   Directive OMPD = Directive::OMPD_sections;
1191   // Since we are using Finalization Callback here, HasFinalize
1192   // and IsCancellable have to be true
1193   return EmitOMPInlinedRegion(OMPD, nullptr, nullptr, BodyGenCB, FiniCBWrapper,
1194                               /*Conditional*/ false, /*hasFinalize*/ true,
1195                               /*IsCancellable*/ true);
1196 }
1197 
1198 /// Create a function with a unique name and a "void (i8*, i8*)" signature in
1199 /// the given module and return it.
1200 Function *getFreshReductionFunc(Module &M) {
1201   Type *VoidTy = Type::getVoidTy(M.getContext());
1202   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
1203   auto *FuncTy =
1204       FunctionType::get(VoidTy, {Int8PtrTy, Int8PtrTy}, /* IsVarArg */ false);
1205   return Function::Create(FuncTy, GlobalVariable::InternalLinkage,
1206                           M.getDataLayout().getDefaultGlobalsAddressSpace(),
1207                           ".omp.reduction.func", &M);
1208 }
1209 
1210 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createReductions(
1211     const LocationDescription &Loc, InsertPointTy AllocaIP,
1212     ArrayRef<ReductionInfo> ReductionInfos, bool IsNoWait) {
1213   for (const ReductionInfo &RI : ReductionInfos) {
1214     (void)RI;
1215     assert(RI.Variable && "expected non-null variable");
1216     assert(RI.PrivateVariable && "expected non-null private variable");
1217     assert(RI.ReductionGen && "expected non-null reduction generator callback");
1218     assert(RI.Variable->getType() == RI.PrivateVariable->getType() &&
1219            "expected variables and their private equivalents to have the same "
1220            "type");
1221     assert(RI.Variable->getType()->isPointerTy() &&
1222            "expected variables to be pointers");
1223   }
1224 
1225   if (!updateToLocation(Loc))
1226     return InsertPointTy();
1227 
1228   BasicBlock *InsertBlock = Loc.IP.getBlock();
1229   BasicBlock *ContinuationBlock =
1230       InsertBlock->splitBasicBlock(Loc.IP.getPoint(), "reduce.finalize");
1231   InsertBlock->getTerminator()->eraseFromParent();
1232 
1233   // Create and populate array of type-erased pointers to private reduction
1234   // values.
1235   unsigned NumReductions = ReductionInfos.size();
1236   Type *RedArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumReductions);
1237   Builder.restoreIP(AllocaIP);
1238   Value *RedArray = Builder.CreateAlloca(RedArrayTy, nullptr, "red.array");
1239 
1240   Builder.SetInsertPoint(InsertBlock, InsertBlock->end());
1241 
1242   for (auto En : enumerate(ReductionInfos)) {
1243     unsigned Index = En.index();
1244     const ReductionInfo &RI = En.value();
1245     Value *RedArrayElemPtr = Builder.CreateConstInBoundsGEP2_64(
1246         RedArrayTy, RedArray, 0, Index, "red.array.elem." + Twine(Index));
1247     Value *Casted =
1248         Builder.CreateBitCast(RI.PrivateVariable, Builder.getInt8PtrTy(),
1249                               "private.red.var." + Twine(Index) + ".casted");
1250     Builder.CreateStore(Casted, RedArrayElemPtr);
1251   }
1252 
1253   // Emit a call to the runtime function that orchestrates the reduction.
1254   // Declare the reduction function in the process.
1255   Function *Func = Builder.GetInsertBlock()->getParent();
1256   Module *Module = Func->getParent();
1257   Value *RedArrayPtr =
1258       Builder.CreateBitCast(RedArray, Builder.getInt8PtrTy(), "red.array.ptr");
1259   uint32_t SrcLocStrSize;
1260   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1261   bool CanGenerateAtomic =
1262       llvm::all_of(ReductionInfos, [](const ReductionInfo &RI) {
1263         return RI.AtomicReductionGen;
1264       });
1265   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize,
1266                                   CanGenerateAtomic
1267                                       ? IdentFlag::OMP_IDENT_FLAG_ATOMIC_REDUCE
1268                                       : IdentFlag(0));
1269   Value *ThreadId = getOrCreateThreadID(Ident);
1270   Constant *NumVariables = Builder.getInt32(NumReductions);
1271   const DataLayout &DL = Module->getDataLayout();
1272   unsigned RedArrayByteSize = DL.getTypeStoreSize(RedArrayTy);
1273   Constant *RedArraySize = Builder.getInt64(RedArrayByteSize);
1274   Function *ReductionFunc = getFreshReductionFunc(*Module);
1275   Value *Lock = getOMPCriticalRegionLock(".reduction");
1276   Function *ReduceFunc = getOrCreateRuntimeFunctionPtr(
1277       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_reduce_nowait
1278                : RuntimeFunction::OMPRTL___kmpc_reduce);
1279   CallInst *ReduceCall =
1280       Builder.CreateCall(ReduceFunc,
1281                          {Ident, ThreadId, NumVariables, RedArraySize,
1282                           RedArrayPtr, ReductionFunc, Lock},
1283                          "reduce");
1284 
1285   // Create final reduction entry blocks for the atomic and non-atomic case.
1286   // Emit IR that dispatches control flow to one of the blocks based on the
1287   // reduction supporting the atomic mode.
1288   BasicBlock *NonAtomicRedBlock =
1289       BasicBlock::Create(Module->getContext(), "reduce.switch.nonatomic", Func);
1290   BasicBlock *AtomicRedBlock =
1291       BasicBlock::Create(Module->getContext(), "reduce.switch.atomic", Func);
1292   SwitchInst *Switch =
1293       Builder.CreateSwitch(ReduceCall, ContinuationBlock, /* NumCases */ 2);
1294   Switch->addCase(Builder.getInt32(1), NonAtomicRedBlock);
1295   Switch->addCase(Builder.getInt32(2), AtomicRedBlock);
1296 
1297   // Populate the non-atomic reduction using the elementwise reduction function.
1298   // This loads the elements from the global and private variables and reduces
1299   // them before storing back the result to the global variable.
1300   Builder.SetInsertPoint(NonAtomicRedBlock);
1301   for (auto En : enumerate(ReductionInfos)) {
1302     const ReductionInfo &RI = En.value();
1303     Type *ValueType = RI.ElementType;
1304     Value *RedValue = Builder.CreateLoad(ValueType, RI.Variable,
1305                                          "red.value." + Twine(En.index()));
1306     Value *PrivateRedValue =
1307         Builder.CreateLoad(ValueType, RI.PrivateVariable,
1308                            "red.private.value." + Twine(En.index()));
1309     Value *Reduced;
1310     Builder.restoreIP(
1311         RI.ReductionGen(Builder.saveIP(), RedValue, PrivateRedValue, Reduced));
1312     if (!Builder.GetInsertBlock())
1313       return InsertPointTy();
1314     Builder.CreateStore(Reduced, RI.Variable);
1315   }
1316   Function *EndReduceFunc = getOrCreateRuntimeFunctionPtr(
1317       IsNoWait ? RuntimeFunction::OMPRTL___kmpc_end_reduce_nowait
1318                : RuntimeFunction::OMPRTL___kmpc_end_reduce);
1319   Builder.CreateCall(EndReduceFunc, {Ident, ThreadId, Lock});
1320   Builder.CreateBr(ContinuationBlock);
1321 
1322   // Populate the atomic reduction using the atomic elementwise reduction
1323   // function. There are no loads/stores here because they will be happening
1324   // inside the atomic elementwise reduction.
1325   Builder.SetInsertPoint(AtomicRedBlock);
1326   if (CanGenerateAtomic) {
1327     for (const ReductionInfo &RI : ReductionInfos) {
1328       Builder.restoreIP(RI.AtomicReductionGen(Builder.saveIP(), RI.ElementType,
1329                                               RI.Variable, RI.PrivateVariable));
1330       if (!Builder.GetInsertBlock())
1331         return InsertPointTy();
1332     }
1333     Builder.CreateBr(ContinuationBlock);
1334   } else {
1335     Builder.CreateUnreachable();
1336   }
1337 
1338   // Populate the outlined reduction function using the elementwise reduction
1339   // function. Partial values are extracted from the type-erased array of
1340   // pointers to private variables.
1341   BasicBlock *ReductionFuncBlock =
1342       BasicBlock::Create(Module->getContext(), "", ReductionFunc);
1343   Builder.SetInsertPoint(ReductionFuncBlock);
1344   Value *LHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(0),
1345                                              RedArrayTy->getPointerTo());
1346   Value *RHSArrayPtr = Builder.CreateBitCast(ReductionFunc->getArg(1),
1347                                              RedArrayTy->getPointerTo());
1348   for (auto En : enumerate(ReductionInfos)) {
1349     const ReductionInfo &RI = En.value();
1350     Value *LHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1351         RedArrayTy, LHSArrayPtr, 0, En.index());
1352     Value *LHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), LHSI8PtrPtr);
1353     Value *LHSPtr = Builder.CreateBitCast(LHSI8Ptr, RI.Variable->getType());
1354     Value *LHS = Builder.CreateLoad(RI.ElementType, LHSPtr);
1355     Value *RHSI8PtrPtr = Builder.CreateConstInBoundsGEP2_64(
1356         RedArrayTy, RHSArrayPtr, 0, En.index());
1357     Value *RHSI8Ptr = Builder.CreateLoad(Builder.getInt8PtrTy(), RHSI8PtrPtr);
1358     Value *RHSPtr =
1359         Builder.CreateBitCast(RHSI8Ptr, RI.PrivateVariable->getType());
1360     Value *RHS = Builder.CreateLoad(RI.ElementType, RHSPtr);
1361     Value *Reduced;
1362     Builder.restoreIP(RI.ReductionGen(Builder.saveIP(), LHS, RHS, Reduced));
1363     if (!Builder.GetInsertBlock())
1364       return InsertPointTy();
1365     Builder.CreateStore(Reduced, LHSPtr);
1366   }
1367   Builder.CreateRetVoid();
1368 
1369   Builder.SetInsertPoint(ContinuationBlock);
1370   return Builder.saveIP();
1371 }
1372 
1373 OpenMPIRBuilder::InsertPointTy
1374 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
1375                               BodyGenCallbackTy BodyGenCB,
1376                               FinalizeCallbackTy FiniCB) {
1377 
1378   if (!updateToLocation(Loc))
1379     return Loc.IP;
1380 
1381   Directive OMPD = Directive::OMPD_master;
1382   uint32_t SrcLocStrSize;
1383   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1384   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1385   Value *ThreadId = getOrCreateThreadID(Ident);
1386   Value *Args[] = {Ident, ThreadId};
1387 
1388   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
1389   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1390 
1391   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
1392   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1393 
1394   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1395                               /*Conditional*/ true, /*hasFinalize*/ true);
1396 }
1397 
1398 OpenMPIRBuilder::InsertPointTy
1399 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
1400                               BodyGenCallbackTy BodyGenCB,
1401                               FinalizeCallbackTy FiniCB, Value *Filter) {
1402   if (!updateToLocation(Loc))
1403     return Loc.IP;
1404 
1405   Directive OMPD = Directive::OMPD_masked;
1406   uint32_t SrcLocStrSize;
1407   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
1408   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1409   Value *ThreadId = getOrCreateThreadID(Ident);
1410   Value *Args[] = {Ident, ThreadId, Filter};
1411   Value *ArgsEnd[] = {Ident, ThreadId};
1412 
1413   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
1414   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1415 
1416   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
1417   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
1418 
1419   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1420                               /*Conditional*/ true, /*hasFinalize*/ true);
1421 }
1422 
1423 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
1424     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
1425     BasicBlock *PostInsertBefore, const Twine &Name) {
1426   Module *M = F->getParent();
1427   LLVMContext &Ctx = M->getContext();
1428   Type *IndVarTy = TripCount->getType();
1429 
1430   // Create the basic block structure.
1431   BasicBlock *Preheader =
1432       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
1433   BasicBlock *Header =
1434       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
1435   BasicBlock *Cond =
1436       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
1437   BasicBlock *Body =
1438       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
1439   BasicBlock *Latch =
1440       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
1441   BasicBlock *Exit =
1442       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
1443   BasicBlock *After =
1444       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
1445 
1446   // Use specified DebugLoc for new instructions.
1447   Builder.SetCurrentDebugLocation(DL);
1448 
1449   Builder.SetInsertPoint(Preheader);
1450   Builder.CreateBr(Header);
1451 
1452   Builder.SetInsertPoint(Header);
1453   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
1454   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
1455   Builder.CreateBr(Cond);
1456 
1457   Builder.SetInsertPoint(Cond);
1458   Value *Cmp =
1459       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
1460   Builder.CreateCondBr(Cmp, Body, Exit);
1461 
1462   Builder.SetInsertPoint(Body);
1463   Builder.CreateBr(Latch);
1464 
1465   Builder.SetInsertPoint(Latch);
1466   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
1467                                   "omp_" + Name + ".next", /*HasNUW=*/true);
1468   Builder.CreateBr(Header);
1469   IndVarPHI->addIncoming(Next, Latch);
1470 
1471   Builder.SetInsertPoint(Exit);
1472   Builder.CreateBr(After);
1473 
1474   // Remember and return the canonical control flow.
1475   LoopInfos.emplace_front();
1476   CanonicalLoopInfo *CL = &LoopInfos.front();
1477 
1478   CL->Header = Header;
1479   CL->Cond = Cond;
1480   CL->Latch = Latch;
1481   CL->Exit = Exit;
1482 
1483 #ifndef NDEBUG
1484   CL->assertOK();
1485 #endif
1486   return CL;
1487 }
1488 
1489 CanonicalLoopInfo *
1490 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
1491                                      LoopBodyGenCallbackTy BodyGenCB,
1492                                      Value *TripCount, const Twine &Name) {
1493   BasicBlock *BB = Loc.IP.getBlock();
1494   BasicBlock *NextBB = BB->getNextNode();
1495 
1496   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
1497                                              NextBB, NextBB, Name);
1498   BasicBlock *After = CL->getAfter();
1499 
1500   // If location is not set, don't connect the loop.
1501   if (updateToLocation(Loc)) {
1502     // Split the loop at the insertion point: Branch to the preheader and move
1503     // every following instruction to after the loop (the After BB). Also, the
1504     // new successor is the loop's after block.
1505     spliceBB(Builder, After, /*CreateBranch=*/false);
1506     Builder.CreateBr(CL->getPreheader());
1507   }
1508 
1509   // Emit the body content. We do it after connecting the loop to the CFG to
1510   // avoid that the callback encounters degenerate BBs.
1511   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
1512 
1513 #ifndef NDEBUG
1514   CL->assertOK();
1515 #endif
1516   return CL;
1517 }
1518 
1519 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
1520     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
1521     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
1522     InsertPointTy ComputeIP, const Twine &Name) {
1523 
1524   // Consider the following difficulties (assuming 8-bit signed integers):
1525   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
1526   //      DO I = 1, 100, 50
1527   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
1528   //      DO I = 100, 0, -128
1529 
1530   // Start, Stop and Step must be of the same integer type.
1531   auto *IndVarTy = cast<IntegerType>(Start->getType());
1532   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
1533   assert(IndVarTy == Step->getType() && "Step type mismatch");
1534 
1535   LocationDescription ComputeLoc =
1536       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
1537   updateToLocation(ComputeLoc);
1538 
1539   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
1540   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
1541 
1542   // Like Step, but always positive.
1543   Value *Incr = Step;
1544 
1545   // Distance between Start and Stop; always positive.
1546   Value *Span;
1547 
1548   // Condition whether there are no iterations are executed at all, e.g. because
1549   // UB < LB.
1550   Value *ZeroCmp;
1551 
1552   if (IsSigned) {
1553     // Ensure that increment is positive. If not, negate and invert LB and UB.
1554     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
1555     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
1556     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
1557     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
1558     Span = Builder.CreateSub(UB, LB, "", false, true);
1559     ZeroCmp = Builder.CreateICmp(
1560         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
1561   } else {
1562     Span = Builder.CreateSub(Stop, Start, "", true);
1563     ZeroCmp = Builder.CreateICmp(
1564         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
1565   }
1566 
1567   Value *CountIfLooping;
1568   if (InclusiveStop) {
1569     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
1570   } else {
1571     // Avoid incrementing past stop since it could overflow.
1572     Value *CountIfTwo = Builder.CreateAdd(
1573         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
1574     Value *OneCmp = Builder.CreateICmp(
1575         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Span, Incr);
1576     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
1577   }
1578   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
1579                                           "omp_" + Name + ".tripcount");
1580 
1581   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
1582     Builder.restoreIP(CodeGenIP);
1583     Value *Span = Builder.CreateMul(IV, Step);
1584     Value *IndVar = Builder.CreateAdd(Span, Start);
1585     BodyGenCB(Builder.saveIP(), IndVar);
1586   };
1587   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
1588   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
1589 }
1590 
1591 // Returns an LLVM function to call for initializing loop bounds using OpenMP
1592 // static scheduling depending on `type`. Only i32 and i64 are supported by the
1593 // runtime. Always interpret integers as unsigned similarly to
1594 // CanonicalLoopInfo.
1595 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
1596                                                   OpenMPIRBuilder &OMPBuilder) {
1597   unsigned Bitwidth = Ty->getIntegerBitWidth();
1598   if (Bitwidth == 32)
1599     return OMPBuilder.getOrCreateRuntimeFunction(
1600         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
1601   if (Bitwidth == 64)
1602     return OMPBuilder.getOrCreateRuntimeFunction(
1603         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
1604   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1605 }
1606 
1607 OpenMPIRBuilder::InsertPointTy
1608 OpenMPIRBuilder::applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
1609                                           InsertPointTy AllocaIP,
1610                                           bool NeedsBarrier) {
1611   assert(CLI->isValid() && "Requires a valid canonical loop");
1612   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
1613          "Require dedicated allocate IP");
1614 
1615   // Set up the source location value for OpenMP runtime.
1616   Builder.restoreIP(CLI->getPreheaderIP());
1617   Builder.SetCurrentDebugLocation(DL);
1618 
1619   uint32_t SrcLocStrSize;
1620   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
1621   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1622 
1623   // Declare useful OpenMP runtime functions.
1624   Value *IV = CLI->getIndVar();
1625   Type *IVTy = IV->getType();
1626   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
1627   FunctionCallee StaticFini =
1628       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
1629 
1630   // Allocate space for computed loop bounds as expected by the "init" function.
1631   Builder.restoreIP(AllocaIP);
1632   Type *I32Type = Type::getInt32Ty(M.getContext());
1633   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1634   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1635   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1636   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1637 
1638   // At the end of the preheader, prepare for calling the "init" function by
1639   // storing the current loop bounds into the allocated space. A canonical loop
1640   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1641   // and produces an inclusive upper bound.
1642   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
1643   Constant *Zero = ConstantInt::get(IVTy, 0);
1644   Constant *One = ConstantInt::get(IVTy, 1);
1645   Builder.CreateStore(Zero, PLowerBound);
1646   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
1647   Builder.CreateStore(UpperBound, PUpperBound);
1648   Builder.CreateStore(One, PStride);
1649 
1650   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1651 
1652   Constant *SchedulingType =
1653       ConstantInt::get(I32Type, static_cast<int>(OMPScheduleType::Static));
1654 
1655   // Call the "init" function and update the trip count of the loop with the
1656   // value it produced.
1657   Builder.CreateCall(StaticInit,
1658                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
1659                       PUpperBound, PStride, One, Zero});
1660   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
1661   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
1662   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
1663   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
1664   CLI->setTripCount(TripCount);
1665 
1666   // Update all uses of the induction variable except the one in the condition
1667   // block that compares it with the actual upper bound, and the increment in
1668   // the latch block.
1669 
1670   CLI->mapIndVar([&](Instruction *OldIV) -> Value * {
1671     Builder.SetInsertPoint(CLI->getBody(),
1672                            CLI->getBody()->getFirstInsertionPt());
1673     Builder.SetCurrentDebugLocation(DL);
1674     return Builder.CreateAdd(OldIV, LowerBound);
1675   });
1676 
1677   // In the "exit" block, call the "fini" function.
1678   Builder.SetInsertPoint(CLI->getExit(),
1679                          CLI->getExit()->getTerminator()->getIterator());
1680   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
1681 
1682   // Add the barrier if requested.
1683   if (NeedsBarrier)
1684     createBarrier(LocationDescription(Builder.saveIP(), DL),
1685                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
1686                   /* CheckCancelFlag */ false);
1687 
1688   InsertPointTy AfterIP = CLI->getAfterIP();
1689   CLI->invalidate();
1690 
1691   return AfterIP;
1692 }
1693 
1694 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyStaticChunkedWorkshareLoop(
1695     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
1696     bool NeedsBarrier, Value *ChunkSize) {
1697   assert(CLI->isValid() && "Requires a valid canonical loop");
1698   assert(ChunkSize && "Chunk size is required");
1699 
1700   LLVMContext &Ctx = CLI->getFunction()->getContext();
1701   Value *IV = CLI->getIndVar();
1702   Value *OrigTripCount = CLI->getTripCount();
1703   Type *IVTy = IV->getType();
1704   assert(IVTy->getIntegerBitWidth() <= 64 &&
1705          "Max supported tripcount bitwidth is 64 bits");
1706   Type *InternalIVTy = IVTy->getIntegerBitWidth() <= 32 ? Type::getInt32Ty(Ctx)
1707                                                         : Type::getInt64Ty(Ctx);
1708   Type *I32Type = Type::getInt32Ty(M.getContext());
1709   Constant *Zero = ConstantInt::get(InternalIVTy, 0);
1710   Constant *One = ConstantInt::get(InternalIVTy, 1);
1711 
1712   // Declare useful OpenMP runtime functions.
1713   FunctionCallee StaticInit =
1714       getKmpcForStaticInitForType(InternalIVTy, M, *this);
1715   FunctionCallee StaticFini =
1716       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
1717 
1718   // Allocate space for computed loop bounds as expected by the "init" function.
1719   Builder.restoreIP(AllocaIP);
1720   Builder.SetCurrentDebugLocation(DL);
1721   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1722   Value *PLowerBound =
1723       Builder.CreateAlloca(InternalIVTy, nullptr, "p.lowerbound");
1724   Value *PUpperBound =
1725       Builder.CreateAlloca(InternalIVTy, nullptr, "p.upperbound");
1726   Value *PStride = Builder.CreateAlloca(InternalIVTy, nullptr, "p.stride");
1727 
1728   // Set up the source location value for the OpenMP runtime.
1729   Builder.restoreIP(CLI->getPreheaderIP());
1730   Builder.SetCurrentDebugLocation(DL);
1731 
1732   // TODO: Detect overflow in ubsan or max-out with current tripcount.
1733   Value *CastedChunkSize =
1734       Builder.CreateZExtOrTrunc(ChunkSize, InternalIVTy, "chunksize");
1735   Value *CastedTripCount =
1736       Builder.CreateZExt(OrigTripCount, InternalIVTy, "tripcount");
1737 
1738   Constant *SchedulingType = ConstantInt::get(
1739       I32Type, static_cast<int>(OMPScheduleType::StaticChunked));
1740   Builder.CreateStore(Zero, PLowerBound);
1741   Value *OrigUpperBound = Builder.CreateSub(CastedTripCount, One);
1742   Builder.CreateStore(OrigUpperBound, PUpperBound);
1743   Builder.CreateStore(One, PStride);
1744 
1745   // Call the "init" function and update the trip count of the loop with the
1746   // value it produced.
1747   uint32_t SrcLocStrSize;
1748   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
1749   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1750   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1751   Builder.CreateCall(StaticInit,
1752                      {/*loc=*/SrcLoc, /*global_tid=*/ThreadNum,
1753                       /*schedtype=*/SchedulingType, /*plastiter=*/PLastIter,
1754                       /*plower=*/PLowerBound, /*pupper=*/PUpperBound,
1755                       /*pstride=*/PStride, /*incr=*/One,
1756                       /*chunk=*/CastedChunkSize});
1757 
1758   // Load values written by the "init" function.
1759   Value *FirstChunkStart =
1760       Builder.CreateLoad(InternalIVTy, PLowerBound, "omp_firstchunk.lb");
1761   Value *FirstChunkStop =
1762       Builder.CreateLoad(InternalIVTy, PUpperBound, "omp_firstchunk.ub");
1763   Value *FirstChunkEnd = Builder.CreateAdd(FirstChunkStop, One);
1764   Value *ChunkRange =
1765       Builder.CreateSub(FirstChunkEnd, FirstChunkStart, "omp_chunk.range");
1766   Value *NextChunkStride =
1767       Builder.CreateLoad(InternalIVTy, PStride, "omp_dispatch.stride");
1768 
1769   // Create outer "dispatch" loop for enumerating the chunks.
1770   BasicBlock *DispatchEnter = splitBB(Builder, true);
1771   Value *DispatchCounter;
1772   CanonicalLoopInfo *DispatchCLI = createCanonicalLoop(
1773       {Builder.saveIP(), DL},
1774       [&](InsertPointTy BodyIP, Value *Counter) { DispatchCounter = Counter; },
1775       FirstChunkStart, CastedTripCount, NextChunkStride,
1776       /*IsSigned=*/false, /*InclusiveStop=*/false, /*ComputeIP=*/{},
1777       "dispatch");
1778 
1779   // Remember the BasicBlocks of the dispatch loop we need, then invalidate to
1780   // not have to preserve the canonical invariant.
1781   BasicBlock *DispatchBody = DispatchCLI->getBody();
1782   BasicBlock *DispatchLatch = DispatchCLI->getLatch();
1783   BasicBlock *DispatchExit = DispatchCLI->getExit();
1784   BasicBlock *DispatchAfter = DispatchCLI->getAfter();
1785   DispatchCLI->invalidate();
1786 
1787   // Rewire the original loop to become the chunk loop inside the dispatch loop.
1788   redirectTo(DispatchAfter, CLI->getAfter(), DL);
1789   redirectTo(CLI->getExit(), DispatchLatch, DL);
1790   redirectTo(DispatchBody, DispatchEnter, DL);
1791 
1792   // Prepare the prolog of the chunk loop.
1793   Builder.restoreIP(CLI->getPreheaderIP());
1794   Builder.SetCurrentDebugLocation(DL);
1795 
1796   // Compute the number of iterations of the chunk loop.
1797   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
1798   Value *ChunkEnd = Builder.CreateAdd(DispatchCounter, ChunkRange);
1799   Value *IsLastChunk =
1800       Builder.CreateICmpUGE(ChunkEnd, CastedTripCount, "omp_chunk.is_last");
1801   Value *CountUntilOrigTripCount =
1802       Builder.CreateSub(CastedTripCount, DispatchCounter);
1803   Value *ChunkTripCount = Builder.CreateSelect(
1804       IsLastChunk, CountUntilOrigTripCount, ChunkRange, "omp_chunk.tripcount");
1805   Value *BackcastedChunkTC =
1806       Builder.CreateTrunc(ChunkTripCount, IVTy, "omp_chunk.tripcount.trunc");
1807   CLI->setTripCount(BackcastedChunkTC);
1808 
1809   // Update all uses of the induction variable except the one in the condition
1810   // block that compares it with the actual upper bound, and the increment in
1811   // the latch block.
1812   Value *BackcastedDispatchCounter =
1813       Builder.CreateTrunc(DispatchCounter, IVTy, "omp_dispatch.iv.trunc");
1814   CLI->mapIndVar([&](Instruction *) -> Value * {
1815     Builder.restoreIP(CLI->getBodyIP());
1816     return Builder.CreateAdd(IV, BackcastedDispatchCounter);
1817   });
1818 
1819   // In the "exit" block, call the "fini" function.
1820   Builder.SetInsertPoint(DispatchExit, DispatchExit->getFirstInsertionPt());
1821   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
1822 
1823   // Add the barrier if requested.
1824   if (NeedsBarrier)
1825     createBarrier(LocationDescription(Builder.saveIP(), DL), OMPD_for,
1826                   /*ForceSimpleCall=*/false, /*CheckCancelFlag=*/false);
1827 
1828 #ifndef NDEBUG
1829   // Even though we currently do not support applying additional methods to it,
1830   // the chunk loop should remain a canonical loop.
1831   CLI->assertOK();
1832 #endif
1833 
1834   return {DispatchAfter, DispatchAfter->getFirstInsertionPt()};
1835 }
1836 
1837 OpenMPIRBuilder::InsertPointTy
1838 OpenMPIRBuilder::applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
1839                                     InsertPointTy AllocaIP, bool NeedsBarrier,
1840                                     llvm::omp::ScheduleKind SchedKind,
1841                                     llvm::Value *ChunkSize) {
1842   switch (SchedKind) {
1843   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Default:
1844     assert(!ChunkSize && "No chunk size with default schedule (which for clang "
1845                          "is static non-chunked)");
1846     LLVM_FALLTHROUGH;
1847   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Static:
1848     if (ChunkSize)
1849       return applyStaticChunkedWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier,
1850                                              ChunkSize);
1851     return applyStaticWorkshareLoop(DL, CLI, AllocaIP, NeedsBarrier);
1852   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Auto:
1853     assert(!ChunkSize && "Chunk size with auto scheduling not user-defined");
1854     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP, OMPScheduleType::Auto,
1855                                      NeedsBarrier, nullptr);
1856   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Dynamic:
1857     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP,
1858                                      OMPScheduleType::DynamicChunked,
1859                                      NeedsBarrier, ChunkSize);
1860   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Guided:
1861     return applyDynamicWorkshareLoop(DL, CLI, AllocaIP,
1862                                      OMPScheduleType::GuidedChunked,
1863                                      NeedsBarrier, ChunkSize);
1864   case llvm::omp::ScheduleKind::OMP_SCHEDULE_Runtime:
1865     assert(!ChunkSize &&
1866            "Chunk size with runtime scheduling implied to be one");
1867     return applyDynamicWorkshareLoop(
1868         DL, CLI, AllocaIP, OMPScheduleType::Runtime, NeedsBarrier, nullptr);
1869   }
1870 
1871   llvm_unreachable("Unknown/unimplemented schedule kind");
1872 }
1873 
1874 /// Returns an LLVM function to call for initializing loop bounds using OpenMP
1875 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
1876 /// the runtime. Always interpret integers as unsigned similarly to
1877 /// CanonicalLoopInfo.
1878 static FunctionCallee
1879 getKmpcForDynamicInitForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
1880   unsigned Bitwidth = Ty->getIntegerBitWidth();
1881   if (Bitwidth == 32)
1882     return OMPBuilder.getOrCreateRuntimeFunction(
1883         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_4u);
1884   if (Bitwidth == 64)
1885     return OMPBuilder.getOrCreateRuntimeFunction(
1886         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_init_8u);
1887   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1888 }
1889 
1890 /// Returns an LLVM function to call for updating the next loop using OpenMP
1891 /// dynamic scheduling depending on `type`. Only i32 and i64 are supported by
1892 /// the runtime. Always interpret integers as unsigned similarly to
1893 /// CanonicalLoopInfo.
1894 static FunctionCallee
1895 getKmpcForDynamicNextForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
1896   unsigned Bitwidth = Ty->getIntegerBitWidth();
1897   if (Bitwidth == 32)
1898     return OMPBuilder.getOrCreateRuntimeFunction(
1899         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_4u);
1900   if (Bitwidth == 64)
1901     return OMPBuilder.getOrCreateRuntimeFunction(
1902         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_next_8u);
1903   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1904 }
1905 
1906 /// Returns an LLVM function to call for finalizing the dynamic loop using
1907 /// depending on `type`. Only i32 and i64 are supported by the runtime. Always
1908 /// interpret integers as unsigned similarly to CanonicalLoopInfo.
1909 static FunctionCallee
1910 getKmpcForDynamicFiniForType(Type *Ty, Module &M, OpenMPIRBuilder &OMPBuilder) {
1911   unsigned Bitwidth = Ty->getIntegerBitWidth();
1912   if (Bitwidth == 32)
1913     return OMPBuilder.getOrCreateRuntimeFunction(
1914         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_4u);
1915   if (Bitwidth == 64)
1916     return OMPBuilder.getOrCreateRuntimeFunction(
1917         M, omp::RuntimeFunction::OMPRTL___kmpc_dispatch_fini_8u);
1918   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1919 }
1920 
1921 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
1922     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
1923     OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk, bool Ordered) {
1924   assert(CLI->isValid() && "Requires a valid canonical loop");
1925   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
1926          "Require dedicated allocate IP");
1927 
1928   // Set up the source location value for OpenMP runtime.
1929   Builder.SetCurrentDebugLocation(DL);
1930 
1931   uint32_t SrcLocStrSize;
1932   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
1933   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1934 
1935   // Declare useful OpenMP runtime functions.
1936   Value *IV = CLI->getIndVar();
1937   Type *IVTy = IV->getType();
1938   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
1939   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
1940 
1941   // Allocate space for computed loop bounds as expected by the "init" function.
1942   Builder.restoreIP(AllocaIP);
1943   Type *I32Type = Type::getInt32Ty(M.getContext());
1944   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1945   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1946   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1947   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1948 
1949   // At the end of the preheader, prepare for calling the "init" function by
1950   // storing the current loop bounds into the allocated space. A canonical loop
1951   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1952   // and produces an inclusive upper bound.
1953   BasicBlock *PreHeader = CLI->getPreheader();
1954   Builder.SetInsertPoint(PreHeader->getTerminator());
1955   Constant *One = ConstantInt::get(IVTy, 1);
1956   Builder.CreateStore(One, PLowerBound);
1957   Value *UpperBound = CLI->getTripCount();
1958   Builder.CreateStore(UpperBound, PUpperBound);
1959   Builder.CreateStore(One, PStride);
1960 
1961   BasicBlock *Header = CLI->getHeader();
1962   BasicBlock *Exit = CLI->getExit();
1963   BasicBlock *Cond = CLI->getCond();
1964   BasicBlock *Latch = CLI->getLatch();
1965   InsertPointTy AfterIP = CLI->getAfterIP();
1966 
1967   // The CLI will be "broken" in the code below, as the loop is no longer
1968   // a valid canonical loop.
1969 
1970   if (!Chunk)
1971     Chunk = One;
1972 
1973   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1974 
1975   Constant *SchedulingType =
1976       ConstantInt::get(I32Type, static_cast<int>(SchedType));
1977 
1978   // Call the "init" function.
1979   Builder.CreateCall(DynamicInit,
1980                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
1981                       UpperBound, /* step */ One, Chunk});
1982 
1983   // An outer loop around the existing one.
1984   BasicBlock *OuterCond = BasicBlock::Create(
1985       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
1986       PreHeader->getParent());
1987   // This needs to be 32-bit always, so can't use the IVTy Zero above.
1988   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
1989   Value *Res =
1990       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
1991                                        PLowerBound, PUpperBound, PStride});
1992   Constant *Zero32 = ConstantInt::get(I32Type, 0);
1993   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
1994   Value *LowerBound =
1995       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
1996   Builder.CreateCondBr(MoreWork, Header, Exit);
1997 
1998   // Change PHI-node in loop header to use outer cond rather than preheader,
1999   // and set IV to the LowerBound.
2000   Instruction *Phi = &Header->front();
2001   auto *PI = cast<PHINode>(Phi);
2002   PI->setIncomingBlock(0, OuterCond);
2003   PI->setIncomingValue(0, LowerBound);
2004 
2005   // Then set the pre-header to jump to the OuterCond
2006   Instruction *Term = PreHeader->getTerminator();
2007   auto *Br = cast<BranchInst>(Term);
2008   Br->setSuccessor(0, OuterCond);
2009 
2010   // Modify the inner condition:
2011   // * Use the UpperBound returned from the DynamicNext call.
2012   // * jump to the loop outer loop when done with one of the inner loops.
2013   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
2014   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
2015   Instruction *Comp = &*Builder.GetInsertPoint();
2016   auto *CI = cast<CmpInst>(Comp);
2017   CI->setOperand(1, UpperBound);
2018   // Redirect the inner exit to branch to outer condition.
2019   Instruction *Branch = &Cond->back();
2020   auto *BI = cast<BranchInst>(Branch);
2021   assert(BI->getSuccessor(1) == Exit);
2022   BI->setSuccessor(1, OuterCond);
2023 
2024   // Call the "fini" function if "ordered" is present in wsloop directive.
2025   if (Ordered) {
2026     Builder.SetInsertPoint(&Latch->back());
2027     FunctionCallee DynamicFini = getKmpcForDynamicFiniForType(IVTy, M, *this);
2028     Builder.CreateCall(DynamicFini, {SrcLoc, ThreadNum});
2029   }
2030 
2031   // Add the barrier if requested.
2032   if (NeedsBarrier) {
2033     Builder.SetInsertPoint(&Exit->back());
2034     createBarrier(LocationDescription(Builder.saveIP(), DL),
2035                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2036                   /* CheckCancelFlag */ false);
2037   }
2038 
2039   CLI->invalidate();
2040   return AfterIP;
2041 }
2042 
2043 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2044 /// after this \p OldTarget will be orphaned.
2045 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
2046                                       BasicBlock *NewTarget, DebugLoc DL) {
2047   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2048     redirectTo(Pred, NewTarget, DL);
2049 }
2050 
2051 /// Determine which blocks in \p BBs are reachable from outside and remove the
2052 /// ones that are not reachable from the function.
2053 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
2054   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2055   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2056     for (Use &U : BB->uses()) {
2057       auto *UseInst = dyn_cast<Instruction>(U.getUser());
2058       if (!UseInst)
2059         continue;
2060       if (BBsToErase.count(UseInst->getParent()))
2061         continue;
2062       return true;
2063     }
2064     return false;
2065   };
2066 
2067   while (true) {
2068     bool Changed = false;
2069     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2070       if (HasRemainingUses(BB)) {
2071         BBsToErase.erase(BB);
2072         Changed = true;
2073       }
2074     }
2075     if (!Changed)
2076       break;
2077   }
2078 
2079   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2080   DeleteDeadBlocks(BBVec);
2081 }
2082 
2083 CanonicalLoopInfo *
2084 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2085                                InsertPointTy ComputeIP) {
2086   assert(Loops.size() >= 1 && "At least one loop required");
2087   size_t NumLoops = Loops.size();
2088 
2089   // Nothing to do if there is already just one loop.
2090   if (NumLoops == 1)
2091     return Loops.front();
2092 
2093   CanonicalLoopInfo *Outermost = Loops.front();
2094   CanonicalLoopInfo *Innermost = Loops.back();
2095   BasicBlock *OrigPreheader = Outermost->getPreheader();
2096   BasicBlock *OrigAfter = Outermost->getAfter();
2097   Function *F = OrigPreheader->getParent();
2098 
2099   // Loop control blocks that may become orphaned later.
2100   SmallVector<BasicBlock *, 12> OldControlBBs;
2101   OldControlBBs.reserve(6 * Loops.size());
2102   for (CanonicalLoopInfo *Loop : Loops)
2103     Loop->collectControlBlocks(OldControlBBs);
2104 
2105   // Setup the IRBuilder for inserting the trip count computation.
2106   Builder.SetCurrentDebugLocation(DL);
2107   if (ComputeIP.isSet())
2108     Builder.restoreIP(ComputeIP);
2109   else
2110     Builder.restoreIP(Outermost->getPreheaderIP());
2111 
2112   // Derive the collapsed' loop trip count.
2113   // TODO: Find common/largest indvar type.
2114   Value *CollapsedTripCount = nullptr;
2115   for (CanonicalLoopInfo *L : Loops) {
2116     assert(L->isValid() &&
2117            "All loops to collapse must be valid canonical loops");
2118     Value *OrigTripCount = L->getTripCount();
2119     if (!CollapsedTripCount) {
2120       CollapsedTripCount = OrigTripCount;
2121       continue;
2122     }
2123 
2124     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2125     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2126                                            {}, /*HasNUW=*/true);
2127   }
2128 
2129   // Create the collapsed loop control flow.
2130   CanonicalLoopInfo *Result =
2131       createLoopSkeleton(DL, CollapsedTripCount, F,
2132                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2133 
2134   // Build the collapsed loop body code.
2135   // Start with deriving the input loop induction variables from the collapsed
2136   // one, using a divmod scheme. To preserve the original loops' order, the
2137   // innermost loop use the least significant bits.
2138   Builder.restoreIP(Result->getBodyIP());
2139 
2140   Value *Leftover = Result->getIndVar();
2141   SmallVector<Value *> NewIndVars;
2142   NewIndVars.resize(NumLoops);
2143   for (int i = NumLoops - 1; i >= 1; --i) {
2144     Value *OrigTripCount = Loops[i]->getTripCount();
2145 
2146     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2147     NewIndVars[i] = NewIndVar;
2148 
2149     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2150   }
2151   // Outermost loop gets all the remaining bits.
2152   NewIndVars[0] = Leftover;
2153 
2154   // Construct the loop body control flow.
2155   // We progressively construct the branch structure following in direction of
2156   // the control flow, from the leading in-between code, the loop nest body, the
2157   // trailing in-between code, and rejoining the collapsed loop's latch.
2158   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2159   // the ContinueBlock is set, continue with that block. If ContinuePred, use
2160   // its predecessors as sources.
2161   BasicBlock *ContinueBlock = Result->getBody();
2162   BasicBlock *ContinuePred = nullptr;
2163   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2164                                                           BasicBlock *NextSrc) {
2165     if (ContinueBlock)
2166       redirectTo(ContinueBlock, Dest, DL);
2167     else
2168       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2169 
2170     ContinueBlock = nullptr;
2171     ContinuePred = NextSrc;
2172   };
2173 
2174   // The code before the nested loop of each level.
2175   // Because we are sinking it into the nest, it will be executed more often
2176   // that the original loop. More sophisticated schemes could keep track of what
2177   // the in-between code is and instantiate it only once per thread.
2178   for (size_t i = 0; i < NumLoops - 1; ++i)
2179     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2180 
2181   // Connect the loop nest body.
2182   ContinueWith(Innermost->getBody(), Innermost->getLatch());
2183 
2184   // The code after the nested loop at each level.
2185   for (size_t i = NumLoops - 1; i > 0; --i)
2186     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2187 
2188   // Connect the finished loop to the collapsed loop latch.
2189   ContinueWith(Result->getLatch(), nullptr);
2190 
2191   // Replace the input loops with the new collapsed loop.
2192   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2193   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2194 
2195   // Replace the input loop indvars with the derived ones.
2196   for (size_t i = 0; i < NumLoops; ++i)
2197     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2198 
2199   // Remove unused parts of the input loops.
2200   removeUnusedBlocksFromParent(OldControlBBs);
2201 
2202   for (CanonicalLoopInfo *L : Loops)
2203     L->invalidate();
2204 
2205 #ifndef NDEBUG
2206   Result->assertOK();
2207 #endif
2208   return Result;
2209 }
2210 
2211 std::vector<CanonicalLoopInfo *>
2212 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2213                            ArrayRef<Value *> TileSizes) {
2214   assert(TileSizes.size() == Loops.size() &&
2215          "Must pass as many tile sizes as there are loops");
2216   int NumLoops = Loops.size();
2217   assert(NumLoops >= 1 && "At least one loop to tile required");
2218 
2219   CanonicalLoopInfo *OutermostLoop = Loops.front();
2220   CanonicalLoopInfo *InnermostLoop = Loops.back();
2221   Function *F = OutermostLoop->getBody()->getParent();
2222   BasicBlock *InnerEnter = InnermostLoop->getBody();
2223   BasicBlock *InnerLatch = InnermostLoop->getLatch();
2224 
2225   // Loop control blocks that may become orphaned later.
2226   SmallVector<BasicBlock *, 12> OldControlBBs;
2227   OldControlBBs.reserve(6 * Loops.size());
2228   for (CanonicalLoopInfo *Loop : Loops)
2229     Loop->collectControlBlocks(OldControlBBs);
2230 
2231   // Collect original trip counts and induction variable to be accessible by
2232   // index. Also, the structure of the original loops is not preserved during
2233   // the construction of the tiled loops, so do it before we scavenge the BBs of
2234   // any original CanonicalLoopInfo.
2235   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2236   for (CanonicalLoopInfo *L : Loops) {
2237     assert(L->isValid() && "All input loops must be valid canonical loops");
2238     OrigTripCounts.push_back(L->getTripCount());
2239     OrigIndVars.push_back(L->getIndVar());
2240   }
2241 
2242   // Collect the code between loop headers. These may contain SSA definitions
2243   // that are used in the loop nest body. To be usable with in the innermost
2244   // body, these BasicBlocks will be sunk into the loop nest body. That is,
2245   // these instructions may be executed more often than before the tiling.
2246   // TODO: It would be sufficient to only sink them into body of the
2247   // corresponding tile loop.
2248   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
2249   for (int i = 0; i < NumLoops - 1; ++i) {
2250     CanonicalLoopInfo *Surrounding = Loops[i];
2251     CanonicalLoopInfo *Nested = Loops[i + 1];
2252 
2253     BasicBlock *EnterBB = Surrounding->getBody();
2254     BasicBlock *ExitBB = Nested->getHeader();
2255     InbetweenCode.emplace_back(EnterBB, ExitBB);
2256   }
2257 
2258   // Compute the trip counts of the floor loops.
2259   Builder.SetCurrentDebugLocation(DL);
2260   Builder.restoreIP(OutermostLoop->getPreheaderIP());
2261   SmallVector<Value *, 4> FloorCount, FloorRems;
2262   for (int i = 0; i < NumLoops; ++i) {
2263     Value *TileSize = TileSizes[i];
2264     Value *OrigTripCount = OrigTripCounts[i];
2265     Type *IVType = OrigTripCount->getType();
2266 
2267     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
2268     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
2269 
2270     // 0 if tripcount divides the tilesize, 1 otherwise.
2271     // 1 means we need an additional iteration for a partial tile.
2272     //
2273     // Unfortunately we cannot just use the roundup-formula
2274     //   (tripcount + tilesize - 1)/tilesize
2275     // because the summation might overflow. We do not want introduce undefined
2276     // behavior when the untiled loop nest did not.
2277     Value *FloorTripOverflow =
2278         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
2279 
2280     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
2281     FloorTripCount =
2282         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
2283                           "omp_floor" + Twine(i) + ".tripcount", true);
2284 
2285     // Remember some values for later use.
2286     FloorCount.push_back(FloorTripCount);
2287     FloorRems.push_back(FloorTripRem);
2288   }
2289 
2290   // Generate the new loop nest, from the outermost to the innermost.
2291   std::vector<CanonicalLoopInfo *> Result;
2292   Result.reserve(NumLoops * 2);
2293 
2294   // The basic block of the surrounding loop that enters the nest generated
2295   // loop.
2296   BasicBlock *Enter = OutermostLoop->getPreheader();
2297 
2298   // The basic block of the surrounding loop where the inner code should
2299   // continue.
2300   BasicBlock *Continue = OutermostLoop->getAfter();
2301 
2302   // Where the next loop basic block should be inserted.
2303   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
2304 
2305   auto EmbeddNewLoop =
2306       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
2307           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
2308     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
2309         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
2310     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
2311     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
2312 
2313     // Setup the position where the next embedded loop connects to this loop.
2314     Enter = EmbeddedLoop->getBody();
2315     Continue = EmbeddedLoop->getLatch();
2316     OutroInsertBefore = EmbeddedLoop->getLatch();
2317     return EmbeddedLoop;
2318   };
2319 
2320   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
2321                                                   const Twine &NameBase) {
2322     for (auto P : enumerate(TripCounts)) {
2323       CanonicalLoopInfo *EmbeddedLoop =
2324           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
2325       Result.push_back(EmbeddedLoop);
2326     }
2327   };
2328 
2329   EmbeddNewLoops(FloorCount, "floor");
2330 
2331   // Within the innermost floor loop, emit the code that computes the tile
2332   // sizes.
2333   Builder.SetInsertPoint(Enter->getTerminator());
2334   SmallVector<Value *, 4> TileCounts;
2335   for (int i = 0; i < NumLoops; ++i) {
2336     CanonicalLoopInfo *FloorLoop = Result[i];
2337     Value *TileSize = TileSizes[i];
2338 
2339     Value *FloorIsEpilogue =
2340         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
2341     Value *TileTripCount =
2342         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
2343 
2344     TileCounts.push_back(TileTripCount);
2345   }
2346 
2347   // Create the tile loops.
2348   EmbeddNewLoops(TileCounts, "tile");
2349 
2350   // Insert the inbetween code into the body.
2351   BasicBlock *BodyEnter = Enter;
2352   BasicBlock *BodyEntered = nullptr;
2353   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
2354     BasicBlock *EnterBB = P.first;
2355     BasicBlock *ExitBB = P.second;
2356 
2357     if (BodyEnter)
2358       redirectTo(BodyEnter, EnterBB, DL);
2359     else
2360       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
2361 
2362     BodyEnter = nullptr;
2363     BodyEntered = ExitBB;
2364   }
2365 
2366   // Append the original loop nest body into the generated loop nest body.
2367   if (BodyEnter)
2368     redirectTo(BodyEnter, InnerEnter, DL);
2369   else
2370     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
2371   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
2372 
2373   // Replace the original induction variable with an induction variable computed
2374   // from the tile and floor induction variables.
2375   Builder.restoreIP(Result.back()->getBodyIP());
2376   for (int i = 0; i < NumLoops; ++i) {
2377     CanonicalLoopInfo *FloorLoop = Result[i];
2378     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
2379     Value *OrigIndVar = OrigIndVars[i];
2380     Value *Size = TileSizes[i];
2381 
2382     Value *Scale =
2383         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
2384     Value *Shift =
2385         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
2386     OrigIndVar->replaceAllUsesWith(Shift);
2387   }
2388 
2389   // Remove unused parts of the original loops.
2390   removeUnusedBlocksFromParent(OldControlBBs);
2391 
2392   for (CanonicalLoopInfo *L : Loops)
2393     L->invalidate();
2394 
2395 #ifndef NDEBUG
2396   for (CanonicalLoopInfo *GenL : Result)
2397     GenL->assertOK();
2398 #endif
2399   return Result;
2400 }
2401 
2402 /// Attach loop metadata \p Properties to the loop described by \p Loop. If the
2403 /// loop already has metadata, the loop properties are appended.
2404 static void addLoopMetadata(CanonicalLoopInfo *Loop,
2405                             ArrayRef<Metadata *> Properties) {
2406   assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
2407 
2408   // Nothing to do if no property to attach.
2409   if (Properties.empty())
2410     return;
2411 
2412   LLVMContext &Ctx = Loop->getFunction()->getContext();
2413   SmallVector<Metadata *> NewLoopProperties;
2414   NewLoopProperties.push_back(nullptr);
2415 
2416   // If the loop already has metadata, prepend it to the new metadata.
2417   BasicBlock *Latch = Loop->getLatch();
2418   assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
2419   MDNode *Existing = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
2420   if (Existing)
2421     append_range(NewLoopProperties, drop_begin(Existing->operands(), 1));
2422 
2423   append_range(NewLoopProperties, Properties);
2424   MDNode *LoopID = MDNode::getDistinct(Ctx, NewLoopProperties);
2425   LoopID->replaceOperandWith(0, LoopID);
2426 
2427   Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
2428 }
2429 
2430 /// Attach llvm.access.group metadata to the memref instructions of \p Block
2431 static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
2432                             LoopInfo &LI) {
2433   for (Instruction &I : *Block) {
2434     if (I.mayReadOrWriteMemory()) {
2435       // TODO: This instruction may already have access group from
2436       // other pragmas e.g. #pragma clang loop vectorize.  Append
2437       // so that the existing metadata is not overwritten.
2438       I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
2439     }
2440   }
2441 }
2442 
2443 void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {
2444   LLVMContext &Ctx = Builder.getContext();
2445   addLoopMetadata(
2446       Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2447              MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
2448 }
2449 
2450 void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {
2451   LLVMContext &Ctx = Builder.getContext();
2452   addLoopMetadata(
2453       Loop, {
2454                 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2455             });
2456 }
2457 
2458 void OpenMPIRBuilder::applySimd(DebugLoc, CanonicalLoopInfo *CanonicalLoop) {
2459   LLVMContext &Ctx = Builder.getContext();
2460 
2461   Function *F = CanonicalLoop->getFunction();
2462 
2463   FunctionAnalysisManager FAM;
2464   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2465   FAM.registerPass([]() { return LoopAnalysis(); });
2466   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2467 
2468   LoopAnalysis LIA;
2469   LoopInfo &&LI = LIA.run(*F, FAM);
2470 
2471   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
2472 
2473   SmallSet<BasicBlock *, 8> Reachable;
2474 
2475   // Get the basic blocks from the loop in which memref instructions
2476   // can be found.
2477   // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
2478   // preferably without running any passes.
2479   for (BasicBlock *Block : L->getBlocks()) {
2480     if (Block == CanonicalLoop->getCond() ||
2481         Block == CanonicalLoop->getHeader())
2482       continue;
2483     Reachable.insert(Block);
2484   }
2485 
2486   // Add access group metadata to memory-access instructions.
2487   MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
2488   for (BasicBlock *BB : Reachable)
2489     addSimdMetadata(BB, AccessGroup, LI);
2490 
2491   // Use the above access group metadata to create loop level
2492   // metadata, which should be distinct for each loop.
2493   ConstantAsMetadata *BoolConst =
2494       ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));
2495   // TODO:  If the loop has existing parallel access metadata, have
2496   // to combine two lists.
2497   addLoopMetadata(
2498       CanonicalLoop,
2499       {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"),
2500                          AccessGroup}),
2501        MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
2502                          BoolConst})});
2503 }
2504 
2505 /// Create the TargetMachine object to query the backend for optimization
2506 /// preferences.
2507 ///
2508 /// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
2509 /// e.g. Clang does not pass it to its CodeGen layer and creates it only when
2510 /// needed for the LLVM pass pipline. We use some default options to avoid
2511 /// having to pass too many settings from the frontend that probably do not
2512 /// matter.
2513 ///
2514 /// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
2515 /// method. If we are going to use TargetMachine for more purposes, especially
2516 /// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
2517 /// might become be worth requiring front-ends to pass on their TargetMachine,
2518 /// or at least cache it between methods. Note that while fontends such as Clang
2519 /// have just a single main TargetMachine per translation unit, "target-cpu" and
2520 /// "target-features" that determine the TargetMachine are per-function and can
2521 /// be overrided using __attribute__((target("OPTIONS"))).
2522 static std::unique_ptr<TargetMachine>
2523 createTargetMachine(Function *F, CodeGenOpt::Level OptLevel) {
2524   Module *M = F->getParent();
2525 
2526   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
2527   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
2528   const std::string &Triple = M->getTargetTriple();
2529 
2530   std::string Error;
2531   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
2532   if (!TheTarget)
2533     return {};
2534 
2535   llvm::TargetOptions Options;
2536   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
2537       Triple, CPU, Features, Options, /*RelocModel=*/None, /*CodeModel=*/None,
2538       OptLevel));
2539 }
2540 
2541 /// Heuristically determine the best-performant unroll factor for \p CLI. This
2542 /// depends on the target processor. We are re-using the same heuristics as the
2543 /// LoopUnrollPass.
2544 static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {
2545   Function *F = CLI->getFunction();
2546 
2547   // Assume the user requests the most aggressive unrolling, even if the rest of
2548   // the code is optimized using a lower setting.
2549   CodeGenOpt::Level OptLevel = CodeGenOpt::Aggressive;
2550   std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
2551 
2552   FunctionAnalysisManager FAM;
2553   FAM.registerPass([]() { return TargetLibraryAnalysis(); });
2554   FAM.registerPass([]() { return AssumptionAnalysis(); });
2555   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2556   FAM.registerPass([]() { return LoopAnalysis(); });
2557   FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
2558   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2559   TargetIRAnalysis TIRA;
2560   if (TM)
2561     TIRA = TargetIRAnalysis(
2562         [&](const Function &F) { return TM->getTargetTransformInfo(F); });
2563   FAM.registerPass([&]() { return TIRA; });
2564 
2565   TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
2566   ScalarEvolutionAnalysis SEA;
2567   ScalarEvolution &&SE = SEA.run(*F, FAM);
2568   DominatorTreeAnalysis DTA;
2569   DominatorTree &&DT = DTA.run(*F, FAM);
2570   LoopAnalysis LIA;
2571   LoopInfo &&LI = LIA.run(*F, FAM);
2572   AssumptionAnalysis ACT;
2573   AssumptionCache &&AC = ACT.run(*F, FAM);
2574   OptimizationRemarkEmitter ORE{F};
2575 
2576   Loop *L = LI.getLoopFor(CLI->getHeader());
2577   assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
2578 
2579   TargetTransformInfo::UnrollingPreferences UP =
2580       gatherUnrollingPreferences(L, SE, TTI,
2581                                  /*BlockFrequencyInfo=*/nullptr,
2582                                  /*ProfileSummaryInfo=*/nullptr, ORE, OptLevel,
2583                                  /*UserThreshold=*/None,
2584                                  /*UserCount=*/None,
2585                                  /*UserAllowPartial=*/true,
2586                                  /*UserAllowRuntime=*/true,
2587                                  /*UserUpperBound=*/None,
2588                                  /*UserFullUnrollMaxCount=*/None);
2589 
2590   UP.Force = true;
2591 
2592   // Account for additional optimizations taking place before the LoopUnrollPass
2593   // would unroll the loop.
2594   UP.Threshold *= UnrollThresholdFactor;
2595   UP.PartialThreshold *= UnrollThresholdFactor;
2596 
2597   // Use normal unroll factors even if the rest of the code is optimized for
2598   // size.
2599   UP.OptSizeThreshold = UP.Threshold;
2600   UP.PartialOptSizeThreshold = UP.PartialThreshold;
2601 
2602   LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
2603                     << "  Threshold=" << UP.Threshold << "\n"
2604                     << "  PartialThreshold=" << UP.PartialThreshold << "\n"
2605                     << "  OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
2606                     << "  PartialOptSizeThreshold="
2607                     << UP.PartialOptSizeThreshold << "\n");
2608 
2609   // Disable peeling.
2610   TargetTransformInfo::PeelingPreferences PP =
2611       gatherPeelingPreferences(L, SE, TTI,
2612                                /*UserAllowPeeling=*/false,
2613                                /*UserAllowProfileBasedPeeling=*/false,
2614                                /*UnrollingSpecficValues=*/false);
2615 
2616   SmallPtrSet<const Value *, 32> EphValues;
2617   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
2618 
2619   // Assume that reads and writes to stack variables can be eliminated by
2620   // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
2621   // size.
2622   for (BasicBlock *BB : L->blocks()) {
2623     for (Instruction &I : *BB) {
2624       Value *Ptr;
2625       if (auto *Load = dyn_cast<LoadInst>(&I)) {
2626         Ptr = Load->getPointerOperand();
2627       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2628         Ptr = Store->getPointerOperand();
2629       } else
2630         continue;
2631 
2632       Ptr = Ptr->stripPointerCasts();
2633 
2634       if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
2635         if (Alloca->getParent() == &F->getEntryBlock())
2636           EphValues.insert(&I);
2637       }
2638     }
2639   }
2640 
2641   unsigned NumInlineCandidates;
2642   bool NotDuplicatable;
2643   bool Convergent;
2644   unsigned LoopSize =
2645       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
2646                           TTI, EphValues, UP.BEInsns);
2647   LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSize << "\n");
2648 
2649   // Loop is not unrollable if the loop contains certain instructions.
2650   if (NotDuplicatable || Convergent) {
2651     LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
2652     return 1;
2653   }
2654 
2655   // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
2656   // be able to use it.
2657   int TripCount = 0;
2658   int MaxTripCount = 0;
2659   bool MaxOrZero = false;
2660   unsigned TripMultiple = 0;
2661 
2662   bool UseUpperBound = false;
2663   computeUnrollCount(L, TTI, DT, &LI, SE, EphValues, &ORE, TripCount,
2664                      MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
2665                      UseUpperBound);
2666   unsigned Factor = UP.Count;
2667   LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
2668 
2669   // This function returns 1 to signal to not unroll a loop.
2670   if (Factor == 0)
2671     return 1;
2672   return Factor;
2673 }
2674 
2675 void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
2676                                         int32_t Factor,
2677                                         CanonicalLoopInfo **UnrolledCLI) {
2678   assert(Factor >= 0 && "Unroll factor must not be negative");
2679 
2680   Function *F = Loop->getFunction();
2681   LLVMContext &Ctx = F->getContext();
2682 
2683   // If the unrolled loop is not used for another loop-associated directive, it
2684   // is sufficient to add metadata for the LoopUnrollPass.
2685   if (!UnrolledCLI) {
2686     SmallVector<Metadata *, 2> LoopMetadata;
2687     LoopMetadata.push_back(
2688         MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
2689 
2690     if (Factor >= 1) {
2691       ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
2692           ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
2693       LoopMetadata.push_back(MDNode::get(
2694           Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
2695     }
2696 
2697     addLoopMetadata(Loop, LoopMetadata);
2698     return;
2699   }
2700 
2701   // Heuristically determine the unroll factor.
2702   if (Factor == 0)
2703     Factor = computeHeuristicUnrollFactor(Loop);
2704 
2705   // No change required with unroll factor 1.
2706   if (Factor == 1) {
2707     *UnrolledCLI = Loop;
2708     return;
2709   }
2710 
2711   assert(Factor >= 2 &&
2712          "unrolling only makes sense with a factor of 2 or larger");
2713 
2714   Type *IndVarTy = Loop->getIndVarType();
2715 
2716   // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
2717   // unroll the inner loop.
2718   Value *FactorVal =
2719       ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
2720                                        /*isSigned=*/false));
2721   std::vector<CanonicalLoopInfo *> LoopNest =
2722       tileLoops(DL, {Loop}, {FactorVal});
2723   assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
2724   *UnrolledCLI = LoopNest[0];
2725   CanonicalLoopInfo *InnerLoop = LoopNest[1];
2726 
2727   // LoopUnrollPass can only fully unroll loops with constant trip count.
2728   // Unroll by the unroll factor with a fallback epilog for the remainder
2729   // iterations if necessary.
2730   ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
2731       ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
2732   addLoopMetadata(
2733       InnerLoop,
2734       {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2735        MDNode::get(
2736            Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
2737 
2738 #ifndef NDEBUG
2739   (*UnrolledCLI)->assertOK();
2740 #endif
2741 }
2742 
2743 OpenMPIRBuilder::InsertPointTy
2744 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
2745                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
2746                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
2747   if (!updateToLocation(Loc))
2748     return Loc.IP;
2749 
2750   uint32_t SrcLocStrSize;
2751   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2752   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2753   Value *ThreadId = getOrCreateThreadID(Ident);
2754 
2755   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
2756 
2757   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
2758 
2759   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
2760   Builder.CreateCall(Fn, Args);
2761 
2762   return Builder.saveIP();
2763 }
2764 
2765 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(
2766     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2767     FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
2768 
2769   if (!updateToLocation(Loc))
2770     return Loc.IP;
2771 
2772   // If needed (i.e. not null), initialize `DidIt` with 0
2773   if (DidIt) {
2774     Builder.CreateStore(Builder.getInt32(0), DidIt);
2775   }
2776 
2777   Directive OMPD = Directive::OMPD_single;
2778   uint32_t SrcLocStrSize;
2779   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2780   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2781   Value *ThreadId = getOrCreateThreadID(Ident);
2782   Value *Args[] = {Ident, ThreadId};
2783 
2784   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
2785   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2786 
2787   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
2788   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2789 
2790   // generates the following:
2791   // if (__kmpc_single()) {
2792   //		.... single region ...
2793   // 		__kmpc_end_single
2794   // }
2795   // __kmpc_barrier
2796 
2797   EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2798                        /*Conditional*/ true,
2799                        /*hasFinalize*/ true);
2800   if (!IsNowait)
2801     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
2802                   omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
2803                   /* CheckCancelFlag */ false);
2804   return Builder.saveIP();
2805 }
2806 
2807 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
2808     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2809     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
2810 
2811   if (!updateToLocation(Loc))
2812     return Loc.IP;
2813 
2814   Directive OMPD = Directive::OMPD_critical;
2815   uint32_t SrcLocStrSize;
2816   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2817   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2818   Value *ThreadId = getOrCreateThreadID(Ident);
2819   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
2820   Value *Args[] = {Ident, ThreadId, LockVar};
2821 
2822   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
2823   Function *RTFn = nullptr;
2824   if (HintInst) {
2825     // Add Hint to entry Args and create call
2826     EnterArgs.push_back(HintInst);
2827     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
2828   } else {
2829     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
2830   }
2831   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
2832 
2833   Function *ExitRTLFn =
2834       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
2835   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2836 
2837   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2838                               /*Conditional*/ false, /*hasFinalize*/ true);
2839 }
2840 
2841 OpenMPIRBuilder::InsertPointTy
2842 OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,
2843                                      InsertPointTy AllocaIP, unsigned NumLoops,
2844                                      ArrayRef<llvm::Value *> StoreValues,
2845                                      const Twine &Name, bool IsDependSource) {
2846   for (size_t I = 0; I < StoreValues.size(); I++)
2847     assert(StoreValues[I]->getType()->isIntegerTy(64) &&
2848            "OpenMP runtime requires depend vec with i64 type");
2849 
2850   if (!updateToLocation(Loc))
2851     return Loc.IP;
2852 
2853   // Allocate space for vector and generate alloc instruction.
2854   auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
2855   Builder.restoreIP(AllocaIP);
2856   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
2857   ArgsBase->setAlignment(Align(8));
2858   Builder.restoreIP(Loc.IP);
2859 
2860   // Store the index value with offset in depend vector.
2861   for (unsigned I = 0; I < NumLoops; ++I) {
2862     Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
2863         ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
2864     StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
2865     STInst->setAlignment(Align(8));
2866   }
2867 
2868   Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
2869       ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
2870 
2871   uint32_t SrcLocStrSize;
2872   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2873   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2874   Value *ThreadId = getOrCreateThreadID(Ident);
2875   Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
2876 
2877   Function *RTLFn = nullptr;
2878   if (IsDependSource)
2879     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
2880   else
2881     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
2882   Builder.CreateCall(RTLFn, Args);
2883 
2884   return Builder.saveIP();
2885 }
2886 
2887 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(
2888     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2889     FinalizeCallbackTy FiniCB, bool IsThreads) {
2890   if (!updateToLocation(Loc))
2891     return Loc.IP;
2892 
2893   Directive OMPD = Directive::OMPD_ordered;
2894   Instruction *EntryCall = nullptr;
2895   Instruction *ExitCall = nullptr;
2896 
2897   if (IsThreads) {
2898     uint32_t SrcLocStrSize;
2899     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2900     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2901     Value *ThreadId = getOrCreateThreadID(Ident);
2902     Value *Args[] = {Ident, ThreadId};
2903 
2904     Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
2905     EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2906 
2907     Function *ExitRTLFn =
2908         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
2909     ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2910   }
2911 
2912   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2913                               /*Conditional*/ false, /*hasFinalize*/ true);
2914 }
2915 
2916 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
2917     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
2918     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
2919     bool HasFinalize, bool IsCancellable) {
2920 
2921   if (HasFinalize)
2922     FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
2923 
2924   // Create inlined region's entry and body blocks, in preparation
2925   // for conditional creation
2926   BasicBlock *EntryBB = Builder.GetInsertBlock();
2927   Instruction *SplitPos = EntryBB->getTerminator();
2928   if (!isa_and_nonnull<BranchInst>(SplitPos))
2929     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
2930   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
2931   BasicBlock *FiniBB =
2932       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
2933 
2934   Builder.SetInsertPoint(EntryBB->getTerminator());
2935   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
2936 
2937   // generate body
2938   BodyGenCB(/* AllocaIP */ InsertPointTy(),
2939             /* CodeGenIP */ Builder.saveIP(), *FiniBB);
2940 
2941   // If we didn't emit a branch to FiniBB during body generation, it means
2942   // FiniBB is unreachable (e.g. while(1);). stop generating all the
2943   // unreachable blocks, and remove anything we are not going to use.
2944   auto SkipEmittingRegion = FiniBB->hasNPredecessors(0);
2945   if (SkipEmittingRegion) {
2946     FiniBB->eraseFromParent();
2947     ExitCall->eraseFromParent();
2948     // Discard finalization if we have it.
2949     if (HasFinalize) {
2950       assert(!FinalizationStack.empty() &&
2951              "Unexpected finalization stack state!");
2952       FinalizationStack.pop_back();
2953     }
2954   } else {
2955     // emit exit call and do any needed finalization.
2956     auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
2957     assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
2958            FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
2959            "Unexpected control flow graph state!!");
2960     emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
2961     assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
2962            "Unexpected Control Flow State!");
2963     MergeBlockIntoPredecessor(FiniBB);
2964   }
2965 
2966   // If we are skipping the region of a non conditional, remove the exit
2967   // block, and clear the builder's insertion point.
2968   assert(SplitPos->getParent() == ExitBB &&
2969          "Unexpected Insertion point location!");
2970   if (!Conditional && SkipEmittingRegion) {
2971     ExitBB->eraseFromParent();
2972     Builder.ClearInsertionPoint();
2973   } else {
2974     auto merged = MergeBlockIntoPredecessor(ExitBB);
2975     BasicBlock *ExitPredBB = SplitPos->getParent();
2976     auto InsertBB = merged ? ExitPredBB : ExitBB;
2977     if (!isa_and_nonnull<BranchInst>(SplitPos))
2978       SplitPos->eraseFromParent();
2979     Builder.SetInsertPoint(InsertBB);
2980   }
2981 
2982   return Builder.saveIP();
2983 }
2984 
2985 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
2986     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
2987   // if nothing to do, Return current insertion point.
2988   if (!Conditional || !EntryCall)
2989     return Builder.saveIP();
2990 
2991   BasicBlock *EntryBB = Builder.GetInsertBlock();
2992   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
2993   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
2994   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
2995 
2996   // Emit thenBB and set the Builder's insertion point there for
2997   // body generation next. Place the block after the current block.
2998   Function *CurFn = EntryBB->getParent();
2999   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
3000 
3001   // Move Entry branch to end of ThenBB, and replace with conditional
3002   // branch (If-stmt)
3003   Instruction *EntryBBTI = EntryBB->getTerminator();
3004   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
3005   EntryBBTI->removeFromParent();
3006   Builder.SetInsertPoint(UI);
3007   Builder.Insert(EntryBBTI);
3008   UI->eraseFromParent();
3009   Builder.SetInsertPoint(ThenBB->getTerminator());
3010 
3011   // return an insertion point to ExitBB.
3012   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
3013 }
3014 
3015 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
3016     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
3017     bool HasFinalize) {
3018 
3019   Builder.restoreIP(FinIP);
3020 
3021   // If there is finalization to do, emit it before the exit call
3022   if (HasFinalize) {
3023     assert(!FinalizationStack.empty() &&
3024            "Unexpected finalization stack state!");
3025 
3026     FinalizationInfo Fi = FinalizationStack.pop_back_val();
3027     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3028 
3029     Fi.FiniCB(FinIP);
3030 
3031     BasicBlock *FiniBB = FinIP.getBlock();
3032     Instruction *FiniBBTI = FiniBB->getTerminator();
3033 
3034     // set Builder IP for call creation
3035     Builder.SetInsertPoint(FiniBBTI);
3036   }
3037 
3038   if (!ExitCall)
3039     return Builder.saveIP();
3040 
3041   // place the Exitcall as last instruction before Finalization block terminator
3042   ExitCall->removeFromParent();
3043   Builder.Insert(ExitCall);
3044 
3045   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3046                                   ExitCall->getIterator());
3047 }
3048 
3049 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
3050     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3051     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3052   if (!IP.isSet())
3053     return IP;
3054 
3055   IRBuilder<>::InsertPointGuard IPG(Builder);
3056 
3057   // creates the following CFG structure
3058   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
3059   //       F     T
3060   //       |      \
3061   //       |     copin.not.master
3062   //       |      /
3063   //       v     /
3064   //   copyin.not.master.end
3065   //		     |
3066   //         v
3067   //   OMP.Entry.Next
3068 
3069   BasicBlock *OMP_Entry = IP.getBlock();
3070   Function *CurFn = OMP_Entry->getParent();
3071   BasicBlock *CopyBegin =
3072       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3073   BasicBlock *CopyEnd = nullptr;
3074 
3075   // If entry block is terminated, split to preserve the branch to following
3076   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3077   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3078     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3079                                          "copyin.not.master.end");
3080     OMP_Entry->getTerminator()->eraseFromParent();
3081   } else {
3082     CopyEnd =
3083         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3084   }
3085 
3086   Builder.SetInsertPoint(OMP_Entry);
3087   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3088   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3089   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3090   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3091 
3092   Builder.SetInsertPoint(CopyBegin);
3093   if (BranchtoEnd)
3094     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
3095 
3096   return Builder.saveIP();
3097 }
3098 
3099 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
3100                                           Value *Size, Value *Allocator,
3101                                           std::string Name) {
3102   IRBuilder<>::InsertPointGuard IPG(Builder);
3103   Builder.restoreIP(Loc.IP);
3104 
3105   uint32_t SrcLocStrSize;
3106   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3107   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3108   Value *ThreadId = getOrCreateThreadID(Ident);
3109   Value *Args[] = {ThreadId, Size, Allocator};
3110 
3111   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3112 
3113   return Builder.CreateCall(Fn, Args, Name);
3114 }
3115 
3116 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
3117                                          Value *Addr, Value *Allocator,
3118                                          std::string Name) {
3119   IRBuilder<>::InsertPointGuard IPG(Builder);
3120   Builder.restoreIP(Loc.IP);
3121 
3122   uint32_t SrcLocStrSize;
3123   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3124   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3125   Value *ThreadId = getOrCreateThreadID(Ident);
3126   Value *Args[] = {ThreadId, Addr, Allocator};
3127   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3128   return Builder.CreateCall(Fn, Args, Name);
3129 }
3130 
3131 CallInst *OpenMPIRBuilder::createOMPInteropInit(
3132     const LocationDescription &Loc, Value *InteropVar,
3133     omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3134     Value *DependenceAddress, bool HaveNowaitClause) {
3135   IRBuilder<>::InsertPointGuard IPG(Builder);
3136   Builder.restoreIP(Loc.IP);
3137 
3138   uint32_t SrcLocStrSize;
3139   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3140   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3141   Value *ThreadId = getOrCreateThreadID(Ident);
3142   if (Device == nullptr)
3143     Device = ConstantInt::get(Int32, -1);
3144   Constant *InteropTypeVal = ConstantInt::get(Int64, (int)InteropType);
3145   if (NumDependences == nullptr) {
3146     NumDependences = ConstantInt::get(Int32, 0);
3147     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3148     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3149   }
3150   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3151   Value *Args[] = {
3152       Ident,  ThreadId,       InteropVar,        InteropTypeVal,
3153       Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
3154 
3155   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
3156 
3157   return Builder.CreateCall(Fn, Args);
3158 }
3159 
3160 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
3161     const LocationDescription &Loc, Value *InteropVar, Value *Device,
3162     Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
3163   IRBuilder<>::InsertPointGuard IPG(Builder);
3164   Builder.restoreIP(Loc.IP);
3165 
3166   uint32_t SrcLocStrSize;
3167   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3168   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3169   Value *ThreadId = getOrCreateThreadID(Ident);
3170   if (Device == nullptr)
3171     Device = ConstantInt::get(Int32, -1);
3172   if (NumDependences == nullptr) {
3173     NumDependences = ConstantInt::get(Int32, 0);
3174     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3175     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3176   }
3177   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3178   Value *Args[] = {
3179       Ident,          ThreadId,          InteropVar,         Device,
3180       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3181 
3182   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
3183 
3184   return Builder.CreateCall(Fn, Args);
3185 }
3186 
3187 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
3188                                                Value *InteropVar, Value *Device,
3189                                                Value *NumDependences,
3190                                                Value *DependenceAddress,
3191                                                bool HaveNowaitClause) {
3192   IRBuilder<>::InsertPointGuard IPG(Builder);
3193   Builder.restoreIP(Loc.IP);
3194   uint32_t SrcLocStrSize;
3195   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3196   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3197   Value *ThreadId = getOrCreateThreadID(Ident);
3198   if (Device == nullptr)
3199     Device = ConstantInt::get(Int32, -1);
3200   if (NumDependences == nullptr) {
3201     NumDependences = ConstantInt::get(Int32, 0);
3202     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3203     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3204   }
3205   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3206   Value *Args[] = {
3207       Ident,          ThreadId,          InteropVar,         Device,
3208       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3209 
3210   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
3211 
3212   return Builder.CreateCall(Fn, Args);
3213 }
3214 
3215 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
3216     const LocationDescription &Loc, llvm::Value *Pointer,
3217     llvm::ConstantInt *Size, const llvm::Twine &Name) {
3218   IRBuilder<>::InsertPointGuard IPG(Builder);
3219   Builder.restoreIP(Loc.IP);
3220 
3221   uint32_t SrcLocStrSize;
3222   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3223   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3224   Value *ThreadId = getOrCreateThreadID(Ident);
3225   Constant *ThreadPrivateCache =
3226       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
3227   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
3228 
3229   Function *Fn =
3230       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
3231 
3232   return Builder.CreateCall(Fn, Args);
3233 }
3234 
3235 OpenMPIRBuilder::InsertPointTy
3236 OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
3237                                   bool RequiresFullRuntime) {
3238   if (!updateToLocation(Loc))
3239     return Loc.IP;
3240 
3241   uint32_t SrcLocStrSize;
3242   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3243   Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3244   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3245       IntegerType::getInt8Ty(Int8->getContext()),
3246       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3247   ConstantInt *UseGenericStateMachine =
3248       ConstantInt::getBool(Int32->getContext(), !IsSPMD);
3249   ConstantInt *RequiresFullRuntimeVal =
3250       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3251 
3252   Function *Fn = getOrCreateRuntimeFunctionPtr(
3253       omp::RuntimeFunction::OMPRTL___kmpc_target_init);
3254 
3255   CallInst *ThreadKind = Builder.CreateCall(
3256       Fn, {Ident, IsSPMDVal, UseGenericStateMachine, RequiresFullRuntimeVal});
3257 
3258   Value *ExecUserCode = Builder.CreateICmpEQ(
3259       ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
3260       "exec_user_code");
3261 
3262   // ThreadKind = __kmpc_target_init(...)
3263   // if (ThreadKind == -1)
3264   //   user_code
3265   // else
3266   //   return;
3267 
3268   auto *UI = Builder.CreateUnreachable();
3269   BasicBlock *CheckBB = UI->getParent();
3270   BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
3271 
3272   BasicBlock *WorkerExitBB = BasicBlock::Create(
3273       CheckBB->getContext(), "worker.exit", CheckBB->getParent());
3274   Builder.SetInsertPoint(WorkerExitBB);
3275   Builder.CreateRetVoid();
3276 
3277   auto *CheckBBTI = CheckBB->getTerminator();
3278   Builder.SetInsertPoint(CheckBBTI);
3279   Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
3280 
3281   CheckBBTI->eraseFromParent();
3282   UI->eraseFromParent();
3283 
3284   // Continue in the "user_code" block, see diagram above and in
3285   // openmp/libomptarget/deviceRTLs/common/include/target.h .
3286   return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
3287 }
3288 
3289 void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,
3290                                          bool IsSPMD,
3291                                          bool RequiresFullRuntime) {
3292   if (!updateToLocation(Loc))
3293     return;
3294 
3295   uint32_t SrcLocStrSize;
3296   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3297   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3298   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3299       IntegerType::getInt8Ty(Int8->getContext()),
3300       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3301   ConstantInt *RequiresFullRuntimeVal =
3302       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3303 
3304   Function *Fn = getOrCreateRuntimeFunctionPtr(
3305       omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
3306 
3307   Builder.CreateCall(Fn, {Ident, IsSPMDVal, RequiresFullRuntimeVal});
3308 }
3309 
3310 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
3311                                                    StringRef FirstSeparator,
3312                                                    StringRef Separator) {
3313   SmallString<128> Buffer;
3314   llvm::raw_svector_ostream OS(Buffer);
3315   StringRef Sep = FirstSeparator;
3316   for (StringRef Part : Parts) {
3317     OS << Sep << Part;
3318     Sep = Separator;
3319   }
3320   return OS.str().str();
3321 }
3322 
3323 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
3324     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
3325   // TODO: Replace the twine arg with stringref to get rid of the conversion
3326   // logic. However This is taken from current implementation in clang as is.
3327   // Since this method is used in many places exclusively for OMP internal use
3328   // we will keep it as is for temporarily until we move all users to the
3329   // builder and then, if possible, fix it everywhere in one go.
3330   SmallString<256> Buffer;
3331   llvm::raw_svector_ostream Out(Buffer);
3332   Out << Name;
3333   StringRef RuntimeName = Out.str();
3334   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
3335   if (Elem.second) {
3336     assert(cast<PointerType>(Elem.second->getType())
3337                ->isOpaqueOrPointeeTypeMatches(Ty) &&
3338            "OMP internal variable has different type than requested");
3339   } else {
3340     // TODO: investigate the appropriate linkage type used for the global
3341     // variable for possibly changing that to internal or private, or maybe
3342     // create different versions of the function for different OMP internal
3343     // variables.
3344     Elem.second = new llvm::GlobalVariable(
3345         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
3346         llvm::Constant::getNullValue(Ty), Elem.first(),
3347         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3348         AddressSpace);
3349   }
3350 
3351   return Elem.second;
3352 }
3353 
3354 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
3355   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
3356   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
3357   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
3358 }
3359 
3360 GlobalVariable *
3361 OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
3362                                        std::string VarName) {
3363   llvm::Constant *MaptypesArrayInit =
3364       llvm::ConstantDataArray::get(M.getContext(), Mappings);
3365   auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
3366       M, MaptypesArrayInit->getType(),
3367       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
3368       VarName);
3369   MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3370   return MaptypesArrayGlobal;
3371 }
3372 
3373 void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,
3374                                           InsertPointTy AllocaIP,
3375                                           unsigned NumOperands,
3376                                           struct MapperAllocas &MapperAllocas) {
3377   if (!updateToLocation(Loc))
3378     return;
3379 
3380   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3381   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3382   Builder.restoreIP(AllocaIP);
3383   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI8PtrTy);
3384   AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy);
3385   AllocaInst *ArgSizes = Builder.CreateAlloca(ArrI64Ty);
3386   Builder.restoreIP(Loc.IP);
3387   MapperAllocas.ArgsBase = ArgsBase;
3388   MapperAllocas.Args = Args;
3389   MapperAllocas.ArgSizes = ArgSizes;
3390 }
3391 
3392 void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,
3393                                      Function *MapperFunc, Value *SrcLocInfo,
3394                                      Value *MaptypesArg, Value *MapnamesArg,
3395                                      struct MapperAllocas &MapperAllocas,
3396                                      int64_t DeviceID, unsigned NumOperands) {
3397   if (!updateToLocation(Loc))
3398     return;
3399 
3400   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3401   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3402   Value *ArgsBaseGEP =
3403       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
3404                                 {Builder.getInt32(0), Builder.getInt32(0)});
3405   Value *ArgsGEP =
3406       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
3407                                 {Builder.getInt32(0), Builder.getInt32(0)});
3408   Value *ArgSizesGEP =
3409       Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
3410                                 {Builder.getInt32(0), Builder.getInt32(0)});
3411   Value *NullPtr = Constant::getNullValue(Int8Ptr->getPointerTo());
3412   Builder.CreateCall(MapperFunc,
3413                      {SrcLocInfo, Builder.getInt64(DeviceID),
3414                       Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,
3415                       ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
3416 }
3417 
3418 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
3419     const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
3420   assert(!(AO == AtomicOrdering::NotAtomic ||
3421            AO == llvm::AtomicOrdering::Unordered) &&
3422          "Unexpected Atomic Ordering.");
3423 
3424   bool Flush = false;
3425   llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;
3426 
3427   switch (AK) {
3428   case Read:
3429     if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||
3430         AO == AtomicOrdering::SequentiallyConsistent) {
3431       FlushAO = AtomicOrdering::Acquire;
3432       Flush = true;
3433     }
3434     break;
3435   case Write:
3436   case Compare:
3437   case Update:
3438     if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||
3439         AO == AtomicOrdering::SequentiallyConsistent) {
3440       FlushAO = AtomicOrdering::Release;
3441       Flush = true;
3442     }
3443     break;
3444   case Capture:
3445     switch (AO) {
3446     case AtomicOrdering::Acquire:
3447       FlushAO = AtomicOrdering::Acquire;
3448       Flush = true;
3449       break;
3450     case AtomicOrdering::Release:
3451       FlushAO = AtomicOrdering::Release;
3452       Flush = true;
3453       break;
3454     case AtomicOrdering::AcquireRelease:
3455     case AtomicOrdering::SequentiallyConsistent:
3456       FlushAO = AtomicOrdering::AcquireRelease;
3457       Flush = true;
3458       break;
3459     default:
3460       // do nothing - leave silently.
3461       break;
3462     }
3463   }
3464 
3465   if (Flush) {
3466     // Currently Flush RT call still doesn't take memory_ordering, so for when
3467     // that happens, this tries to do the resolution of which atomic ordering
3468     // to use with but issue the flush call
3469     // TODO: pass `FlushAO` after memory ordering support is added
3470     (void)FlushAO;
3471     emitFlush(Loc);
3472   }
3473 
3474   // for AO == AtomicOrdering::Monotonic and  all other case combinations
3475   // do nothing
3476   return Flush;
3477 }
3478 
3479 OpenMPIRBuilder::InsertPointTy
3480 OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,
3481                                   AtomicOpValue &X, AtomicOpValue &V,
3482                                   AtomicOrdering AO) {
3483   if (!updateToLocation(Loc))
3484     return Loc.IP;
3485 
3486   Type *XTy = X.Var->getType();
3487   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3488   Type *XElemTy = X.ElemTy;
3489   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3490           XElemTy->isPointerTy()) &&
3491          "OMP atomic read expected a scalar type");
3492 
3493   Value *XRead = nullptr;
3494 
3495   if (XElemTy->isIntegerTy()) {
3496     LoadInst *XLD =
3497         Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
3498     XLD->setAtomic(AO);
3499     XRead = cast<Value>(XLD);
3500   } else {
3501     // We need to bitcast and perform atomic op as integer
3502     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3503     IntegerType *IntCastTy =
3504         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3505     Value *XBCast = Builder.CreateBitCast(
3506         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.src.int.cast");
3507     LoadInst *XLoad =
3508         Builder.CreateLoad(IntCastTy, XBCast, X.IsVolatile, "omp.atomic.load");
3509     XLoad->setAtomic(AO);
3510     if (XElemTy->isFloatingPointTy()) {
3511       XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
3512     } else {
3513       XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
3514     }
3515   }
3516   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);
3517   Builder.CreateStore(XRead, V.Var, V.IsVolatile);
3518   return Builder.saveIP();
3519 }
3520 
3521 OpenMPIRBuilder::InsertPointTy
3522 OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,
3523                                    AtomicOpValue &X, Value *Expr,
3524                                    AtomicOrdering AO) {
3525   if (!updateToLocation(Loc))
3526     return Loc.IP;
3527 
3528   Type *XTy = X.Var->getType();
3529   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3530   Type *XElemTy = X.ElemTy;
3531   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3532           XElemTy->isPointerTy()) &&
3533          "OMP atomic write expected a scalar type");
3534 
3535   if (XElemTy->isIntegerTy()) {
3536     StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
3537     XSt->setAtomic(AO);
3538   } else {
3539     // We need to bitcast and perform atomic op as integers
3540     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3541     IntegerType *IntCastTy =
3542         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3543     Value *XBCast = Builder.CreateBitCast(
3544         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.dst.int.cast");
3545     Value *ExprCast =
3546         Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
3547     StoreInst *XSt = Builder.CreateStore(ExprCast, XBCast, X.IsVolatile);
3548     XSt->setAtomic(AO);
3549   }
3550 
3551   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);
3552   return Builder.saveIP();
3553 }
3554 
3555 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(
3556     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3557     Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3558     AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {
3559   assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
3560   if (!updateToLocation(Loc))
3561     return Loc.IP;
3562 
3563   LLVM_DEBUG({
3564     Type *XTy = X.Var->getType();
3565     assert(XTy->isPointerTy() &&
3566            "OMP Atomic expects a pointer to target memory");
3567     Type *XElemTy = X.ElemTy;
3568     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3569             XElemTy->isPointerTy()) &&
3570            "OMP atomic update expected a scalar type");
3571     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3572            (RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&
3573            "OpenMP atomic does not support LT or GT operations");
3574   });
3575 
3576   emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,
3577                    X.IsVolatile, IsXBinopExpr);
3578   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);
3579   return Builder.saveIP();
3580 }
3581 
3582 Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3583                                                AtomicRMWInst::BinOp RMWOp) {
3584   switch (RMWOp) {
3585   case AtomicRMWInst::Add:
3586     return Builder.CreateAdd(Src1, Src2);
3587   case AtomicRMWInst::Sub:
3588     return Builder.CreateSub(Src1, Src2);
3589   case AtomicRMWInst::And:
3590     return Builder.CreateAnd(Src1, Src2);
3591   case AtomicRMWInst::Nand:
3592     return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
3593   case AtomicRMWInst::Or:
3594     return Builder.CreateOr(Src1, Src2);
3595   case AtomicRMWInst::Xor:
3596     return Builder.CreateXor(Src1, Src2);
3597   case AtomicRMWInst::Xchg:
3598   case AtomicRMWInst::FAdd:
3599   case AtomicRMWInst::FSub:
3600   case AtomicRMWInst::BAD_BINOP:
3601   case AtomicRMWInst::Max:
3602   case AtomicRMWInst::Min:
3603   case AtomicRMWInst::UMax:
3604   case AtomicRMWInst::UMin:
3605     llvm_unreachable("Unsupported atomic update operation");
3606   }
3607   llvm_unreachable("Unsupported atomic update operation");
3608 }
3609 
3610 std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(
3611     InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3612     AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3613     AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {
3614   // TODO: handle the case where XElemTy is not byte-sized or not a power of 2
3615   // or a complex datatype.
3616   bool emitRMWOp = false;
3617   switch (RMWOp) {
3618   case AtomicRMWInst::Add:
3619   case AtomicRMWInst::And:
3620   case AtomicRMWInst::Nand:
3621   case AtomicRMWInst::Or:
3622   case AtomicRMWInst::Xor:
3623   case AtomicRMWInst::Xchg:
3624     emitRMWOp = XElemTy;
3625     break;
3626   case AtomicRMWInst::Sub:
3627     emitRMWOp = (IsXBinopExpr && XElemTy);
3628     break;
3629   default:
3630     emitRMWOp = false;
3631   }
3632   emitRMWOp &= XElemTy->isIntegerTy();
3633 
3634   std::pair<Value *, Value *> Res;
3635   if (emitRMWOp) {
3636     Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
3637     // not needed except in case of postfix captures. Generate anyway for
3638     // consistency with the else part. Will be removed with any DCE pass.
3639     // AtomicRMWInst::Xchg does not have a coressponding instruction.
3640     if (RMWOp == AtomicRMWInst::Xchg)
3641       Res.second = Res.first;
3642     else
3643       Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
3644   } else {
3645     unsigned Addrspace = cast<PointerType>(X->getType())->getAddressSpace();
3646     IntegerType *IntCastTy =
3647         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3648     Value *XBCast =
3649         Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
3650     LoadInst *OldVal =
3651         Builder.CreateLoad(IntCastTy, XBCast, X->getName() + ".atomic.load");
3652     OldVal->setAtomic(AO);
3653     // CurBB
3654     // |     /---\
3655 		// ContBB    |
3656     // |     \---/
3657     // ExitBB
3658     BasicBlock *CurBB = Builder.GetInsertBlock();
3659     Instruction *CurBBTI = CurBB->getTerminator();
3660     CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
3661     BasicBlock *ExitBB =
3662         CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
3663     BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
3664                                                 X->getName() + ".atomic.cont");
3665     ContBB->getTerminator()->eraseFromParent();
3666     Builder.restoreIP(AllocaIP);
3667     AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
3668     NewAtomicAddr->setName(X->getName() + "x.new.val");
3669     Builder.SetInsertPoint(ContBB);
3670     llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
3671     PHI->addIncoming(OldVal, CurBB);
3672     IntegerType *NewAtomicCastTy =
3673         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3674     bool IsIntTy = XElemTy->isIntegerTy();
3675     Value *NewAtomicIntAddr =
3676         (IsIntTy)
3677             ? NewAtomicAddr
3678             : Builder.CreateBitCast(NewAtomicAddr,
3679                                     NewAtomicCastTy->getPointerTo(Addrspace));
3680     Value *OldExprVal = PHI;
3681     if (!IsIntTy) {
3682       if (XElemTy->isFloatingPointTy()) {
3683         OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
3684                                            X->getName() + ".atomic.fltCast");
3685       } else {
3686         OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
3687                                             X->getName() + ".atomic.ptrCast");
3688       }
3689     }
3690 
3691     Value *Upd = UpdateOp(OldExprVal, Builder);
3692     Builder.CreateStore(Upd, NewAtomicAddr);
3693     LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicIntAddr);
3694     Value *XAddr =
3695         (IsIntTy)
3696             ? X
3697             : Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
3698     AtomicOrdering Failure =
3699         llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
3700     AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
3701         XAddr, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
3702     Result->setVolatile(VolatileX);
3703     Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
3704     Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
3705     PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
3706     Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
3707 
3708     Res.first = OldExprVal;
3709     Res.second = Upd;
3710 
3711     // set Insertion point in exit block
3712     if (UnreachableInst *ExitTI =
3713             dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
3714       CurBBTI->eraseFromParent();
3715       Builder.SetInsertPoint(ExitBB);
3716     } else {
3717       Builder.SetInsertPoint(ExitTI);
3718     }
3719   }
3720 
3721   return Res;
3722 }
3723 
3724 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(
3725     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3726     AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
3727     AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
3728     bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {
3729   if (!updateToLocation(Loc))
3730     return Loc.IP;
3731 
3732   LLVM_DEBUG({
3733     Type *XTy = X.Var->getType();
3734     assert(XTy->isPointerTy() &&
3735            "OMP Atomic expects a pointer to target memory");
3736     Type *XElemTy = X.ElemTy;
3737     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3738             XElemTy->isPointerTy()) &&
3739            "OMP atomic capture expected a scalar type");
3740     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3741            "OpenMP atomic does not support LT or GT operations");
3742   });
3743 
3744   // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
3745   // 'x' is simply atomically rewritten with 'expr'.
3746   AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
3747   std::pair<Value *, Value *> Result =
3748       emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
3749                        X.IsVolatile, IsXBinopExpr);
3750 
3751   Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);
3752   Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
3753 
3754   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);
3755   return Builder.saveIP();
3756 }
3757 
3758 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(
3759     const LocationDescription &Loc, AtomicOpValue &X, Value *E, Value *D,
3760     AtomicOrdering AO, OMPAtomicCompareOp Op, bool IsXBinopExpr) {
3761   if (!updateToLocation(Loc))
3762     return Loc.IP;
3763 
3764   assert(X.Var->getType()->isPointerTy() &&
3765          "OMP atomic expects a pointer to target memory");
3766   assert((X.ElemTy->isIntegerTy() || X.ElemTy->isPointerTy()) &&
3767          "OMP atomic compare expected a integer scalar type");
3768 
3769   if (Op == OMPAtomicCompareOp::EQ) {
3770     AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
3771     // We don't need the result for now.
3772     (void)Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
3773   } else {
3774     assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
3775            "Op should be either max or min at this point");
3776 
3777     // Reverse the ordop as the OpenMP forms are different from LLVM forms.
3778     // Let's take max as example.
3779     // OpenMP form:
3780     // x = x > expr ? expr : x;
3781     // LLVM form:
3782     // *ptr = *ptr > val ? *ptr : val;
3783     // We need to transform to LLVM form.
3784     // x = x <= expr ? x : expr;
3785     AtomicRMWInst::BinOp NewOp;
3786     if (IsXBinopExpr) {
3787       if (X.IsSigned)
3788         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
3789                                               : AtomicRMWInst::Max;
3790       else
3791         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
3792                                               : AtomicRMWInst::UMax;
3793     } else {
3794       if (X.IsSigned)
3795         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
3796                                               : AtomicRMWInst::Min;
3797       else
3798         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
3799                                               : AtomicRMWInst::UMin;
3800     }
3801     // We dont' need the result for now.
3802     (void)Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
3803   }
3804 
3805   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);
3806 
3807   return Builder.saveIP();
3808 }
3809 
3810 GlobalVariable *
3811 OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
3812                                        std::string VarName) {
3813   llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
3814       llvm::ArrayType::get(
3815           llvm::Type::getInt8Ty(M.getContext())->getPointerTo(), Names.size()),
3816       Names);
3817   auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
3818       M, MapNamesArrayInit->getType(),
3819       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
3820       VarName);
3821   return MapNamesArrayGlobal;
3822 }
3823 
3824 // Create all simple and struct types exposed by the runtime and remember
3825 // the llvm::PointerTypes of them for easy access later.
3826 void OpenMPIRBuilder::initializeTypes(Module &M) {
3827   LLVMContext &Ctx = M.getContext();
3828   StructType *T;
3829 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
3830 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
3831   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
3832   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
3833 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
3834   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
3835   VarName##Ptr = PointerType::getUnqual(VarName);
3836 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
3837   T = StructType::getTypeByName(Ctx, StructName);                              \
3838   if (!T)                                                                      \
3839     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
3840   VarName = T;                                                                 \
3841   VarName##Ptr = PointerType::getUnqual(T);
3842 #include "llvm/Frontend/OpenMP/OMPKinds.def"
3843 }
3844 
3845 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
3846     SmallPtrSetImpl<BasicBlock *> &BlockSet,
3847     SmallVectorImpl<BasicBlock *> &BlockVector) {
3848   SmallVector<BasicBlock *, 32> Worklist;
3849   BlockSet.insert(EntryBB);
3850   BlockSet.insert(ExitBB);
3851 
3852   Worklist.push_back(EntryBB);
3853   while (!Worklist.empty()) {
3854     BasicBlock *BB = Worklist.pop_back_val();
3855     BlockVector.push_back(BB);
3856     for (BasicBlock *SuccBB : successors(BB))
3857       if (BlockSet.insert(SuccBB).second)
3858         Worklist.push_back(SuccBB);
3859   }
3860 }
3861 
3862 void CanonicalLoopInfo::collectControlBlocks(
3863     SmallVectorImpl<BasicBlock *> &BBs) {
3864   // We only count those BBs as control block for which we do not need to
3865   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
3866   // flow. For consistency, this also means we do not add the Body block, which
3867   // is just the entry to the body code.
3868   BBs.reserve(BBs.size() + 6);
3869   BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
3870 }
3871 
3872 BasicBlock *CanonicalLoopInfo::getPreheader() const {
3873   assert(isValid() && "Requires a valid canonical loop");
3874   for (BasicBlock *Pred : predecessors(Header)) {
3875     if (Pred != Latch)
3876       return Pred;
3877   }
3878   llvm_unreachable("Missing preheader");
3879 }
3880 
3881 void CanonicalLoopInfo::setTripCount(Value *TripCount) {
3882   assert(isValid() && "Requires a valid canonical loop");
3883 
3884   Instruction *CmpI = &getCond()->front();
3885   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
3886   CmpI->setOperand(1, TripCount);
3887 
3888 #ifndef NDEBUG
3889   assertOK();
3890 #endif
3891 }
3892 
3893 void CanonicalLoopInfo::mapIndVar(
3894     llvm::function_ref<Value *(Instruction *)> Updater) {
3895   assert(isValid() && "Requires a valid canonical loop");
3896 
3897   Instruction *OldIV = getIndVar();
3898 
3899   // Record all uses excluding those introduced by the updater. Uses by the
3900   // CanonicalLoopInfo itself to keep track of the number of iterations are
3901   // excluded.
3902   SmallVector<Use *> ReplacableUses;
3903   for (Use &U : OldIV->uses()) {
3904     auto *User = dyn_cast<Instruction>(U.getUser());
3905     if (!User)
3906       continue;
3907     if (User->getParent() == getCond())
3908       continue;
3909     if (User->getParent() == getLatch())
3910       continue;
3911     ReplacableUses.push_back(&U);
3912   }
3913 
3914   // Run the updater that may introduce new uses
3915   Value *NewIV = Updater(OldIV);
3916 
3917   // Replace the old uses with the value returned by the updater.
3918   for (Use *U : ReplacableUses)
3919     U->set(NewIV);
3920 
3921 #ifndef NDEBUG
3922   assertOK();
3923 #endif
3924 }
3925 
3926 void CanonicalLoopInfo::assertOK() const {
3927 #ifndef NDEBUG
3928   // No constraints if this object currently does not describe a loop.
3929   if (!isValid())
3930     return;
3931 
3932   BasicBlock *Preheader = getPreheader();
3933   BasicBlock *Body = getBody();
3934   BasicBlock *After = getAfter();
3935 
3936   // Verify standard control-flow we use for OpenMP loops.
3937   assert(Preheader);
3938   assert(isa<BranchInst>(Preheader->getTerminator()) &&
3939          "Preheader must terminate with unconditional branch");
3940   assert(Preheader->getSingleSuccessor() == Header &&
3941          "Preheader must jump to header");
3942 
3943   assert(Header);
3944   assert(isa<BranchInst>(Header->getTerminator()) &&
3945          "Header must terminate with unconditional branch");
3946   assert(Header->getSingleSuccessor() == Cond &&
3947          "Header must jump to exiting block");
3948 
3949   assert(Cond);
3950   assert(Cond->getSinglePredecessor() == Header &&
3951          "Exiting block only reachable from header");
3952 
3953   assert(isa<BranchInst>(Cond->getTerminator()) &&
3954          "Exiting block must terminate with conditional branch");
3955   assert(size(successors(Cond)) == 2 &&
3956          "Exiting block must have two successors");
3957   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
3958          "Exiting block's first successor jump to the body");
3959   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
3960          "Exiting block's second successor must exit the loop");
3961 
3962   assert(Body);
3963   assert(Body->getSinglePredecessor() == Cond &&
3964          "Body only reachable from exiting block");
3965   assert(!isa<PHINode>(Body->front()));
3966 
3967   assert(Latch);
3968   assert(isa<BranchInst>(Latch->getTerminator()) &&
3969          "Latch must terminate with unconditional branch");
3970   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
3971   // TODO: To support simple redirecting of the end of the body code that has
3972   // multiple; introduce another auxiliary basic block like preheader and after.
3973   assert(Latch->getSinglePredecessor() != nullptr);
3974   assert(!isa<PHINode>(Latch->front()));
3975 
3976   assert(Exit);
3977   assert(isa<BranchInst>(Exit->getTerminator()) &&
3978          "Exit block must terminate with unconditional branch");
3979   assert(Exit->getSingleSuccessor() == After &&
3980          "Exit block must jump to after block");
3981 
3982   assert(After);
3983   assert(After->getSinglePredecessor() == Exit &&
3984          "After block only reachable from exit block");
3985   assert(After->empty() || !isa<PHINode>(After->front()));
3986 
3987   Instruction *IndVar = getIndVar();
3988   assert(IndVar && "Canonical induction variable not found?");
3989   assert(isa<IntegerType>(IndVar->getType()) &&
3990          "Induction variable must be an integer");
3991   assert(cast<PHINode>(IndVar)->getParent() == Header &&
3992          "Induction variable must be a PHI in the loop header");
3993   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
3994   assert(
3995       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
3996   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
3997 
3998   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
3999   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
4000   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
4001   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
4002   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
4003              ->isOne());
4004 
4005   Value *TripCount = getTripCount();
4006   assert(TripCount && "Loop trip count not found?");
4007   assert(IndVar->getType() == TripCount->getType() &&
4008          "Trip count and induction variable must have the same type");
4009 
4010   auto *CmpI = cast<CmpInst>(&Cond->front());
4011   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
4012          "Exit condition must be a signed less-than comparison");
4013   assert(CmpI->getOperand(0) == IndVar &&
4014          "Exit condition must compare the induction variable");
4015   assert(CmpI->getOperand(1) == TripCount &&
4016          "Exit condition must compare with the trip count");
4017 #endif
4018 }
4019 
4020 void CanonicalLoopInfo::invalidate() {
4021   Header = nullptr;
4022   Cond = nullptr;
4023   Latch = nullptr;
4024   Exit = nullptr;
4025 }
4026