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 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::applyDynamicWorkshareLoop(
1907     DebugLoc DL, CanonicalLoopInfo *CLI, InsertPointTy AllocaIP,
1908     OMPScheduleType SchedType, bool NeedsBarrier, Value *Chunk) {
1909   assert(CLI->isValid() && "Requires a valid canonical loop");
1910   assert(!isConflictIP(AllocaIP, CLI->getPreheaderIP()) &&
1911          "Require dedicated allocate IP");
1912 
1913   // Set up the source location value for OpenMP runtime.
1914   Builder.SetCurrentDebugLocation(DL);
1915 
1916   uint32_t SrcLocStrSize;
1917   Constant *SrcLocStr = getOrCreateSrcLocStr(DL, SrcLocStrSize);
1918   Value *SrcLoc = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
1919 
1920   // Declare useful OpenMP runtime functions.
1921   Value *IV = CLI->getIndVar();
1922   Type *IVTy = IV->getType();
1923   FunctionCallee DynamicInit = getKmpcForDynamicInitForType(IVTy, M, *this);
1924   FunctionCallee DynamicNext = getKmpcForDynamicNextForType(IVTy, M, *this);
1925 
1926   // Allocate space for computed loop bounds as expected by the "init" function.
1927   Builder.restoreIP(AllocaIP);
1928   Type *I32Type = Type::getInt32Ty(M.getContext());
1929   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1930   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1931   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1932   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1933 
1934   // At the end of the preheader, prepare for calling the "init" function by
1935   // storing the current loop bounds into the allocated space. A canonical loop
1936   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1937   // and produces an inclusive upper bound.
1938   BasicBlock *PreHeader = CLI->getPreheader();
1939   Builder.SetInsertPoint(PreHeader->getTerminator());
1940   Constant *One = ConstantInt::get(IVTy, 1);
1941   Builder.CreateStore(One, PLowerBound);
1942   Value *UpperBound = CLI->getTripCount();
1943   Builder.CreateStore(UpperBound, PUpperBound);
1944   Builder.CreateStore(One, PStride);
1945 
1946   BasicBlock *Header = CLI->getHeader();
1947   BasicBlock *Exit = CLI->getExit();
1948   BasicBlock *Cond = CLI->getCond();
1949   InsertPointTy AfterIP = CLI->getAfterIP();
1950 
1951   // The CLI will be "broken" in the code below, as the loop is no longer
1952   // a valid canonical loop.
1953 
1954   if (!Chunk)
1955     Chunk = One;
1956 
1957   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1958 
1959   Constant *SchedulingType =
1960       ConstantInt::get(I32Type, static_cast<int>(SchedType));
1961 
1962   // Call the "init" function.
1963   Builder.CreateCall(DynamicInit,
1964                      {SrcLoc, ThreadNum, SchedulingType, /* LowerBound */ One,
1965                       UpperBound, /* step */ One, Chunk});
1966 
1967   // An outer loop around the existing one.
1968   BasicBlock *OuterCond = BasicBlock::Create(
1969       PreHeader->getContext(), Twine(PreHeader->getName()) + ".outer.cond",
1970       PreHeader->getParent());
1971   // This needs to be 32-bit always, so can't use the IVTy Zero above.
1972   Builder.SetInsertPoint(OuterCond, OuterCond->getFirstInsertionPt());
1973   Value *Res =
1974       Builder.CreateCall(DynamicNext, {SrcLoc, ThreadNum, PLastIter,
1975                                        PLowerBound, PUpperBound, PStride});
1976   Constant *Zero32 = ConstantInt::get(I32Type, 0);
1977   Value *MoreWork = Builder.CreateCmp(CmpInst::ICMP_NE, Res, Zero32);
1978   Value *LowerBound =
1979       Builder.CreateSub(Builder.CreateLoad(IVTy, PLowerBound), One, "lb");
1980   Builder.CreateCondBr(MoreWork, Header, Exit);
1981 
1982   // Change PHI-node in loop header to use outer cond rather than preheader,
1983   // and set IV to the LowerBound.
1984   Instruction *Phi = &Header->front();
1985   auto *PI = cast<PHINode>(Phi);
1986   PI->setIncomingBlock(0, OuterCond);
1987   PI->setIncomingValue(0, LowerBound);
1988 
1989   // Then set the pre-header to jump to the OuterCond
1990   Instruction *Term = PreHeader->getTerminator();
1991   auto *Br = cast<BranchInst>(Term);
1992   Br->setSuccessor(0, OuterCond);
1993 
1994   // Modify the inner condition:
1995   // * Use the UpperBound returned from the DynamicNext call.
1996   // * jump to the loop outer loop when done with one of the inner loops.
1997   Builder.SetInsertPoint(Cond, Cond->getFirstInsertionPt());
1998   UpperBound = Builder.CreateLoad(IVTy, PUpperBound, "ub");
1999   Instruction *Comp = &*Builder.GetInsertPoint();
2000   auto *CI = cast<CmpInst>(Comp);
2001   CI->setOperand(1, UpperBound);
2002   // Redirect the inner exit to branch to outer condition.
2003   Instruction *Branch = &Cond->back();
2004   auto *BI = cast<BranchInst>(Branch);
2005   assert(BI->getSuccessor(1) == Exit);
2006   BI->setSuccessor(1, OuterCond);
2007 
2008   // Add the barrier if requested.
2009   if (NeedsBarrier) {
2010     Builder.SetInsertPoint(&Exit->back());
2011     createBarrier(LocationDescription(Builder.saveIP(), DL),
2012                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
2013                   /* CheckCancelFlag */ false);
2014   }
2015 
2016   CLI->invalidate();
2017   return AfterIP;
2018 }
2019 
2020 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
2021 /// after this \p OldTarget will be orphaned.
2022 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
2023                                       BasicBlock *NewTarget, DebugLoc DL) {
2024   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
2025     redirectTo(Pred, NewTarget, DL);
2026 }
2027 
2028 /// Determine which blocks in \p BBs are reachable from outside and remove the
2029 /// ones that are not reachable from the function.
2030 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
2031   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
2032   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
2033     for (Use &U : BB->uses()) {
2034       auto *UseInst = dyn_cast<Instruction>(U.getUser());
2035       if (!UseInst)
2036         continue;
2037       if (BBsToErase.count(UseInst->getParent()))
2038         continue;
2039       return true;
2040     }
2041     return false;
2042   };
2043 
2044   while (true) {
2045     bool Changed = false;
2046     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
2047       if (HasRemainingUses(BB)) {
2048         BBsToErase.erase(BB);
2049         Changed = true;
2050       }
2051     }
2052     if (!Changed)
2053       break;
2054   }
2055 
2056   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
2057   DeleteDeadBlocks(BBVec);
2058 }
2059 
2060 CanonicalLoopInfo *
2061 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2062                                InsertPointTy ComputeIP) {
2063   assert(Loops.size() >= 1 && "At least one loop required");
2064   size_t NumLoops = Loops.size();
2065 
2066   // Nothing to do if there is already just one loop.
2067   if (NumLoops == 1)
2068     return Loops.front();
2069 
2070   CanonicalLoopInfo *Outermost = Loops.front();
2071   CanonicalLoopInfo *Innermost = Loops.back();
2072   BasicBlock *OrigPreheader = Outermost->getPreheader();
2073   BasicBlock *OrigAfter = Outermost->getAfter();
2074   Function *F = OrigPreheader->getParent();
2075 
2076   // Loop control blocks that may become orphaned later.
2077   SmallVector<BasicBlock *, 12> OldControlBBs;
2078   OldControlBBs.reserve(6 * Loops.size());
2079   for (CanonicalLoopInfo *Loop : Loops)
2080     Loop->collectControlBlocks(OldControlBBs);
2081 
2082   // Setup the IRBuilder for inserting the trip count computation.
2083   Builder.SetCurrentDebugLocation(DL);
2084   if (ComputeIP.isSet())
2085     Builder.restoreIP(ComputeIP);
2086   else
2087     Builder.restoreIP(Outermost->getPreheaderIP());
2088 
2089   // Derive the collapsed' loop trip count.
2090   // TODO: Find common/largest indvar type.
2091   Value *CollapsedTripCount = nullptr;
2092   for (CanonicalLoopInfo *L : Loops) {
2093     assert(L->isValid() &&
2094            "All loops to collapse must be valid canonical loops");
2095     Value *OrigTripCount = L->getTripCount();
2096     if (!CollapsedTripCount) {
2097       CollapsedTripCount = OrigTripCount;
2098       continue;
2099     }
2100 
2101     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
2102     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
2103                                            {}, /*HasNUW=*/true);
2104   }
2105 
2106   // Create the collapsed loop control flow.
2107   CanonicalLoopInfo *Result =
2108       createLoopSkeleton(DL, CollapsedTripCount, F,
2109                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
2110 
2111   // Build the collapsed loop body code.
2112   // Start with deriving the input loop induction variables from the collapsed
2113   // one, using a divmod scheme. To preserve the original loops' order, the
2114   // innermost loop use the least significant bits.
2115   Builder.restoreIP(Result->getBodyIP());
2116 
2117   Value *Leftover = Result->getIndVar();
2118   SmallVector<Value *> NewIndVars;
2119   NewIndVars.resize(NumLoops);
2120   for (int i = NumLoops - 1; i >= 1; --i) {
2121     Value *OrigTripCount = Loops[i]->getTripCount();
2122 
2123     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
2124     NewIndVars[i] = NewIndVar;
2125 
2126     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
2127   }
2128   // Outermost loop gets all the remaining bits.
2129   NewIndVars[0] = Leftover;
2130 
2131   // Construct the loop body control flow.
2132   // We progressively construct the branch structure following in direction of
2133   // the control flow, from the leading in-between code, the loop nest body, the
2134   // trailing in-between code, and rejoining the collapsed loop's latch.
2135   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
2136   // the ContinueBlock is set, continue with that block. If ContinuePred, use
2137   // its predecessors as sources.
2138   BasicBlock *ContinueBlock = Result->getBody();
2139   BasicBlock *ContinuePred = nullptr;
2140   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
2141                                                           BasicBlock *NextSrc) {
2142     if (ContinueBlock)
2143       redirectTo(ContinueBlock, Dest, DL);
2144     else
2145       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
2146 
2147     ContinueBlock = nullptr;
2148     ContinuePred = NextSrc;
2149   };
2150 
2151   // The code before the nested loop of each level.
2152   // Because we are sinking it into the nest, it will be executed more often
2153   // that the original loop. More sophisticated schemes could keep track of what
2154   // the in-between code is and instantiate it only once per thread.
2155   for (size_t i = 0; i < NumLoops - 1; ++i)
2156     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
2157 
2158   // Connect the loop nest body.
2159   ContinueWith(Innermost->getBody(), Innermost->getLatch());
2160 
2161   // The code after the nested loop at each level.
2162   for (size_t i = NumLoops - 1; i > 0; --i)
2163     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
2164 
2165   // Connect the finished loop to the collapsed loop latch.
2166   ContinueWith(Result->getLatch(), nullptr);
2167 
2168   // Replace the input loops with the new collapsed loop.
2169   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
2170   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
2171 
2172   // Replace the input loop indvars with the derived ones.
2173   for (size_t i = 0; i < NumLoops; ++i)
2174     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
2175 
2176   // Remove unused parts of the input loops.
2177   removeUnusedBlocksFromParent(OldControlBBs);
2178 
2179   for (CanonicalLoopInfo *L : Loops)
2180     L->invalidate();
2181 
2182 #ifndef NDEBUG
2183   Result->assertOK();
2184 #endif
2185   return Result;
2186 }
2187 
2188 std::vector<CanonicalLoopInfo *>
2189 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
2190                            ArrayRef<Value *> TileSizes) {
2191   assert(TileSizes.size() == Loops.size() &&
2192          "Must pass as many tile sizes as there are loops");
2193   int NumLoops = Loops.size();
2194   assert(NumLoops >= 1 && "At least one loop to tile required");
2195 
2196   CanonicalLoopInfo *OutermostLoop = Loops.front();
2197   CanonicalLoopInfo *InnermostLoop = Loops.back();
2198   Function *F = OutermostLoop->getBody()->getParent();
2199   BasicBlock *InnerEnter = InnermostLoop->getBody();
2200   BasicBlock *InnerLatch = InnermostLoop->getLatch();
2201 
2202   // Loop control blocks that may become orphaned later.
2203   SmallVector<BasicBlock *, 12> OldControlBBs;
2204   OldControlBBs.reserve(6 * Loops.size());
2205   for (CanonicalLoopInfo *Loop : Loops)
2206     Loop->collectControlBlocks(OldControlBBs);
2207 
2208   // Collect original trip counts and induction variable to be accessible by
2209   // index. Also, the structure of the original loops is not preserved during
2210   // the construction of the tiled loops, so do it before we scavenge the BBs of
2211   // any original CanonicalLoopInfo.
2212   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
2213   for (CanonicalLoopInfo *L : Loops) {
2214     assert(L->isValid() && "All input loops must be valid canonical loops");
2215     OrigTripCounts.push_back(L->getTripCount());
2216     OrigIndVars.push_back(L->getIndVar());
2217   }
2218 
2219   // Collect the code between loop headers. These may contain SSA definitions
2220   // that are used in the loop nest body. To be usable with in the innermost
2221   // body, these BasicBlocks will be sunk into the loop nest body. That is,
2222   // these instructions may be executed more often than before the tiling.
2223   // TODO: It would be sufficient to only sink them into body of the
2224   // corresponding tile loop.
2225   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
2226   for (int i = 0; i < NumLoops - 1; ++i) {
2227     CanonicalLoopInfo *Surrounding = Loops[i];
2228     CanonicalLoopInfo *Nested = Loops[i + 1];
2229 
2230     BasicBlock *EnterBB = Surrounding->getBody();
2231     BasicBlock *ExitBB = Nested->getHeader();
2232     InbetweenCode.emplace_back(EnterBB, ExitBB);
2233   }
2234 
2235   // Compute the trip counts of the floor loops.
2236   Builder.SetCurrentDebugLocation(DL);
2237   Builder.restoreIP(OutermostLoop->getPreheaderIP());
2238   SmallVector<Value *, 4> FloorCount, FloorRems;
2239   for (int i = 0; i < NumLoops; ++i) {
2240     Value *TileSize = TileSizes[i];
2241     Value *OrigTripCount = OrigTripCounts[i];
2242     Type *IVType = OrigTripCount->getType();
2243 
2244     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
2245     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
2246 
2247     // 0 if tripcount divides the tilesize, 1 otherwise.
2248     // 1 means we need an additional iteration for a partial tile.
2249     //
2250     // Unfortunately we cannot just use the roundup-formula
2251     //   (tripcount + tilesize - 1)/tilesize
2252     // because the summation might overflow. We do not want introduce undefined
2253     // behavior when the untiled loop nest did not.
2254     Value *FloorTripOverflow =
2255         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
2256 
2257     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
2258     FloorTripCount =
2259         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
2260                           "omp_floor" + Twine(i) + ".tripcount", true);
2261 
2262     // Remember some values for later use.
2263     FloorCount.push_back(FloorTripCount);
2264     FloorRems.push_back(FloorTripRem);
2265   }
2266 
2267   // Generate the new loop nest, from the outermost to the innermost.
2268   std::vector<CanonicalLoopInfo *> Result;
2269   Result.reserve(NumLoops * 2);
2270 
2271   // The basic block of the surrounding loop that enters the nest generated
2272   // loop.
2273   BasicBlock *Enter = OutermostLoop->getPreheader();
2274 
2275   // The basic block of the surrounding loop where the inner code should
2276   // continue.
2277   BasicBlock *Continue = OutermostLoop->getAfter();
2278 
2279   // Where the next loop basic block should be inserted.
2280   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
2281 
2282   auto EmbeddNewLoop =
2283       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
2284           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
2285     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
2286         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
2287     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
2288     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
2289 
2290     // Setup the position where the next embedded loop connects to this loop.
2291     Enter = EmbeddedLoop->getBody();
2292     Continue = EmbeddedLoop->getLatch();
2293     OutroInsertBefore = EmbeddedLoop->getLatch();
2294     return EmbeddedLoop;
2295   };
2296 
2297   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
2298                                                   const Twine &NameBase) {
2299     for (auto P : enumerate(TripCounts)) {
2300       CanonicalLoopInfo *EmbeddedLoop =
2301           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
2302       Result.push_back(EmbeddedLoop);
2303     }
2304   };
2305 
2306   EmbeddNewLoops(FloorCount, "floor");
2307 
2308   // Within the innermost floor loop, emit the code that computes the tile
2309   // sizes.
2310   Builder.SetInsertPoint(Enter->getTerminator());
2311   SmallVector<Value *, 4> TileCounts;
2312   for (int i = 0; i < NumLoops; ++i) {
2313     CanonicalLoopInfo *FloorLoop = Result[i];
2314     Value *TileSize = TileSizes[i];
2315 
2316     Value *FloorIsEpilogue =
2317         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
2318     Value *TileTripCount =
2319         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
2320 
2321     TileCounts.push_back(TileTripCount);
2322   }
2323 
2324   // Create the tile loops.
2325   EmbeddNewLoops(TileCounts, "tile");
2326 
2327   // Insert the inbetween code into the body.
2328   BasicBlock *BodyEnter = Enter;
2329   BasicBlock *BodyEntered = nullptr;
2330   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
2331     BasicBlock *EnterBB = P.first;
2332     BasicBlock *ExitBB = P.second;
2333 
2334     if (BodyEnter)
2335       redirectTo(BodyEnter, EnterBB, DL);
2336     else
2337       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
2338 
2339     BodyEnter = nullptr;
2340     BodyEntered = ExitBB;
2341   }
2342 
2343   // Append the original loop nest body into the generated loop nest body.
2344   if (BodyEnter)
2345     redirectTo(BodyEnter, InnerEnter, DL);
2346   else
2347     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
2348   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
2349 
2350   // Replace the original induction variable with an induction variable computed
2351   // from the tile and floor induction variables.
2352   Builder.restoreIP(Result.back()->getBodyIP());
2353   for (int i = 0; i < NumLoops; ++i) {
2354     CanonicalLoopInfo *FloorLoop = Result[i];
2355     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
2356     Value *OrigIndVar = OrigIndVars[i];
2357     Value *Size = TileSizes[i];
2358 
2359     Value *Scale =
2360         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
2361     Value *Shift =
2362         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
2363     OrigIndVar->replaceAllUsesWith(Shift);
2364   }
2365 
2366   // Remove unused parts of the original loops.
2367   removeUnusedBlocksFromParent(OldControlBBs);
2368 
2369   for (CanonicalLoopInfo *L : Loops)
2370     L->invalidate();
2371 
2372 #ifndef NDEBUG
2373   for (CanonicalLoopInfo *GenL : Result)
2374     GenL->assertOK();
2375 #endif
2376   return Result;
2377 }
2378 
2379 /// Attach loop metadata \p Properties to the loop described by \p Loop. If the
2380 /// loop already has metadata, the loop properties are appended.
2381 static void addLoopMetadata(CanonicalLoopInfo *Loop,
2382                             ArrayRef<Metadata *> Properties) {
2383   assert(Loop->isValid() && "Expecting a valid CanonicalLoopInfo");
2384 
2385   // Nothing to do if no property to attach.
2386   if (Properties.empty())
2387     return;
2388 
2389   LLVMContext &Ctx = Loop->getFunction()->getContext();
2390   SmallVector<Metadata *> NewLoopProperties;
2391   NewLoopProperties.push_back(nullptr);
2392 
2393   // If the loop already has metadata, prepend it to the new metadata.
2394   BasicBlock *Latch = Loop->getLatch();
2395   assert(Latch && "A valid CanonicalLoopInfo must have a unique latch");
2396   MDNode *Existing = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
2397   if (Existing)
2398     append_range(NewLoopProperties, drop_begin(Existing->operands(), 1));
2399 
2400   append_range(NewLoopProperties, Properties);
2401   MDNode *LoopID = MDNode::getDistinct(Ctx, NewLoopProperties);
2402   LoopID->replaceOperandWith(0, LoopID);
2403 
2404   Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
2405 }
2406 
2407 /// Attach llvm.access.group metadata to the memref instructions of \p Block
2408 static void addSimdMetadata(BasicBlock *Block, MDNode *AccessGroup,
2409                             LoopInfo &LI) {
2410   for (Instruction &I : *Block) {
2411     if (I.mayReadOrWriteMemory()) {
2412       // TODO: This instruction may already have access group from
2413       // other pragmas e.g. #pragma clang loop vectorize.  Append
2414       // so that the existing metadata is not overwritten.
2415       I.setMetadata(LLVMContext::MD_access_group, AccessGroup);
2416     }
2417   }
2418 }
2419 
2420 void OpenMPIRBuilder::unrollLoopFull(DebugLoc, CanonicalLoopInfo *Loop) {
2421   LLVMContext &Ctx = Builder.getContext();
2422   addLoopMetadata(
2423       Loop, {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2424              MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.full"))});
2425 }
2426 
2427 void OpenMPIRBuilder::unrollLoopHeuristic(DebugLoc, CanonicalLoopInfo *Loop) {
2428   LLVMContext &Ctx = Builder.getContext();
2429   addLoopMetadata(
2430       Loop, {
2431                 MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2432             });
2433 }
2434 
2435 void OpenMPIRBuilder::applySimd(DebugLoc, CanonicalLoopInfo *CanonicalLoop) {
2436   LLVMContext &Ctx = Builder.getContext();
2437 
2438   Function *F = CanonicalLoop->getFunction();
2439 
2440   FunctionAnalysisManager FAM;
2441   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2442   FAM.registerPass([]() { return LoopAnalysis(); });
2443   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2444 
2445   LoopAnalysis LIA;
2446   LoopInfo &&LI = LIA.run(*F, FAM);
2447 
2448   Loop *L = LI.getLoopFor(CanonicalLoop->getHeader());
2449 
2450   SmallSet<BasicBlock *, 8> Reachable;
2451 
2452   // Get the basic blocks from the loop in which memref instructions
2453   // can be found.
2454   // TODO: Generalize getting all blocks inside a CanonicalizeLoopInfo,
2455   // preferably without running any passes.
2456   for (BasicBlock *Block : L->getBlocks()) {
2457     if (Block == CanonicalLoop->getCond() ||
2458         Block == CanonicalLoop->getHeader())
2459       continue;
2460     Reachable.insert(Block);
2461   }
2462 
2463   // Add access group metadata to memory-access instructions.
2464   MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
2465   for (BasicBlock *BB : Reachable)
2466     addSimdMetadata(BB, AccessGroup, LI);
2467 
2468   // Use the above access group metadata to create loop level
2469   // metadata, which should be distinct for each loop.
2470   ConstantAsMetadata *BoolConst =
2471       ConstantAsMetadata::get(ConstantInt::getTrue(Type::getInt1Ty(Ctx)));
2472   // TODO:  If the loop has existing parallel access metadata, have
2473   // to combine two lists.
2474   addLoopMetadata(
2475       CanonicalLoop,
2476       {MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.parallel_accesses"),
2477                          AccessGroup}),
2478        MDNode::get(Ctx, {MDString::get(Ctx, "llvm.loop.vectorize.enable"),
2479                          BoolConst})});
2480 }
2481 
2482 /// Create the TargetMachine object to query the backend for optimization
2483 /// preferences.
2484 ///
2485 /// Ideally, this would be passed from the front-end to the OpenMPBuilder, but
2486 /// e.g. Clang does not pass it to its CodeGen layer and creates it only when
2487 /// needed for the LLVM pass pipline. We use some default options to avoid
2488 /// having to pass too many settings from the frontend that probably do not
2489 /// matter.
2490 ///
2491 /// Currently, TargetMachine is only used sometimes by the unrollLoopPartial
2492 /// method. If we are going to use TargetMachine for more purposes, especially
2493 /// those that are sensitive to TargetOptions, RelocModel and CodeModel, it
2494 /// might become be worth requiring front-ends to pass on their TargetMachine,
2495 /// or at least cache it between methods. Note that while fontends such as Clang
2496 /// have just a single main TargetMachine per translation unit, "target-cpu" and
2497 /// "target-features" that determine the TargetMachine are per-function and can
2498 /// be overrided using __attribute__((target("OPTIONS"))).
2499 static std::unique_ptr<TargetMachine>
2500 createTargetMachine(Function *F, CodeGenOpt::Level OptLevel) {
2501   Module *M = F->getParent();
2502 
2503   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
2504   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
2505   const std::string &Triple = M->getTargetTriple();
2506 
2507   std::string Error;
2508   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
2509   if (!TheTarget)
2510     return {};
2511 
2512   llvm::TargetOptions Options;
2513   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
2514       Triple, CPU, Features, Options, /*RelocModel=*/None, /*CodeModel=*/None,
2515       OptLevel));
2516 }
2517 
2518 /// Heuristically determine the best-performant unroll factor for \p CLI. This
2519 /// depends on the target processor. We are re-using the same heuristics as the
2520 /// LoopUnrollPass.
2521 static int32_t computeHeuristicUnrollFactor(CanonicalLoopInfo *CLI) {
2522   Function *F = CLI->getFunction();
2523 
2524   // Assume the user requests the most aggressive unrolling, even if the rest of
2525   // the code is optimized using a lower setting.
2526   CodeGenOpt::Level OptLevel = CodeGenOpt::Aggressive;
2527   std::unique_ptr<TargetMachine> TM = createTargetMachine(F, OptLevel);
2528 
2529   FunctionAnalysisManager FAM;
2530   FAM.registerPass([]() { return TargetLibraryAnalysis(); });
2531   FAM.registerPass([]() { return AssumptionAnalysis(); });
2532   FAM.registerPass([]() { return DominatorTreeAnalysis(); });
2533   FAM.registerPass([]() { return LoopAnalysis(); });
2534   FAM.registerPass([]() { return ScalarEvolutionAnalysis(); });
2535   FAM.registerPass([]() { return PassInstrumentationAnalysis(); });
2536   TargetIRAnalysis TIRA;
2537   if (TM)
2538     TIRA = TargetIRAnalysis(
2539         [&](const Function &F) { return TM->getTargetTransformInfo(F); });
2540   FAM.registerPass([&]() { return TIRA; });
2541 
2542   TargetIRAnalysis::Result &&TTI = TIRA.run(*F, FAM);
2543   ScalarEvolutionAnalysis SEA;
2544   ScalarEvolution &&SE = SEA.run(*F, FAM);
2545   DominatorTreeAnalysis DTA;
2546   DominatorTree &&DT = DTA.run(*F, FAM);
2547   LoopAnalysis LIA;
2548   LoopInfo &&LI = LIA.run(*F, FAM);
2549   AssumptionAnalysis ACT;
2550   AssumptionCache &&AC = ACT.run(*F, FAM);
2551   OptimizationRemarkEmitter ORE{F};
2552 
2553   Loop *L = LI.getLoopFor(CLI->getHeader());
2554   assert(L && "Expecting CanonicalLoopInfo to be recognized as a loop");
2555 
2556   TargetTransformInfo::UnrollingPreferences UP =
2557       gatherUnrollingPreferences(L, SE, TTI,
2558                                  /*BlockFrequencyInfo=*/nullptr,
2559                                  /*ProfileSummaryInfo=*/nullptr, ORE, OptLevel,
2560                                  /*UserThreshold=*/None,
2561                                  /*UserCount=*/None,
2562                                  /*UserAllowPartial=*/true,
2563                                  /*UserAllowRuntime=*/true,
2564                                  /*UserUpperBound=*/None,
2565                                  /*UserFullUnrollMaxCount=*/None);
2566 
2567   UP.Force = true;
2568 
2569   // Account for additional optimizations taking place before the LoopUnrollPass
2570   // would unroll the loop.
2571   UP.Threshold *= UnrollThresholdFactor;
2572   UP.PartialThreshold *= UnrollThresholdFactor;
2573 
2574   // Use normal unroll factors even if the rest of the code is optimized for
2575   // size.
2576   UP.OptSizeThreshold = UP.Threshold;
2577   UP.PartialOptSizeThreshold = UP.PartialThreshold;
2578 
2579   LLVM_DEBUG(dbgs() << "Unroll heuristic thresholds:\n"
2580                     << "  Threshold=" << UP.Threshold << "\n"
2581                     << "  PartialThreshold=" << UP.PartialThreshold << "\n"
2582                     << "  OptSizeThreshold=" << UP.OptSizeThreshold << "\n"
2583                     << "  PartialOptSizeThreshold="
2584                     << UP.PartialOptSizeThreshold << "\n");
2585 
2586   // Disable peeling.
2587   TargetTransformInfo::PeelingPreferences PP =
2588       gatherPeelingPreferences(L, SE, TTI,
2589                                /*UserAllowPeeling=*/false,
2590                                /*UserAllowProfileBasedPeeling=*/false,
2591                                /*UnrollingSpecficValues=*/false);
2592 
2593   SmallPtrSet<const Value *, 32> EphValues;
2594   CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
2595 
2596   // Assume that reads and writes to stack variables can be eliminated by
2597   // Mem2Reg, SROA or LICM. That is, don't count them towards the loop body's
2598   // size.
2599   for (BasicBlock *BB : L->blocks()) {
2600     for (Instruction &I : *BB) {
2601       Value *Ptr;
2602       if (auto *Load = dyn_cast<LoadInst>(&I)) {
2603         Ptr = Load->getPointerOperand();
2604       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2605         Ptr = Store->getPointerOperand();
2606       } else
2607         continue;
2608 
2609       Ptr = Ptr->stripPointerCasts();
2610 
2611       if (auto *Alloca = dyn_cast<AllocaInst>(Ptr)) {
2612         if (Alloca->getParent() == &F->getEntryBlock())
2613           EphValues.insert(&I);
2614       }
2615     }
2616   }
2617 
2618   unsigned NumInlineCandidates;
2619   bool NotDuplicatable;
2620   bool Convergent;
2621   unsigned LoopSize =
2622       ApproximateLoopSize(L, NumInlineCandidates, NotDuplicatable, Convergent,
2623                           TTI, EphValues, UP.BEInsns);
2624   LLVM_DEBUG(dbgs() << "Estimated loop size is " << LoopSize << "\n");
2625 
2626   // Loop is not unrollable if the loop contains certain instructions.
2627   if (NotDuplicatable || Convergent) {
2628     LLVM_DEBUG(dbgs() << "Loop not considered unrollable\n");
2629     return 1;
2630   }
2631 
2632   // TODO: Determine trip count of \p CLI if constant, computeUnrollCount might
2633   // be able to use it.
2634   int TripCount = 0;
2635   int MaxTripCount = 0;
2636   bool MaxOrZero = false;
2637   unsigned TripMultiple = 0;
2638 
2639   bool UseUpperBound = false;
2640   computeUnrollCount(L, TTI, DT, &LI, SE, EphValues, &ORE, TripCount,
2641                      MaxTripCount, MaxOrZero, TripMultiple, LoopSize, UP, PP,
2642                      UseUpperBound);
2643   unsigned Factor = UP.Count;
2644   LLVM_DEBUG(dbgs() << "Suggesting unroll factor of " << Factor << "\n");
2645 
2646   // This function returns 1 to signal to not unroll a loop.
2647   if (Factor == 0)
2648     return 1;
2649   return Factor;
2650 }
2651 
2652 void OpenMPIRBuilder::unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop,
2653                                         int32_t Factor,
2654                                         CanonicalLoopInfo **UnrolledCLI) {
2655   assert(Factor >= 0 && "Unroll factor must not be negative");
2656 
2657   Function *F = Loop->getFunction();
2658   LLVMContext &Ctx = F->getContext();
2659 
2660   // If the unrolled loop is not used for another loop-associated directive, it
2661   // is sufficient to add metadata for the LoopUnrollPass.
2662   if (!UnrolledCLI) {
2663     SmallVector<Metadata *, 2> LoopMetadata;
2664     LoopMetadata.push_back(
2665         MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")));
2666 
2667     if (Factor >= 1) {
2668       ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
2669           ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
2670       LoopMetadata.push_back(MDNode::get(
2671           Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst}));
2672     }
2673 
2674     addLoopMetadata(Loop, LoopMetadata);
2675     return;
2676   }
2677 
2678   // Heuristically determine the unroll factor.
2679   if (Factor == 0)
2680     Factor = computeHeuristicUnrollFactor(Loop);
2681 
2682   // No change required with unroll factor 1.
2683   if (Factor == 1) {
2684     *UnrolledCLI = Loop;
2685     return;
2686   }
2687 
2688   assert(Factor >= 2 &&
2689          "unrolling only makes sense with a factor of 2 or larger");
2690 
2691   Type *IndVarTy = Loop->getIndVarType();
2692 
2693   // Apply partial unrolling by tiling the loop by the unroll-factor, then fully
2694   // unroll the inner loop.
2695   Value *FactorVal =
2696       ConstantInt::get(IndVarTy, APInt(IndVarTy->getIntegerBitWidth(), Factor,
2697                                        /*isSigned=*/false));
2698   std::vector<CanonicalLoopInfo *> LoopNest =
2699       tileLoops(DL, {Loop}, {FactorVal});
2700   assert(LoopNest.size() == 2 && "Expect 2 loops after tiling");
2701   *UnrolledCLI = LoopNest[0];
2702   CanonicalLoopInfo *InnerLoop = LoopNest[1];
2703 
2704   // LoopUnrollPass can only fully unroll loops with constant trip count.
2705   // Unroll by the unroll factor with a fallback epilog for the remainder
2706   // iterations if necessary.
2707   ConstantAsMetadata *FactorConst = ConstantAsMetadata::get(
2708       ConstantInt::get(Type::getInt32Ty(Ctx), APInt(32, Factor)));
2709   addLoopMetadata(
2710       InnerLoop,
2711       {MDNode::get(Ctx, MDString::get(Ctx, "llvm.loop.unroll.enable")),
2712        MDNode::get(
2713            Ctx, {MDString::get(Ctx, "llvm.loop.unroll.count"), FactorConst})});
2714 
2715 #ifndef NDEBUG
2716   (*UnrolledCLI)->assertOK();
2717 #endif
2718 }
2719 
2720 OpenMPIRBuilder::InsertPointTy
2721 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
2722                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
2723                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
2724   if (!updateToLocation(Loc))
2725     return Loc.IP;
2726 
2727   uint32_t SrcLocStrSize;
2728   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2729   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2730   Value *ThreadId = getOrCreateThreadID(Ident);
2731 
2732   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
2733 
2734   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
2735 
2736   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
2737   Builder.CreateCall(Fn, Args);
2738 
2739   return Builder.saveIP();
2740 }
2741 
2742 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createSingle(
2743     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2744     FinalizeCallbackTy FiniCB, bool IsNowait, llvm::Value *DidIt) {
2745 
2746   if (!updateToLocation(Loc))
2747     return Loc.IP;
2748 
2749   // If needed (i.e. not null), initialize `DidIt` with 0
2750   if (DidIt) {
2751     Builder.CreateStore(Builder.getInt32(0), DidIt);
2752   }
2753 
2754   Directive OMPD = Directive::OMPD_single;
2755   uint32_t SrcLocStrSize;
2756   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2757   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2758   Value *ThreadId = getOrCreateThreadID(Ident);
2759   Value *Args[] = {Ident, ThreadId};
2760 
2761   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
2762   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2763 
2764   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
2765   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2766 
2767   // generates the following:
2768   // if (__kmpc_single()) {
2769   //		.... single region ...
2770   // 		__kmpc_end_single
2771   // }
2772   // __kmpc_barrier
2773 
2774   EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2775                        /*Conditional*/ true,
2776                        /*hasFinalize*/ true);
2777   if (!IsNowait)
2778     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
2779                   omp::Directive::OMPD_unknown, /* ForceSimpleCall */ false,
2780                   /* CheckCancelFlag */ false);
2781   return Builder.saveIP();
2782 }
2783 
2784 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
2785     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2786     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
2787 
2788   if (!updateToLocation(Loc))
2789     return Loc.IP;
2790 
2791   Directive OMPD = Directive::OMPD_critical;
2792   uint32_t SrcLocStrSize;
2793   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2794   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2795   Value *ThreadId = getOrCreateThreadID(Ident);
2796   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
2797   Value *Args[] = {Ident, ThreadId, LockVar};
2798 
2799   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
2800   Function *RTFn = nullptr;
2801   if (HintInst) {
2802     // Add Hint to entry Args and create call
2803     EnterArgs.push_back(HintInst);
2804     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
2805   } else {
2806     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
2807   }
2808   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
2809 
2810   Function *ExitRTLFn =
2811       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
2812   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2813 
2814   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2815                               /*Conditional*/ false, /*hasFinalize*/ true);
2816 }
2817 
2818 OpenMPIRBuilder::InsertPointTy
2819 OpenMPIRBuilder::createOrderedDepend(const LocationDescription &Loc,
2820                                      InsertPointTy AllocaIP, unsigned NumLoops,
2821                                      ArrayRef<llvm::Value *> StoreValues,
2822                                      const Twine &Name, bool IsDependSource) {
2823   for (size_t I = 0; I < StoreValues.size(); I++)
2824     assert(StoreValues[I]->getType()->isIntegerTy(64) &&
2825            "OpenMP runtime requires depend vec with i64 type");
2826 
2827   if (!updateToLocation(Loc))
2828     return Loc.IP;
2829 
2830   // Allocate space for vector and generate alloc instruction.
2831   auto *ArrI64Ty = ArrayType::get(Int64, NumLoops);
2832   Builder.restoreIP(AllocaIP);
2833   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI64Ty, nullptr, Name);
2834   ArgsBase->setAlignment(Align(8));
2835   Builder.restoreIP(Loc.IP);
2836 
2837   // Store the index value with offset in depend vector.
2838   for (unsigned I = 0; I < NumLoops; ++I) {
2839     Value *DependAddrGEPIter = Builder.CreateInBoundsGEP(
2840         ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(I)});
2841     StoreInst *STInst = Builder.CreateStore(StoreValues[I], DependAddrGEPIter);
2842     STInst->setAlignment(Align(8));
2843   }
2844 
2845   Value *DependBaseAddrGEP = Builder.CreateInBoundsGEP(
2846       ArrI64Ty, ArgsBase, {Builder.getInt64(0), Builder.getInt64(0)});
2847 
2848   uint32_t SrcLocStrSize;
2849   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2850   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2851   Value *ThreadId = getOrCreateThreadID(Ident);
2852   Value *Args[] = {Ident, ThreadId, DependBaseAddrGEP};
2853 
2854   Function *RTLFn = nullptr;
2855   if (IsDependSource)
2856     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_post);
2857   else
2858     RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_doacross_wait);
2859   Builder.CreateCall(RTLFn, Args);
2860 
2861   return Builder.saveIP();
2862 }
2863 
2864 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createOrderedThreadsSimd(
2865     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
2866     FinalizeCallbackTy FiniCB, bool IsThreads) {
2867   if (!updateToLocation(Loc))
2868     return Loc.IP;
2869 
2870   Directive OMPD = Directive::OMPD_ordered;
2871   Instruction *EntryCall = nullptr;
2872   Instruction *ExitCall = nullptr;
2873 
2874   if (IsThreads) {
2875     uint32_t SrcLocStrSize;
2876     Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
2877     Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
2878     Value *ThreadId = getOrCreateThreadID(Ident);
2879     Value *Args[] = {Ident, ThreadId};
2880 
2881     Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_ordered);
2882     EntryCall = Builder.CreateCall(EntryRTLFn, Args);
2883 
2884     Function *ExitRTLFn =
2885         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_ordered);
2886     ExitCall = Builder.CreateCall(ExitRTLFn, Args);
2887   }
2888 
2889   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
2890                               /*Conditional*/ false, /*hasFinalize*/ true);
2891 }
2892 
2893 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
2894     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
2895     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
2896     bool HasFinalize, bool IsCancellable) {
2897 
2898   if (HasFinalize)
2899     FinalizationStack.push_back({FiniCB, OMPD, IsCancellable});
2900 
2901   // Create inlined region's entry and body blocks, in preparation
2902   // for conditional creation
2903   BasicBlock *EntryBB = Builder.GetInsertBlock();
2904   Instruction *SplitPos = EntryBB->getTerminator();
2905   if (!isa_and_nonnull<BranchInst>(SplitPos))
2906     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
2907   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
2908   BasicBlock *FiniBB =
2909       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
2910 
2911   Builder.SetInsertPoint(EntryBB->getTerminator());
2912   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
2913 
2914   // generate body
2915   BodyGenCB(/* AllocaIP */ InsertPointTy(),
2916             /* CodeGenIP */ Builder.saveIP(), *FiniBB);
2917 
2918   // If we didn't emit a branch to FiniBB during body generation, it means
2919   // FiniBB is unreachable (e.g. while(1);). stop generating all the
2920   // unreachable blocks, and remove anything we are not going to use.
2921   auto SkipEmittingRegion = FiniBB->hasNPredecessors(0);
2922   if (SkipEmittingRegion) {
2923     FiniBB->eraseFromParent();
2924     ExitCall->eraseFromParent();
2925     // Discard finalization if we have it.
2926     if (HasFinalize) {
2927       assert(!FinalizationStack.empty() &&
2928              "Unexpected finalization stack state!");
2929       FinalizationStack.pop_back();
2930     }
2931   } else {
2932     // emit exit call and do any needed finalization.
2933     auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
2934     assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
2935            FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
2936            "Unexpected control flow graph state!!");
2937     emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
2938     assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
2939            "Unexpected Control Flow State!");
2940     MergeBlockIntoPredecessor(FiniBB);
2941   }
2942 
2943   // If we are skipping the region of a non conditional, remove the exit
2944   // block, and clear the builder's insertion point.
2945   assert(SplitPos->getParent() == ExitBB &&
2946          "Unexpected Insertion point location!");
2947   if (!Conditional && SkipEmittingRegion) {
2948     ExitBB->eraseFromParent();
2949     Builder.ClearInsertionPoint();
2950   } else {
2951     auto merged = MergeBlockIntoPredecessor(ExitBB);
2952     BasicBlock *ExitPredBB = SplitPos->getParent();
2953     auto InsertBB = merged ? ExitPredBB : ExitBB;
2954     if (!isa_and_nonnull<BranchInst>(SplitPos))
2955       SplitPos->eraseFromParent();
2956     Builder.SetInsertPoint(InsertBB);
2957   }
2958 
2959   return Builder.saveIP();
2960 }
2961 
2962 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
2963     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
2964   // if nothing to do, Return current insertion point.
2965   if (!Conditional || !EntryCall)
2966     return Builder.saveIP();
2967 
2968   BasicBlock *EntryBB = Builder.GetInsertBlock();
2969   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
2970   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
2971   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
2972 
2973   // Emit thenBB and set the Builder's insertion point there for
2974   // body generation next. Place the block after the current block.
2975   Function *CurFn = EntryBB->getParent();
2976   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
2977 
2978   // Move Entry branch to end of ThenBB, and replace with conditional
2979   // branch (If-stmt)
2980   Instruction *EntryBBTI = EntryBB->getTerminator();
2981   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
2982   EntryBBTI->removeFromParent();
2983   Builder.SetInsertPoint(UI);
2984   Builder.Insert(EntryBBTI);
2985   UI->eraseFromParent();
2986   Builder.SetInsertPoint(ThenBB->getTerminator());
2987 
2988   // return an insertion point to ExitBB.
2989   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
2990 }
2991 
2992 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
2993     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
2994     bool HasFinalize) {
2995 
2996   Builder.restoreIP(FinIP);
2997 
2998   // If there is finalization to do, emit it before the exit call
2999   if (HasFinalize) {
3000     assert(!FinalizationStack.empty() &&
3001            "Unexpected finalization stack state!");
3002 
3003     FinalizationInfo Fi = FinalizationStack.pop_back_val();
3004     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
3005 
3006     Fi.FiniCB(FinIP);
3007 
3008     BasicBlock *FiniBB = FinIP.getBlock();
3009     Instruction *FiniBBTI = FiniBB->getTerminator();
3010 
3011     // set Builder IP for call creation
3012     Builder.SetInsertPoint(FiniBBTI);
3013   }
3014 
3015   if (!ExitCall)
3016     return Builder.saveIP();
3017 
3018   // place the Exitcall as last instruction before Finalization block terminator
3019   ExitCall->removeFromParent();
3020   Builder.Insert(ExitCall);
3021 
3022   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
3023                                   ExitCall->getIterator());
3024 }
3025 
3026 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
3027     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
3028     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
3029   if (!IP.isSet())
3030     return IP;
3031 
3032   IRBuilder<>::InsertPointGuard IPG(Builder);
3033 
3034   // creates the following CFG structure
3035   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
3036   //       F     T
3037   //       |      \
3038   //       |     copin.not.master
3039   //       |      /
3040   //       v     /
3041   //   copyin.not.master.end
3042   //		     |
3043   //         v
3044   //   OMP.Entry.Next
3045 
3046   BasicBlock *OMP_Entry = IP.getBlock();
3047   Function *CurFn = OMP_Entry->getParent();
3048   BasicBlock *CopyBegin =
3049       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
3050   BasicBlock *CopyEnd = nullptr;
3051 
3052   // If entry block is terminated, split to preserve the branch to following
3053   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
3054   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
3055     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
3056                                          "copyin.not.master.end");
3057     OMP_Entry->getTerminator()->eraseFromParent();
3058   } else {
3059     CopyEnd =
3060         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
3061   }
3062 
3063   Builder.SetInsertPoint(OMP_Entry);
3064   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
3065   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
3066   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
3067   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
3068 
3069   Builder.SetInsertPoint(CopyBegin);
3070   if (BranchtoEnd)
3071     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
3072 
3073   return Builder.saveIP();
3074 }
3075 
3076 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
3077                                           Value *Size, Value *Allocator,
3078                                           std::string Name) {
3079   IRBuilder<>::InsertPointGuard IPG(Builder);
3080   Builder.restoreIP(Loc.IP);
3081 
3082   uint32_t SrcLocStrSize;
3083   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3084   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3085   Value *ThreadId = getOrCreateThreadID(Ident);
3086   Value *Args[] = {ThreadId, Size, Allocator};
3087 
3088   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
3089 
3090   return Builder.CreateCall(Fn, Args, Name);
3091 }
3092 
3093 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
3094                                          Value *Addr, Value *Allocator,
3095                                          std::string Name) {
3096   IRBuilder<>::InsertPointGuard IPG(Builder);
3097   Builder.restoreIP(Loc.IP);
3098 
3099   uint32_t SrcLocStrSize;
3100   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3101   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3102   Value *ThreadId = getOrCreateThreadID(Ident);
3103   Value *Args[] = {ThreadId, Addr, Allocator};
3104   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
3105   return Builder.CreateCall(Fn, Args, Name);
3106 }
3107 
3108 CallInst *OpenMPIRBuilder::createOMPInteropInit(
3109     const LocationDescription &Loc, Value *InteropVar,
3110     omp::OMPInteropType InteropType, Value *Device, Value *NumDependences,
3111     Value *DependenceAddress, bool HaveNowaitClause) {
3112   IRBuilder<>::InsertPointGuard IPG(Builder);
3113   Builder.restoreIP(Loc.IP);
3114 
3115   uint32_t SrcLocStrSize;
3116   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3117   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3118   Value *ThreadId = getOrCreateThreadID(Ident);
3119   if (Device == nullptr)
3120     Device = ConstantInt::get(Int32, -1);
3121   Constant *InteropTypeVal = ConstantInt::get(Int64, (int)InteropType);
3122   if (NumDependences == nullptr) {
3123     NumDependences = ConstantInt::get(Int32, 0);
3124     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3125     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3126   }
3127   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3128   Value *Args[] = {
3129       Ident,  ThreadId,       InteropVar,        InteropTypeVal,
3130       Device, NumDependences, DependenceAddress, HaveNowaitClauseVal};
3131 
3132   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_init);
3133 
3134   return Builder.CreateCall(Fn, Args);
3135 }
3136 
3137 CallInst *OpenMPIRBuilder::createOMPInteropDestroy(
3138     const LocationDescription &Loc, Value *InteropVar, Value *Device,
3139     Value *NumDependences, Value *DependenceAddress, bool HaveNowaitClause) {
3140   IRBuilder<>::InsertPointGuard IPG(Builder);
3141   Builder.restoreIP(Loc.IP);
3142 
3143   uint32_t SrcLocStrSize;
3144   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3145   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3146   Value *ThreadId = getOrCreateThreadID(Ident);
3147   if (Device == nullptr)
3148     Device = ConstantInt::get(Int32, -1);
3149   if (NumDependences == nullptr) {
3150     NumDependences = ConstantInt::get(Int32, 0);
3151     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3152     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3153   }
3154   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3155   Value *Args[] = {
3156       Ident,          ThreadId,          InteropVar,         Device,
3157       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3158 
3159   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_destroy);
3160 
3161   return Builder.CreateCall(Fn, Args);
3162 }
3163 
3164 CallInst *OpenMPIRBuilder::createOMPInteropUse(const LocationDescription &Loc,
3165                                                Value *InteropVar, Value *Device,
3166                                                Value *NumDependences,
3167                                                Value *DependenceAddress,
3168                                                bool HaveNowaitClause) {
3169   IRBuilder<>::InsertPointGuard IPG(Builder);
3170   Builder.restoreIP(Loc.IP);
3171   uint32_t SrcLocStrSize;
3172   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3173   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3174   Value *ThreadId = getOrCreateThreadID(Ident);
3175   if (Device == nullptr)
3176     Device = ConstantInt::get(Int32, -1);
3177   if (NumDependences == nullptr) {
3178     NumDependences = ConstantInt::get(Int32, 0);
3179     PointerType *PointerTypeVar = Type::getInt8PtrTy(M.getContext());
3180     DependenceAddress = ConstantPointerNull::get(PointerTypeVar);
3181   }
3182   Value *HaveNowaitClauseVal = ConstantInt::get(Int32, HaveNowaitClause);
3183   Value *Args[] = {
3184       Ident,          ThreadId,          InteropVar,         Device,
3185       NumDependences, DependenceAddress, HaveNowaitClauseVal};
3186 
3187   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___tgt_interop_use);
3188 
3189   return Builder.CreateCall(Fn, Args);
3190 }
3191 
3192 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
3193     const LocationDescription &Loc, llvm::Value *Pointer,
3194     llvm::ConstantInt *Size, const llvm::Twine &Name) {
3195   IRBuilder<>::InsertPointGuard IPG(Builder);
3196   Builder.restoreIP(Loc.IP);
3197 
3198   uint32_t SrcLocStrSize;
3199   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3200   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3201   Value *ThreadId = getOrCreateThreadID(Ident);
3202   Constant *ThreadPrivateCache =
3203       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
3204   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
3205 
3206   Function *Fn =
3207       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
3208 
3209   return Builder.CreateCall(Fn, Args);
3210 }
3211 
3212 OpenMPIRBuilder::InsertPointTy
3213 OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
3214                                   bool RequiresFullRuntime) {
3215   if (!updateToLocation(Loc))
3216     return Loc.IP;
3217 
3218   uint32_t SrcLocStrSize;
3219   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3220   Constant *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3221   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3222       IntegerType::getInt8Ty(Int8->getContext()),
3223       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3224   ConstantInt *UseGenericStateMachine =
3225       ConstantInt::getBool(Int32->getContext(), !IsSPMD);
3226   ConstantInt *RequiresFullRuntimeVal =
3227       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3228 
3229   Function *Fn = getOrCreateRuntimeFunctionPtr(
3230       omp::RuntimeFunction::OMPRTL___kmpc_target_init);
3231 
3232   CallInst *ThreadKind = Builder.CreateCall(
3233       Fn, {Ident, IsSPMDVal, UseGenericStateMachine, RequiresFullRuntimeVal});
3234 
3235   Value *ExecUserCode = Builder.CreateICmpEQ(
3236       ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
3237       "exec_user_code");
3238 
3239   // ThreadKind = __kmpc_target_init(...)
3240   // if (ThreadKind == -1)
3241   //   user_code
3242   // else
3243   //   return;
3244 
3245   auto *UI = Builder.CreateUnreachable();
3246   BasicBlock *CheckBB = UI->getParent();
3247   BasicBlock *UserCodeEntryBB = CheckBB->splitBasicBlock(UI, "user_code.entry");
3248 
3249   BasicBlock *WorkerExitBB = BasicBlock::Create(
3250       CheckBB->getContext(), "worker.exit", CheckBB->getParent());
3251   Builder.SetInsertPoint(WorkerExitBB);
3252   Builder.CreateRetVoid();
3253 
3254   auto *CheckBBTI = CheckBB->getTerminator();
3255   Builder.SetInsertPoint(CheckBBTI);
3256   Builder.CreateCondBr(ExecUserCode, UI->getParent(), WorkerExitBB);
3257 
3258   CheckBBTI->eraseFromParent();
3259   UI->eraseFromParent();
3260 
3261   // Continue in the "user_code" block, see diagram above and in
3262   // openmp/libomptarget/deviceRTLs/common/include/target.h .
3263   return InsertPointTy(UserCodeEntryBB, UserCodeEntryBB->getFirstInsertionPt());
3264 }
3265 
3266 void OpenMPIRBuilder::createTargetDeinit(const LocationDescription &Loc,
3267                                          bool IsSPMD,
3268                                          bool RequiresFullRuntime) {
3269   if (!updateToLocation(Loc))
3270     return;
3271 
3272   uint32_t SrcLocStrSize;
3273   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
3274   Value *Ident = getOrCreateIdent(SrcLocStr, SrcLocStrSize);
3275   ConstantInt *IsSPMDVal = ConstantInt::getSigned(
3276       IntegerType::getInt8Ty(Int8->getContext()),
3277       IsSPMD ? OMP_TGT_EXEC_MODE_SPMD : OMP_TGT_EXEC_MODE_GENERIC);
3278   ConstantInt *RequiresFullRuntimeVal =
3279       ConstantInt::getBool(Int32->getContext(), RequiresFullRuntime);
3280 
3281   Function *Fn = getOrCreateRuntimeFunctionPtr(
3282       omp::RuntimeFunction::OMPRTL___kmpc_target_deinit);
3283 
3284   Builder.CreateCall(Fn, {Ident, IsSPMDVal, RequiresFullRuntimeVal});
3285 }
3286 
3287 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
3288                                                    StringRef FirstSeparator,
3289                                                    StringRef Separator) {
3290   SmallString<128> Buffer;
3291   llvm::raw_svector_ostream OS(Buffer);
3292   StringRef Sep = FirstSeparator;
3293   for (StringRef Part : Parts) {
3294     OS << Sep << Part;
3295     Sep = Separator;
3296   }
3297   return OS.str().str();
3298 }
3299 
3300 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
3301     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
3302   // TODO: Replace the twine arg with stringref to get rid of the conversion
3303   // logic. However This is taken from current implementation in clang as is.
3304   // Since this method is used in many places exclusively for OMP internal use
3305   // we will keep it as is for temporarily until we move all users to the
3306   // builder and then, if possible, fix it everywhere in one go.
3307   SmallString<256> Buffer;
3308   llvm::raw_svector_ostream Out(Buffer);
3309   Out << Name;
3310   StringRef RuntimeName = Out.str();
3311   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
3312   if (Elem.second) {
3313     assert(cast<PointerType>(Elem.second->getType())
3314                ->isOpaqueOrPointeeTypeMatches(Ty) &&
3315            "OMP internal variable has different type than requested");
3316   } else {
3317     // TODO: investigate the appropriate linkage type used for the global
3318     // variable for possibly changing that to internal or private, or maybe
3319     // create different versions of the function for different OMP internal
3320     // variables.
3321     Elem.second = new llvm::GlobalVariable(
3322         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
3323         llvm::Constant::getNullValue(Ty), Elem.first(),
3324         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3325         AddressSpace);
3326   }
3327 
3328   return Elem.second;
3329 }
3330 
3331 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
3332   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
3333   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
3334   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
3335 }
3336 
3337 GlobalVariable *
3338 OpenMPIRBuilder::createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
3339                                        std::string VarName) {
3340   llvm::Constant *MaptypesArrayInit =
3341       llvm::ConstantDataArray::get(M.getContext(), Mappings);
3342   auto *MaptypesArrayGlobal = new llvm::GlobalVariable(
3343       M, MaptypesArrayInit->getType(),
3344       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MaptypesArrayInit,
3345       VarName);
3346   MaptypesArrayGlobal->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3347   return MaptypesArrayGlobal;
3348 }
3349 
3350 void OpenMPIRBuilder::createMapperAllocas(const LocationDescription &Loc,
3351                                           InsertPointTy AllocaIP,
3352                                           unsigned NumOperands,
3353                                           struct MapperAllocas &MapperAllocas) {
3354   if (!updateToLocation(Loc))
3355     return;
3356 
3357   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3358   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3359   Builder.restoreIP(AllocaIP);
3360   AllocaInst *ArgsBase = Builder.CreateAlloca(ArrI8PtrTy);
3361   AllocaInst *Args = Builder.CreateAlloca(ArrI8PtrTy);
3362   AllocaInst *ArgSizes = Builder.CreateAlloca(ArrI64Ty);
3363   Builder.restoreIP(Loc.IP);
3364   MapperAllocas.ArgsBase = ArgsBase;
3365   MapperAllocas.Args = Args;
3366   MapperAllocas.ArgSizes = ArgSizes;
3367 }
3368 
3369 void OpenMPIRBuilder::emitMapperCall(const LocationDescription &Loc,
3370                                      Function *MapperFunc, Value *SrcLocInfo,
3371                                      Value *MaptypesArg, Value *MapnamesArg,
3372                                      struct MapperAllocas &MapperAllocas,
3373                                      int64_t DeviceID, unsigned NumOperands) {
3374   if (!updateToLocation(Loc))
3375     return;
3376 
3377   auto *ArrI8PtrTy = ArrayType::get(Int8Ptr, NumOperands);
3378   auto *ArrI64Ty = ArrayType::get(Int64, NumOperands);
3379   Value *ArgsBaseGEP =
3380       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.ArgsBase,
3381                                 {Builder.getInt32(0), Builder.getInt32(0)});
3382   Value *ArgsGEP =
3383       Builder.CreateInBoundsGEP(ArrI8PtrTy, MapperAllocas.Args,
3384                                 {Builder.getInt32(0), Builder.getInt32(0)});
3385   Value *ArgSizesGEP =
3386       Builder.CreateInBoundsGEP(ArrI64Ty, MapperAllocas.ArgSizes,
3387                                 {Builder.getInt32(0), Builder.getInt32(0)});
3388   Value *NullPtr = Constant::getNullValue(Int8Ptr->getPointerTo());
3389   Builder.CreateCall(MapperFunc,
3390                      {SrcLocInfo, Builder.getInt64(DeviceID),
3391                       Builder.getInt32(NumOperands), ArgsBaseGEP, ArgsGEP,
3392                       ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
3393 }
3394 
3395 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
3396     const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
3397   assert(!(AO == AtomicOrdering::NotAtomic ||
3398            AO == llvm::AtomicOrdering::Unordered) &&
3399          "Unexpected Atomic Ordering.");
3400 
3401   bool Flush = false;
3402   llvm::AtomicOrdering FlushAO = AtomicOrdering::Monotonic;
3403 
3404   switch (AK) {
3405   case Read:
3406     if (AO == AtomicOrdering::Acquire || AO == AtomicOrdering::AcquireRelease ||
3407         AO == AtomicOrdering::SequentiallyConsistent) {
3408       FlushAO = AtomicOrdering::Acquire;
3409       Flush = true;
3410     }
3411     break;
3412   case Write:
3413   case Compare:
3414   case Update:
3415     if (AO == AtomicOrdering::Release || AO == AtomicOrdering::AcquireRelease ||
3416         AO == AtomicOrdering::SequentiallyConsistent) {
3417       FlushAO = AtomicOrdering::Release;
3418       Flush = true;
3419     }
3420     break;
3421   case Capture:
3422     switch (AO) {
3423     case AtomicOrdering::Acquire:
3424       FlushAO = AtomicOrdering::Acquire;
3425       Flush = true;
3426       break;
3427     case AtomicOrdering::Release:
3428       FlushAO = AtomicOrdering::Release;
3429       Flush = true;
3430       break;
3431     case AtomicOrdering::AcquireRelease:
3432     case AtomicOrdering::SequentiallyConsistent:
3433       FlushAO = AtomicOrdering::AcquireRelease;
3434       Flush = true;
3435       break;
3436     default:
3437       // do nothing - leave silently.
3438       break;
3439     }
3440   }
3441 
3442   if (Flush) {
3443     // Currently Flush RT call still doesn't take memory_ordering, so for when
3444     // that happens, this tries to do the resolution of which atomic ordering
3445     // to use with but issue the flush call
3446     // TODO: pass `FlushAO` after memory ordering support is added
3447     (void)FlushAO;
3448     emitFlush(Loc);
3449   }
3450 
3451   // for AO == AtomicOrdering::Monotonic and  all other case combinations
3452   // do nothing
3453   return Flush;
3454 }
3455 
3456 OpenMPIRBuilder::InsertPointTy
3457 OpenMPIRBuilder::createAtomicRead(const LocationDescription &Loc,
3458                                   AtomicOpValue &X, AtomicOpValue &V,
3459                                   AtomicOrdering AO) {
3460   if (!updateToLocation(Loc))
3461     return Loc.IP;
3462 
3463   Type *XTy = X.Var->getType();
3464   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3465   Type *XElemTy = X.ElemTy;
3466   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3467           XElemTy->isPointerTy()) &&
3468          "OMP atomic read expected a scalar type");
3469 
3470   Value *XRead = nullptr;
3471 
3472   if (XElemTy->isIntegerTy()) {
3473     LoadInst *XLD =
3474         Builder.CreateLoad(XElemTy, X.Var, X.IsVolatile, "omp.atomic.read");
3475     XLD->setAtomic(AO);
3476     XRead = cast<Value>(XLD);
3477   } else {
3478     // We need to bitcast and perform atomic op as integer
3479     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3480     IntegerType *IntCastTy =
3481         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3482     Value *XBCast = Builder.CreateBitCast(
3483         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.src.int.cast");
3484     LoadInst *XLoad =
3485         Builder.CreateLoad(IntCastTy, XBCast, X.IsVolatile, "omp.atomic.load");
3486     XLoad->setAtomic(AO);
3487     if (XElemTy->isFloatingPointTy()) {
3488       XRead = Builder.CreateBitCast(XLoad, XElemTy, "atomic.flt.cast");
3489     } else {
3490       XRead = Builder.CreateIntToPtr(XLoad, XElemTy, "atomic.ptr.cast");
3491     }
3492   }
3493   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Read);
3494   Builder.CreateStore(XRead, V.Var, V.IsVolatile);
3495   return Builder.saveIP();
3496 }
3497 
3498 OpenMPIRBuilder::InsertPointTy
3499 OpenMPIRBuilder::createAtomicWrite(const LocationDescription &Loc,
3500                                    AtomicOpValue &X, Value *Expr,
3501                                    AtomicOrdering AO) {
3502   if (!updateToLocation(Loc))
3503     return Loc.IP;
3504 
3505   Type *XTy = X.Var->getType();
3506   assert(XTy->isPointerTy() && "OMP Atomic expects a pointer to target memory");
3507   Type *XElemTy = X.ElemTy;
3508   assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3509           XElemTy->isPointerTy()) &&
3510          "OMP atomic write expected a scalar type");
3511 
3512   if (XElemTy->isIntegerTy()) {
3513     StoreInst *XSt = Builder.CreateStore(Expr, X.Var, X.IsVolatile);
3514     XSt->setAtomic(AO);
3515   } else {
3516     // We need to bitcast and perform atomic op as integers
3517     unsigned Addrspace = cast<PointerType>(XTy)->getAddressSpace();
3518     IntegerType *IntCastTy =
3519         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3520     Value *XBCast = Builder.CreateBitCast(
3521         X.Var, IntCastTy->getPointerTo(Addrspace), "atomic.dst.int.cast");
3522     Value *ExprCast =
3523         Builder.CreateBitCast(Expr, IntCastTy, "atomic.src.int.cast");
3524     StoreInst *XSt = Builder.CreateStore(ExprCast, XBCast, X.IsVolatile);
3525     XSt->setAtomic(AO);
3526   }
3527 
3528   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Write);
3529   return Builder.saveIP();
3530 }
3531 
3532 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicUpdate(
3533     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3534     Value *Expr, AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3535     AtomicUpdateCallbackTy &UpdateOp, bool IsXBinopExpr) {
3536   assert(!isConflictIP(Loc.IP, AllocaIP) && "IPs must not be ambiguous");
3537   if (!updateToLocation(Loc))
3538     return Loc.IP;
3539 
3540   LLVM_DEBUG({
3541     Type *XTy = X.Var->getType();
3542     assert(XTy->isPointerTy() &&
3543            "OMP Atomic expects a pointer to target memory");
3544     Type *XElemTy = X.ElemTy;
3545     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3546             XElemTy->isPointerTy()) &&
3547            "OMP atomic update expected a scalar type");
3548     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3549            (RMWOp != AtomicRMWInst::UMax) && (RMWOp != AtomicRMWInst::UMin) &&
3550            "OpenMP atomic does not support LT or GT operations");
3551   });
3552 
3553   emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, RMWOp, UpdateOp,
3554                    X.IsVolatile, IsXBinopExpr);
3555   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Update);
3556   return Builder.saveIP();
3557 }
3558 
3559 Value *OpenMPIRBuilder::emitRMWOpAsInstruction(Value *Src1, Value *Src2,
3560                                                AtomicRMWInst::BinOp RMWOp) {
3561   switch (RMWOp) {
3562   case AtomicRMWInst::Add:
3563     return Builder.CreateAdd(Src1, Src2);
3564   case AtomicRMWInst::Sub:
3565     return Builder.CreateSub(Src1, Src2);
3566   case AtomicRMWInst::And:
3567     return Builder.CreateAnd(Src1, Src2);
3568   case AtomicRMWInst::Nand:
3569     return Builder.CreateNeg(Builder.CreateAnd(Src1, Src2));
3570   case AtomicRMWInst::Or:
3571     return Builder.CreateOr(Src1, Src2);
3572   case AtomicRMWInst::Xor:
3573     return Builder.CreateXor(Src1, Src2);
3574   case AtomicRMWInst::Xchg:
3575   case AtomicRMWInst::FAdd:
3576   case AtomicRMWInst::FSub:
3577   case AtomicRMWInst::BAD_BINOP:
3578   case AtomicRMWInst::Max:
3579   case AtomicRMWInst::Min:
3580   case AtomicRMWInst::UMax:
3581   case AtomicRMWInst::UMin:
3582     llvm_unreachable("Unsupported atomic update operation");
3583   }
3584   llvm_unreachable("Unsupported atomic update operation");
3585 }
3586 
3587 std::pair<Value *, Value *> OpenMPIRBuilder::emitAtomicUpdate(
3588     InsertPointTy AllocaIP, Value *X, Type *XElemTy, Value *Expr,
3589     AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
3590     AtomicUpdateCallbackTy &UpdateOp, bool VolatileX, bool IsXBinopExpr) {
3591   // TODO: handle the case where XElemTy is not byte-sized or not a power of 2
3592   // or a complex datatype.
3593   bool emitRMWOp = false;
3594   switch (RMWOp) {
3595   case AtomicRMWInst::Add:
3596   case AtomicRMWInst::And:
3597   case AtomicRMWInst::Nand:
3598   case AtomicRMWInst::Or:
3599   case AtomicRMWInst::Xor:
3600   case AtomicRMWInst::Xchg:
3601     emitRMWOp = XElemTy;
3602     break;
3603   case AtomicRMWInst::Sub:
3604     emitRMWOp = (IsXBinopExpr && XElemTy);
3605     break;
3606   default:
3607     emitRMWOp = false;
3608   }
3609   emitRMWOp &= XElemTy->isIntegerTy();
3610 
3611   std::pair<Value *, Value *> Res;
3612   if (emitRMWOp) {
3613     Res.first = Builder.CreateAtomicRMW(RMWOp, X, Expr, llvm::MaybeAlign(), AO);
3614     // not needed except in case of postfix captures. Generate anyway for
3615     // consistency with the else part. Will be removed with any DCE pass.
3616     // AtomicRMWInst::Xchg does not have a coressponding instruction.
3617     if (RMWOp == AtomicRMWInst::Xchg)
3618       Res.second = Res.first;
3619     else
3620       Res.second = emitRMWOpAsInstruction(Res.first, Expr, RMWOp);
3621   } else {
3622     unsigned Addrspace = cast<PointerType>(X->getType())->getAddressSpace();
3623     IntegerType *IntCastTy =
3624         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3625     Value *XBCast =
3626         Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
3627     LoadInst *OldVal =
3628         Builder.CreateLoad(IntCastTy, XBCast, X->getName() + ".atomic.load");
3629     OldVal->setAtomic(AO);
3630     // CurBB
3631     // |     /---\
3632 		// ContBB    |
3633     // |     \---/
3634     // ExitBB
3635     BasicBlock *CurBB = Builder.GetInsertBlock();
3636     Instruction *CurBBTI = CurBB->getTerminator();
3637     CurBBTI = CurBBTI ? CurBBTI : Builder.CreateUnreachable();
3638     BasicBlock *ExitBB =
3639         CurBB->splitBasicBlock(CurBBTI, X->getName() + ".atomic.exit");
3640     BasicBlock *ContBB = CurBB->splitBasicBlock(CurBB->getTerminator(),
3641                                                 X->getName() + ".atomic.cont");
3642     ContBB->getTerminator()->eraseFromParent();
3643     Builder.restoreIP(AllocaIP);
3644     AllocaInst *NewAtomicAddr = Builder.CreateAlloca(XElemTy);
3645     NewAtomicAddr->setName(X->getName() + "x.new.val");
3646     Builder.SetInsertPoint(ContBB);
3647     llvm::PHINode *PHI = Builder.CreatePHI(OldVal->getType(), 2);
3648     PHI->addIncoming(OldVal, CurBB);
3649     IntegerType *NewAtomicCastTy =
3650         IntegerType::get(M.getContext(), XElemTy->getScalarSizeInBits());
3651     bool IsIntTy = XElemTy->isIntegerTy();
3652     Value *NewAtomicIntAddr =
3653         (IsIntTy)
3654             ? NewAtomicAddr
3655             : Builder.CreateBitCast(NewAtomicAddr,
3656                                     NewAtomicCastTy->getPointerTo(Addrspace));
3657     Value *OldExprVal = PHI;
3658     if (!IsIntTy) {
3659       if (XElemTy->isFloatingPointTy()) {
3660         OldExprVal = Builder.CreateBitCast(PHI, XElemTy,
3661                                            X->getName() + ".atomic.fltCast");
3662       } else {
3663         OldExprVal = Builder.CreateIntToPtr(PHI, XElemTy,
3664                                             X->getName() + ".atomic.ptrCast");
3665       }
3666     }
3667 
3668     Value *Upd = UpdateOp(OldExprVal, Builder);
3669     Builder.CreateStore(Upd, NewAtomicAddr);
3670     LoadInst *DesiredVal = Builder.CreateLoad(IntCastTy, NewAtomicIntAddr);
3671     Value *XAddr =
3672         (IsIntTy)
3673             ? X
3674             : Builder.CreateBitCast(X, IntCastTy->getPointerTo(Addrspace));
3675     AtomicOrdering Failure =
3676         llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
3677     AtomicCmpXchgInst *Result = Builder.CreateAtomicCmpXchg(
3678         XAddr, PHI, DesiredVal, llvm::MaybeAlign(), AO, Failure);
3679     Result->setVolatile(VolatileX);
3680     Value *PreviousVal = Builder.CreateExtractValue(Result, /*Idxs=*/0);
3681     Value *SuccessFailureVal = Builder.CreateExtractValue(Result, /*Idxs=*/1);
3682     PHI->addIncoming(PreviousVal, Builder.GetInsertBlock());
3683     Builder.CreateCondBr(SuccessFailureVal, ExitBB, ContBB);
3684 
3685     Res.first = OldExprVal;
3686     Res.second = Upd;
3687 
3688     // set Insertion point in exit block
3689     if (UnreachableInst *ExitTI =
3690             dyn_cast<UnreachableInst>(ExitBB->getTerminator())) {
3691       CurBBTI->eraseFromParent();
3692       Builder.SetInsertPoint(ExitBB);
3693     } else {
3694       Builder.SetInsertPoint(ExitTI);
3695     }
3696   }
3697 
3698   return Res;
3699 }
3700 
3701 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCapture(
3702     const LocationDescription &Loc, InsertPointTy AllocaIP, AtomicOpValue &X,
3703     AtomicOpValue &V, Value *Expr, AtomicOrdering AO,
3704     AtomicRMWInst::BinOp RMWOp, AtomicUpdateCallbackTy &UpdateOp,
3705     bool UpdateExpr, bool IsPostfixUpdate, bool IsXBinopExpr) {
3706   if (!updateToLocation(Loc))
3707     return Loc.IP;
3708 
3709   LLVM_DEBUG({
3710     Type *XTy = X.Var->getType();
3711     assert(XTy->isPointerTy() &&
3712            "OMP Atomic expects a pointer to target memory");
3713     Type *XElemTy = X.ElemTy;
3714     assert((XElemTy->isFloatingPointTy() || XElemTy->isIntegerTy() ||
3715             XElemTy->isPointerTy()) &&
3716            "OMP atomic capture expected a scalar type");
3717     assert((RMWOp != AtomicRMWInst::Max) && (RMWOp != AtomicRMWInst::Min) &&
3718            "OpenMP atomic does not support LT or GT operations");
3719   });
3720 
3721   // If UpdateExpr is 'x' updated with some `expr` not based on 'x',
3722   // 'x' is simply atomically rewritten with 'expr'.
3723   AtomicRMWInst::BinOp AtomicOp = (UpdateExpr ? RMWOp : AtomicRMWInst::Xchg);
3724   std::pair<Value *, Value *> Result =
3725       emitAtomicUpdate(AllocaIP, X.Var, X.ElemTy, Expr, AO, AtomicOp, UpdateOp,
3726                        X.IsVolatile, IsXBinopExpr);
3727 
3728   Value *CapturedVal = (IsPostfixUpdate ? Result.first : Result.second);
3729   Builder.CreateStore(CapturedVal, V.Var, V.IsVolatile);
3730 
3731   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Capture);
3732   return Builder.saveIP();
3733 }
3734 
3735 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createAtomicCompare(
3736     const LocationDescription &Loc, AtomicOpValue &X, Value *E, Value *D,
3737     AtomicOrdering AO, OMPAtomicCompareOp Op, bool IsXBinopExpr) {
3738   if (!updateToLocation(Loc))
3739     return Loc.IP;
3740 
3741   assert(X.Var->getType()->isPointerTy() &&
3742          "OMP atomic expects a pointer to target memory");
3743   assert((X.ElemTy->isIntegerTy() || X.ElemTy->isPointerTy()) &&
3744          "OMP atomic compare expected a integer scalar type");
3745 
3746   if (Op == OMPAtomicCompareOp::EQ) {
3747     AtomicOrdering Failure = AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
3748     // We don't need the result for now.
3749     (void)Builder.CreateAtomicCmpXchg(X.Var, E, D, MaybeAlign(), AO, Failure);
3750   } else {
3751     assert((Op == OMPAtomicCompareOp::MAX || Op == OMPAtomicCompareOp::MIN) &&
3752            "Op should be either max or min at this point");
3753 
3754     // Reverse the ordop as the OpenMP forms are different from LLVM forms.
3755     // Let's take max as example.
3756     // OpenMP form:
3757     // x = x > expr ? expr : x;
3758     // LLVM form:
3759     // *ptr = *ptr > val ? *ptr : val;
3760     // We need to transform to LLVM form.
3761     // x = x <= expr ? x : expr;
3762     AtomicRMWInst::BinOp NewOp;
3763     if (IsXBinopExpr) {
3764       if (X.IsSigned)
3765         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Min
3766                                               : AtomicRMWInst::Max;
3767       else
3768         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMin
3769                                               : AtomicRMWInst::UMax;
3770     } else {
3771       if (X.IsSigned)
3772         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::Max
3773                                               : AtomicRMWInst::Min;
3774       else
3775         NewOp = Op == OMPAtomicCompareOp::MAX ? AtomicRMWInst::UMax
3776                                               : AtomicRMWInst::UMin;
3777     }
3778     // We dont' need the result for now.
3779     (void)Builder.CreateAtomicRMW(NewOp, X.Var, E, MaybeAlign(), AO);
3780   }
3781 
3782   checkAndEmitFlushAfterAtomic(Loc, AO, AtomicKind::Compare);
3783 
3784   return Builder.saveIP();
3785 }
3786 
3787 GlobalVariable *
3788 OpenMPIRBuilder::createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
3789                                        std::string VarName) {
3790   llvm::Constant *MapNamesArrayInit = llvm::ConstantArray::get(
3791       llvm::ArrayType::get(
3792           llvm::Type::getInt8Ty(M.getContext())->getPointerTo(), Names.size()),
3793       Names);
3794   auto *MapNamesArrayGlobal = new llvm::GlobalVariable(
3795       M, MapNamesArrayInit->getType(),
3796       /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, MapNamesArrayInit,
3797       VarName);
3798   return MapNamesArrayGlobal;
3799 }
3800 
3801 // Create all simple and struct types exposed by the runtime and remember
3802 // the llvm::PointerTypes of them for easy access later.
3803 void OpenMPIRBuilder::initializeTypes(Module &M) {
3804   LLVMContext &Ctx = M.getContext();
3805   StructType *T;
3806 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
3807 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
3808   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
3809   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
3810 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
3811   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
3812   VarName##Ptr = PointerType::getUnqual(VarName);
3813 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
3814   T = StructType::getTypeByName(Ctx, StructName);                              \
3815   if (!T)                                                                      \
3816     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
3817   VarName = T;                                                                 \
3818   VarName##Ptr = PointerType::getUnqual(T);
3819 #include "llvm/Frontend/OpenMP/OMPKinds.def"
3820 }
3821 
3822 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
3823     SmallPtrSetImpl<BasicBlock *> &BlockSet,
3824     SmallVectorImpl<BasicBlock *> &BlockVector) {
3825   SmallVector<BasicBlock *, 32> Worklist;
3826   BlockSet.insert(EntryBB);
3827   BlockSet.insert(ExitBB);
3828 
3829   Worklist.push_back(EntryBB);
3830   while (!Worklist.empty()) {
3831     BasicBlock *BB = Worklist.pop_back_val();
3832     BlockVector.push_back(BB);
3833     for (BasicBlock *SuccBB : successors(BB))
3834       if (BlockSet.insert(SuccBB).second)
3835         Worklist.push_back(SuccBB);
3836   }
3837 }
3838 
3839 void CanonicalLoopInfo::collectControlBlocks(
3840     SmallVectorImpl<BasicBlock *> &BBs) {
3841   // We only count those BBs as control block for which we do not need to
3842   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
3843   // flow. For consistency, this also means we do not add the Body block, which
3844   // is just the entry to the body code.
3845   BBs.reserve(BBs.size() + 6);
3846   BBs.append({getPreheader(), Header, Cond, Latch, Exit, getAfter()});
3847 }
3848 
3849 BasicBlock *CanonicalLoopInfo::getPreheader() const {
3850   assert(isValid() && "Requires a valid canonical loop");
3851   for (BasicBlock *Pred : predecessors(Header)) {
3852     if (Pred != Latch)
3853       return Pred;
3854   }
3855   llvm_unreachable("Missing preheader");
3856 }
3857 
3858 void CanonicalLoopInfo::setTripCount(Value *TripCount) {
3859   assert(isValid() && "Requires a valid canonical loop");
3860 
3861   Instruction *CmpI = &getCond()->front();
3862   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
3863   CmpI->setOperand(1, TripCount);
3864 
3865 #ifndef NDEBUG
3866   assertOK();
3867 #endif
3868 }
3869 
3870 void CanonicalLoopInfo::mapIndVar(
3871     llvm::function_ref<Value *(Instruction *)> Updater) {
3872   assert(isValid() && "Requires a valid canonical loop");
3873 
3874   Instruction *OldIV = getIndVar();
3875 
3876   // Record all uses excluding those introduced by the updater. Uses by the
3877   // CanonicalLoopInfo itself to keep track of the number of iterations are
3878   // excluded.
3879   SmallVector<Use *> ReplacableUses;
3880   for (Use &U : OldIV->uses()) {
3881     auto *User = dyn_cast<Instruction>(U.getUser());
3882     if (!User)
3883       continue;
3884     if (User->getParent() == getCond())
3885       continue;
3886     if (User->getParent() == getLatch())
3887       continue;
3888     ReplacableUses.push_back(&U);
3889   }
3890 
3891   // Run the updater that may introduce new uses
3892   Value *NewIV = Updater(OldIV);
3893 
3894   // Replace the old uses with the value returned by the updater.
3895   for (Use *U : ReplacableUses)
3896     U->set(NewIV);
3897 
3898 #ifndef NDEBUG
3899   assertOK();
3900 #endif
3901 }
3902 
3903 void CanonicalLoopInfo::assertOK() const {
3904 #ifndef NDEBUG
3905   // No constraints if this object currently does not describe a loop.
3906   if (!isValid())
3907     return;
3908 
3909   BasicBlock *Preheader = getPreheader();
3910   BasicBlock *Body = getBody();
3911   BasicBlock *After = getAfter();
3912 
3913   // Verify standard control-flow we use for OpenMP loops.
3914   assert(Preheader);
3915   assert(isa<BranchInst>(Preheader->getTerminator()) &&
3916          "Preheader must terminate with unconditional branch");
3917   assert(Preheader->getSingleSuccessor() == Header &&
3918          "Preheader must jump to header");
3919 
3920   assert(Header);
3921   assert(isa<BranchInst>(Header->getTerminator()) &&
3922          "Header must terminate with unconditional branch");
3923   assert(Header->getSingleSuccessor() == Cond &&
3924          "Header must jump to exiting block");
3925 
3926   assert(Cond);
3927   assert(Cond->getSinglePredecessor() == Header &&
3928          "Exiting block only reachable from header");
3929 
3930   assert(isa<BranchInst>(Cond->getTerminator()) &&
3931          "Exiting block must terminate with conditional branch");
3932   assert(size(successors(Cond)) == 2 &&
3933          "Exiting block must have two successors");
3934   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
3935          "Exiting block's first successor jump to the body");
3936   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
3937          "Exiting block's second successor must exit the loop");
3938 
3939   assert(Body);
3940   assert(Body->getSinglePredecessor() == Cond &&
3941          "Body only reachable from exiting block");
3942   assert(!isa<PHINode>(Body->front()));
3943 
3944   assert(Latch);
3945   assert(isa<BranchInst>(Latch->getTerminator()) &&
3946          "Latch must terminate with unconditional branch");
3947   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
3948   // TODO: To support simple redirecting of the end of the body code that has
3949   // multiple; introduce another auxiliary basic block like preheader and after.
3950   assert(Latch->getSinglePredecessor() != nullptr);
3951   assert(!isa<PHINode>(Latch->front()));
3952 
3953   assert(Exit);
3954   assert(isa<BranchInst>(Exit->getTerminator()) &&
3955          "Exit block must terminate with unconditional branch");
3956   assert(Exit->getSingleSuccessor() == After &&
3957          "Exit block must jump to after block");
3958 
3959   assert(After);
3960   assert(After->getSinglePredecessor() == Exit &&
3961          "After block only reachable from exit block");
3962   assert(After->empty() || !isa<PHINode>(After->front()));
3963 
3964   Instruction *IndVar = getIndVar();
3965   assert(IndVar && "Canonical induction variable not found?");
3966   assert(isa<IntegerType>(IndVar->getType()) &&
3967          "Induction variable must be an integer");
3968   assert(cast<PHINode>(IndVar)->getParent() == Header &&
3969          "Induction variable must be a PHI in the loop header");
3970   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
3971   assert(
3972       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
3973   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
3974 
3975   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
3976   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
3977   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
3978   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
3979   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
3980              ->isOne());
3981 
3982   Value *TripCount = getTripCount();
3983   assert(TripCount && "Loop trip count not found?");
3984   assert(IndVar->getType() == TripCount->getType() &&
3985          "Trip count and induction variable must have the same type");
3986 
3987   auto *CmpI = cast<CmpInst>(&Cond->front());
3988   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
3989          "Exit condition must be a signed less-than comparison");
3990   assert(CmpI->getOperand(0) == IndVar &&
3991          "Exit condition must compare the induction variable");
3992   assert(CmpI->getOperand(1) == TripCount &&
3993          "Exit condition must compare with the trip count");
3994 #endif
3995 }
3996 
3997 void CanonicalLoopInfo::invalidate() {
3998   Header = nullptr;
3999   Cond = nullptr;
4000   Latch = nullptr;
4001   Exit = nullptr;
4002 }
4003