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