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