1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides a class for OpenMP runtime code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CGCleanup.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/StmtOpenMP.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/Value.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <cassert>
26 
27 using namespace clang;
28 using namespace CodeGen;
29 
30 namespace {
31 /// \brief Base class for handling code generation inside OpenMP regions.
32 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
33 public:
34   CGOpenMPRegionInfo(const OMPExecutableDirective &D, const CapturedStmt &CS)
35       : CGCapturedStmtInfo(CS, CR_OpenMP), Directive(D) {}
36 
37   CGOpenMPRegionInfo(const OMPExecutableDirective &D)
38       : CGCapturedStmtInfo(CR_OpenMP), Directive(D) {}
39 
40   /// \brief Get a variable or parameter for storing global thread id
41   /// inside OpenMP construct.
42   virtual const VarDecl *getThreadIDVariable() const = 0;
43 
44   /// \brief Get an LValue for the current ThreadID variable.
45   /// \return LValue for thread id variable. This LValue always has type int32*.
46   virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
47 
48     /// \brief Emit the captured statement body.
49   virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
50 
51   static bool classof(const CGCapturedStmtInfo *Info) {
52     return Info->getKind() == CR_OpenMP;
53   }
54 protected:
55   /// \brief OpenMP executable directive associated with the region.
56   const OMPExecutableDirective &Directive;
57 };
58 
59 /// \brief API for captured statement code generation in OpenMP constructs.
60 class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
61 public:
62   CGOpenMPOutlinedRegionInfo(const OMPExecutableDirective &D,
63                              const CapturedStmt &CS, const VarDecl *ThreadIDVar)
64       : CGOpenMPRegionInfo(D, CS), ThreadIDVar(ThreadIDVar) {
65     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
66   }
67   /// \brief Get a variable or parameter for storing global thread id
68   /// inside OpenMP construct.
69   virtual const VarDecl *getThreadIDVariable() const override {
70     return ThreadIDVar;
71   }
72   /// \brief Get the name of the capture helper.
73   StringRef getHelperName() const override { return ".omp_outlined."; }
74 
75 private:
76   /// \brief A variable or parameter storing global thread id for OpenMP
77   /// constructs.
78   const VarDecl *ThreadIDVar;
79 };
80 
81 /// \brief API for captured statement code generation in OpenMP constructs.
82 class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
83 public:
84   CGOpenMPTaskOutlinedRegionInfo(const OMPExecutableDirective &D,
85                                  const CapturedStmt &CS,
86                                  const VarDecl *ThreadIDVar,
87                                  const VarDecl *PartIDVar)
88       : CGOpenMPRegionInfo(D, CS), ThreadIDVar(ThreadIDVar),
89         PartIDVar(PartIDVar) {
90     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
91   }
92   /// \brief Get a variable or parameter for storing global thread id
93   /// inside OpenMP construct.
94   virtual const VarDecl *getThreadIDVariable() const override {
95     return ThreadIDVar;
96   }
97 
98   /// \brief Get an LValue for the current ThreadID variable.
99   virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
100 
101   /// \brief Emit the captured statement body.
102   virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
103 
104   /// \brief Get the name of the capture helper.
105   StringRef getHelperName() const override { return ".omp_outlined."; }
106 
107 private:
108   /// \brief A variable or parameter storing global thread id for OpenMP
109   /// constructs.
110   const VarDecl *ThreadIDVar;
111   /// \brief A variable or parameter storing part id for OpenMP tasking
112   /// constructs.
113   const VarDecl *PartIDVar;
114 };
115 
116 /// \brief API for inlined captured statement code generation in OpenMP
117 /// constructs.
118 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
119 public:
120   CGOpenMPInlinedRegionInfo(const OMPExecutableDirective &D,
121                             CodeGenFunction::CGCapturedStmtInfo *OldCSI)
122       : CGOpenMPRegionInfo(D), OldCSI(OldCSI),
123         OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
124   // \brief Retrieve the value of the context parameter.
125   virtual llvm::Value *getContextValue() const override {
126     if (OuterRegionInfo)
127       return OuterRegionInfo->getContextValue();
128     llvm_unreachable("No context value for inlined OpenMP region");
129   }
130   /// \brief Lookup the captured field decl for a variable.
131   virtual const FieldDecl *lookup(const VarDecl *VD) const override {
132     if (OuterRegionInfo)
133       return OuterRegionInfo->lookup(VD);
134     llvm_unreachable("Trying to reference VarDecl that is neither local nor "
135                      "captured in outer OpenMP region");
136   }
137   virtual FieldDecl *getThisFieldDecl() const override {
138     if (OuterRegionInfo)
139       return OuterRegionInfo->getThisFieldDecl();
140     return nullptr;
141   }
142   /// \brief Get a variable or parameter for storing global thread id
143   /// inside OpenMP construct.
144   virtual const VarDecl *getThreadIDVariable() const override {
145     if (OuterRegionInfo)
146       return OuterRegionInfo->getThreadIDVariable();
147     return nullptr;
148   }
149 
150   /// \brief Get the name of the capture helper.
151   virtual StringRef getHelperName() const override {
152     llvm_unreachable("No helper name for inlined OpenMP construct");
153   }
154 
155   CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
156 
157 private:
158   /// \brief CodeGen info about outer OpenMP region.
159   CodeGenFunction::CGCapturedStmtInfo *OldCSI;
160   CGOpenMPRegionInfo *OuterRegionInfo;
161 };
162 } // namespace
163 
164 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
165   return CGF.MakeNaturalAlignAddrLValue(
166       CGF.Builder.CreateAlignedLoad(
167           CGF.GetAddrOfLocalVar(getThreadIDVariable()),
168           CGF.PointerAlignInBytes),
169       getThreadIDVariable()
170           ->getType()
171           ->castAs<PointerType>()
172           ->getPointeeType());
173 }
174 
175 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) {
176   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
177   CGF.EmitOMPPrivateClause(Directive, PrivateScope);
178   CGF.EmitOMPFirstprivateClause(Directive, PrivateScope);
179   if (PrivateScope.Privatize())
180     // Emit implicit barrier to synchronize threads and avoid data races.
181     CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, Directive.getLocStart(),
182                                                /*IsExplicit=*/false);
183   CGCapturedStmtInfo::EmitBody(CGF, S);
184 }
185 
186 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
187     CodeGenFunction &CGF) {
188   return CGF.MakeNaturalAlignAddrLValue(
189       CGF.GetAddrOfLocalVar(getThreadIDVariable()),
190       getThreadIDVariable()->getType());
191 }
192 
193 void CGOpenMPTaskOutlinedRegionInfo::EmitBody(CodeGenFunction &CGF,
194                                               const Stmt *S) {
195   if (PartIDVar) {
196     // TODO: emit code for untied tasks.
197   }
198   CGCapturedStmtInfo::EmitBody(CGF, S);
199 }
200 
201 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
202     : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
203   IdentTy = llvm::StructType::create(
204       "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
205       CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
206       CGM.Int8PtrTy /* psource */, nullptr);
207   // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
208   llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
209                                llvm::PointerType::getUnqual(CGM.Int32Ty)};
210   Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
211   KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
212 }
213 
214 llvm::Value *
215 CGOpenMPRuntime::emitOutlinedFunction(const OMPExecutableDirective &D,
216                                       const VarDecl *ThreadIDVar) {
217   assert(ThreadIDVar->getType()->isPointerType() &&
218          "thread id variable must be of type kmp_int32 *");
219   const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
220   CodeGenFunction CGF(CGM, true);
221   CGOpenMPOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar);
222   CGF.CapturedStmtInfo = &CGInfo;
223   return CGF.GenerateCapturedStmtFunction(*CS);
224 }
225 
226 llvm::Value *
227 CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
228                                           const VarDecl *ThreadIDVar,
229                                           const VarDecl *PartIDVar) {
230   assert(!ThreadIDVar->getType()->isPointerType() &&
231          "thread id variable must be of type kmp_int32 for tasks");
232   auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
233   CodeGenFunction CGF(CGM, true);
234   CGOpenMPTaskOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar, PartIDVar);
235   CGF.CapturedStmtInfo = &CGInfo;
236   return CGF.GenerateCapturedStmtFunction(*CS);
237 }
238 
239 llvm::Value *
240 CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
241   llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
242   if (!Entry) {
243     if (!DefaultOpenMPPSource) {
244       // Initialize default location for psource field of ident_t structure of
245       // all ident_t objects. Format is ";file;function;line;column;;".
246       // Taken from
247       // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
248       DefaultOpenMPPSource =
249           CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
250       DefaultOpenMPPSource =
251           llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
252     }
253     auto DefaultOpenMPLocation = new llvm::GlobalVariable(
254         CGM.getModule(), IdentTy, /*isConstant*/ true,
255         llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
256     DefaultOpenMPLocation->setUnnamedAddr(true);
257 
258     llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
259     llvm::Constant *Values[] = {Zero,
260                                 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
261                                 Zero, Zero, DefaultOpenMPPSource};
262     llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
263     DefaultOpenMPLocation->setInitializer(Init);
264     OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
265     return DefaultOpenMPLocation;
266   }
267   return Entry;
268 }
269 
270 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
271                                                  SourceLocation Loc,
272                                                  OpenMPLocationFlags Flags) {
273   // If no debug info is generated - return global default location.
274   if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
275       Loc.isInvalid())
276     return getOrCreateDefaultLocation(Flags);
277 
278   assert(CGF.CurFn && "No function in current CodeGenFunction.");
279 
280   llvm::Value *LocValue = nullptr;
281   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
282   if (I != OpenMPLocThreadIDMap.end())
283     LocValue = I->second.DebugLoc;
284   // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
285   // GetOpenMPThreadID was called before this routine.
286   if (LocValue == nullptr) {
287     // Generate "ident_t .kmpc_loc.addr;"
288     llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
289     AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
290     auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
291     Elem.second.DebugLoc = AI;
292     LocValue = AI;
293 
294     CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
295     CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
296     CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
297                              llvm::ConstantExpr::getSizeOf(IdentTy),
298                              CGM.PointerAlignInBytes);
299   }
300 
301   // char **psource = &.kmpc_loc_<flags>.addr.psource;
302   auto *PSource =
303       CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource);
304 
305   auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
306   if (OMPDebugLoc == nullptr) {
307     SmallString<128> Buffer2;
308     llvm::raw_svector_ostream OS2(Buffer2);
309     // Build debug location
310     PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
311     OS2 << ";" << PLoc.getFilename() << ";";
312     if (const FunctionDecl *FD =
313             dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
314       OS2 << FD->getQualifiedNameAsString();
315     }
316     OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
317     OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
318     OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
319   }
320   // *psource = ";<File>;<Function>;<Line>;<Column>;;";
321   CGF.Builder.CreateStore(OMPDebugLoc, PSource);
322 
323   return LocValue;
324 }
325 
326 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
327                                           SourceLocation Loc) {
328   assert(CGF.CurFn && "No function in current CodeGenFunction.");
329 
330   llvm::Value *ThreadID = nullptr;
331   // Check whether we've already cached a load of the thread id in this
332   // function.
333   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
334   if (I != OpenMPLocThreadIDMap.end()) {
335     ThreadID = I->second.ThreadID;
336     if (ThreadID != nullptr)
337       return ThreadID;
338   }
339   if (auto OMPRegionInfo =
340           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
341     if (OMPRegionInfo->getThreadIDVariable()) {
342       // Check if this an outlined function with thread id passed as argument.
343       auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
344       ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
345       // If value loaded in entry block, cache it and use it everywhere in
346       // function.
347       if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
348         auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
349         Elem.second.ThreadID = ThreadID;
350       }
351       return ThreadID;
352     }
353   }
354 
355   // This is not an outlined function region - need to call __kmpc_int32
356   // kmpc_global_thread_num(ident_t *loc).
357   // Generate thread id value and cache this value for use across the
358   // function.
359   CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
360   CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
361   ThreadID =
362       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
363                           emitUpdateLocation(CGF, Loc));
364   auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
365   Elem.second.ThreadID = ThreadID;
366   return ThreadID;
367 }
368 
369 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
370   assert(CGF.CurFn && "No function in current CodeGenFunction.");
371   if (OpenMPLocThreadIDMap.count(CGF.CurFn))
372     OpenMPLocThreadIDMap.erase(CGF.CurFn);
373 }
374 
375 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
376   return llvm::PointerType::getUnqual(IdentTy);
377 }
378 
379 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
380   return llvm::PointerType::getUnqual(Kmpc_MicroTy);
381 }
382 
383 llvm::Constant *
384 CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
385   llvm::Constant *RTLFn = nullptr;
386   switch (Function) {
387   case OMPRTL__kmpc_fork_call: {
388     // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
389     // microtask, ...);
390     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
391                                 getKmpc_MicroPointerTy()};
392     llvm::FunctionType *FnTy =
393         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
394     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
395     break;
396   }
397   case OMPRTL__kmpc_global_thread_num: {
398     // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
399     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
400     llvm::FunctionType *FnTy =
401         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
402     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
403     break;
404   }
405   case OMPRTL__kmpc_threadprivate_cached: {
406     // Build void *__kmpc_threadprivate_cached(ident_t *loc,
407     // kmp_int32 global_tid, void *data, size_t size, void ***cache);
408     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
409                                 CGM.VoidPtrTy, CGM.SizeTy,
410                                 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
411     llvm::FunctionType *FnTy =
412         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
413     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
414     break;
415   }
416   case OMPRTL__kmpc_critical: {
417     // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
418     // kmp_critical_name *crit);
419     llvm::Type *TypeParams[] = {
420         getIdentTyPointerTy(), CGM.Int32Ty,
421         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
422     llvm::FunctionType *FnTy =
423         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
424     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
425     break;
426   }
427   case OMPRTL__kmpc_threadprivate_register: {
428     // Build void __kmpc_threadprivate_register(ident_t *, void *data,
429     // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
430     // typedef void *(*kmpc_ctor)(void *);
431     auto KmpcCtorTy =
432         llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
433                                 /*isVarArg*/ false)->getPointerTo();
434     // typedef void *(*kmpc_cctor)(void *, void *);
435     llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
436     auto KmpcCopyCtorTy =
437         llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
438                                 /*isVarArg*/ false)->getPointerTo();
439     // typedef void (*kmpc_dtor)(void *);
440     auto KmpcDtorTy =
441         llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
442             ->getPointerTo();
443     llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
444                               KmpcCopyCtorTy, KmpcDtorTy};
445     auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
446                                         /*isVarArg*/ false);
447     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
448     break;
449   }
450   case OMPRTL__kmpc_end_critical: {
451     // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
452     // kmp_critical_name *crit);
453     llvm::Type *TypeParams[] = {
454         getIdentTyPointerTy(), CGM.Int32Ty,
455         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
456     llvm::FunctionType *FnTy =
457         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
458     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
459     break;
460   }
461   case OMPRTL__kmpc_cancel_barrier: {
462     // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
463     // global_tid);
464     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
465     llvm::FunctionType *FnTy =
466         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
467     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
468     break;
469   }
470   // Build __kmpc_for_static_init*(
471   //               ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
472   //               kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
473   //               kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
474   //               kmp_int[32|64] incr, kmp_int[32|64] chunk);
475   case OMPRTL__kmpc_for_static_init_4: {
476     auto ITy = CGM.Int32Ty;
477     auto PtrTy = llvm::PointerType::getUnqual(ITy);
478     llvm::Type *TypeParams[] = {
479         getIdentTyPointerTy(),                     // loc
480         CGM.Int32Ty,                               // tid
481         CGM.Int32Ty,                               // schedtype
482         llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
483         PtrTy,                                     // p_lower
484         PtrTy,                                     // p_upper
485         PtrTy,                                     // p_stride
486         ITy,                                       // incr
487         ITy                                        // chunk
488     };
489     llvm::FunctionType *FnTy =
490         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
491     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_4");
492     break;
493   }
494   case OMPRTL__kmpc_for_static_init_4u: {
495     auto ITy = CGM.Int32Ty;
496     auto PtrTy = llvm::PointerType::getUnqual(ITy);
497     llvm::Type *TypeParams[] = {
498         getIdentTyPointerTy(),                     // loc
499         CGM.Int32Ty,                               // tid
500         CGM.Int32Ty,                               // schedtype
501         llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
502         PtrTy,                                     // p_lower
503         PtrTy,                                     // p_upper
504         PtrTy,                                     // p_stride
505         ITy,                                       // incr
506         ITy                                        // chunk
507     };
508     llvm::FunctionType *FnTy =
509         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
510     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_4u");
511     break;
512   }
513   case OMPRTL__kmpc_for_static_init_8: {
514     auto ITy = CGM.Int64Ty;
515     auto PtrTy = llvm::PointerType::getUnqual(ITy);
516     llvm::Type *TypeParams[] = {
517         getIdentTyPointerTy(),                     // loc
518         CGM.Int32Ty,                               // tid
519         CGM.Int32Ty,                               // schedtype
520         llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
521         PtrTy,                                     // p_lower
522         PtrTy,                                     // p_upper
523         PtrTy,                                     // p_stride
524         ITy,                                       // incr
525         ITy                                        // chunk
526     };
527     llvm::FunctionType *FnTy =
528         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
529     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_8");
530     break;
531   }
532   case OMPRTL__kmpc_for_static_init_8u: {
533     auto ITy = CGM.Int64Ty;
534     auto PtrTy = llvm::PointerType::getUnqual(ITy);
535     llvm::Type *TypeParams[] = {
536         getIdentTyPointerTy(),                     // loc
537         CGM.Int32Ty,                               // tid
538         CGM.Int32Ty,                               // schedtype
539         llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
540         PtrTy,                                     // p_lower
541         PtrTy,                                     // p_upper
542         PtrTy,                                     // p_stride
543         ITy,                                       // incr
544         ITy                                        // chunk
545     };
546     llvm::FunctionType *FnTy =
547         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
548     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_init_8u");
549     break;
550   }
551   case OMPRTL__kmpc_for_static_fini: {
552     // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
553     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
554     llvm::FunctionType *FnTy =
555         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
556     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
557     break;
558   }
559   case OMPRTL__kmpc_push_num_threads: {
560     // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
561     // kmp_int32 num_threads)
562     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
563                                 CGM.Int32Ty};
564     llvm::FunctionType *FnTy =
565         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
566     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
567     break;
568   }
569   case OMPRTL__kmpc_serialized_parallel: {
570     // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
571     // global_tid);
572     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
573     llvm::FunctionType *FnTy =
574         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
575     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
576     break;
577   }
578   case OMPRTL__kmpc_end_serialized_parallel: {
579     // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
580     // global_tid);
581     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
582     llvm::FunctionType *FnTy =
583         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
584     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
585     break;
586   }
587   case OMPRTL__kmpc_flush: {
588     // Build void __kmpc_flush(ident_t *loc);
589     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
590     llvm::FunctionType *FnTy =
591         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
592     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
593     break;
594   }
595   case OMPRTL__kmpc_master: {
596     // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
597     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
598     llvm::FunctionType *FnTy =
599         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
600     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
601     break;
602   }
603   case OMPRTL__kmpc_end_master: {
604     // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
605     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
606     llvm::FunctionType *FnTy =
607         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
608     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
609     break;
610   }
611   case OMPRTL__kmpc_omp_taskyield: {
612     // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
613     // int end_part);
614     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
615     llvm::FunctionType *FnTy =
616         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
617     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
618     break;
619   }
620   case OMPRTL__kmpc_single: {
621     // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
622     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
623     llvm::FunctionType *FnTy =
624         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
625     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
626     break;
627   }
628   case OMPRTL__kmpc_end_single: {
629     // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
630     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
631     llvm::FunctionType *FnTy =
632         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
633     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
634     break;
635   }
636   case OMPRTL__kmpc_omp_task_alloc: {
637     // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
638     // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
639     // kmp_routine_entry_t *task_entry);
640     assert(KmpRoutineEntryPtrTy != nullptr &&
641            "Type kmp_routine_entry_t must be created.");
642     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
643                                 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
644     // Return void * and then cast to particular kmp_task_t type.
645     llvm::FunctionType *FnTy =
646         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
647     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
648     break;
649   }
650   case OMPRTL__kmpc_omp_task: {
651     // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
652     // *new_task);
653     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
654                                 CGM.VoidPtrTy};
655     llvm::FunctionType *FnTy =
656         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
657     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
658     break;
659   }
660   }
661   return RTLFn;
662 }
663 
664 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
665                                                             bool IVSigned) {
666   assert((IVSize == 32 || IVSize == 64) &&
667          "IV size is not compatible with the omp runtime");
668   auto Name =
669       IVSize == 32
670           ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
671           : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
672   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
673   llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
674                                CGM.Int32Ty,           // tid
675                                CGM.Int32Ty,           // schedtype
676                                ITy,                   // lower
677                                ITy,                   // upper
678                                ITy,                   // stride
679                                ITy                    // chunk
680   };
681   llvm::FunctionType *FnTy =
682       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
683   return CGM.CreateRuntimeFunction(FnTy, Name);
684 }
685 
686 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
687                                                             bool IVSigned) {
688   assert((IVSize == 32 || IVSize == 64) &&
689          "IV size is not compatible with the omp runtime");
690   auto Name =
691       IVSize == 32
692           ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
693           : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
694   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
695   auto PtrTy = llvm::PointerType::getUnqual(ITy);
696   llvm::Type *TypeParams[] = {
697     getIdentTyPointerTy(),                     // loc
698     CGM.Int32Ty,                               // tid
699     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
700     PtrTy,                                     // p_lower
701     PtrTy,                                     // p_upper
702     PtrTy                                      // p_stride
703   };
704   llvm::FunctionType *FnTy =
705       llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
706   return CGM.CreateRuntimeFunction(FnTy, Name);
707 }
708 
709 llvm::Constant *
710 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
711   // Lookup the entry, lazily creating it if necessary.
712   return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
713                                      Twine(CGM.getMangledName(VD)) + ".cache.");
714 }
715 
716 llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
717                                                      const VarDecl *VD,
718                                                      llvm::Value *VDAddr,
719                                                      SourceLocation Loc) {
720   auto VarTy = VDAddr->getType()->getPointerElementType();
721   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
722                          CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
723                          CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
724                          getOrCreateThreadPrivateCache(VD)};
725   return CGF.EmitRuntimeCall(
726       createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
727 }
728 
729 void CGOpenMPRuntime::emitThreadPrivateVarInit(
730     CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
731     llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
732   // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
733   // library.
734   auto OMPLoc = emitUpdateLocation(CGF, Loc);
735   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
736                       OMPLoc);
737   // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
738   // to register constructor/destructor for variable.
739   llvm::Value *Args[] = {OMPLoc,
740                          CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
741                          Ctor, CopyCtor, Dtor};
742   CGF.EmitRuntimeCall(
743       createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
744 }
745 
746 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
747     const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
748     bool PerformInit, CodeGenFunction *CGF) {
749   VD = VD->getDefinition(CGM.getContext());
750   if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
751     ThreadPrivateWithDefinition.insert(VD);
752     QualType ASTTy = VD->getType();
753 
754     llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
755     auto Init = VD->getAnyInitializer();
756     if (CGM.getLangOpts().CPlusPlus && PerformInit) {
757       // Generate function that re-emits the declaration's initializer into the
758       // threadprivate copy of the variable VD
759       CodeGenFunction CtorCGF(CGM);
760       FunctionArgList Args;
761       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
762                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
763       Args.push_back(&Dst);
764 
765       auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
766           CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
767           /*isVariadic=*/false);
768       auto FTy = CGM.getTypes().GetFunctionType(FI);
769       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
770           FTy, ".__kmpc_global_ctor_.", Loc);
771       CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
772                             Args, SourceLocation());
773       auto ArgVal = CtorCGF.EmitLoadOfScalar(
774           CtorCGF.GetAddrOfLocalVar(&Dst),
775           /*Volatile=*/false, CGM.PointerAlignInBytes,
776           CGM.getContext().VoidPtrTy, Dst.getLocation());
777       auto Arg = CtorCGF.Builder.CreatePointerCast(
778           ArgVal,
779           CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
780       CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
781                                /*IsInitializer=*/true);
782       ArgVal = CtorCGF.EmitLoadOfScalar(
783           CtorCGF.GetAddrOfLocalVar(&Dst),
784           /*Volatile=*/false, CGM.PointerAlignInBytes,
785           CGM.getContext().VoidPtrTy, Dst.getLocation());
786       CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
787       CtorCGF.FinishFunction();
788       Ctor = Fn;
789     }
790     if (VD->getType().isDestructedType() != QualType::DK_none) {
791       // Generate function that emits destructor call for the threadprivate copy
792       // of the variable VD
793       CodeGenFunction DtorCGF(CGM);
794       FunctionArgList Args;
795       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
796                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
797       Args.push_back(&Dst);
798 
799       auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
800           CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
801           /*isVariadic=*/false);
802       auto FTy = CGM.getTypes().GetFunctionType(FI);
803       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
804           FTy, ".__kmpc_global_dtor_.", Loc);
805       DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
806                             SourceLocation());
807       auto ArgVal = DtorCGF.EmitLoadOfScalar(
808           DtorCGF.GetAddrOfLocalVar(&Dst),
809           /*Volatile=*/false, CGM.PointerAlignInBytes,
810           CGM.getContext().VoidPtrTy, Dst.getLocation());
811       DtorCGF.emitDestroy(ArgVal, ASTTy,
812                           DtorCGF.getDestroyer(ASTTy.isDestructedType()),
813                           DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
814       DtorCGF.FinishFunction();
815       Dtor = Fn;
816     }
817     // Do not emit init function if it is not required.
818     if (!Ctor && !Dtor)
819       return nullptr;
820 
821     llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
822     auto CopyCtorTy =
823         llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
824                                 /*isVarArg=*/false)->getPointerTo();
825     // Copying constructor for the threadprivate variable.
826     // Must be NULL - reserved by runtime, but currently it requires that this
827     // parameter is always NULL. Otherwise it fires assertion.
828     CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
829     if (Ctor == nullptr) {
830       auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
831                                             /*isVarArg=*/false)->getPointerTo();
832       Ctor = llvm::Constant::getNullValue(CtorTy);
833     }
834     if (Dtor == nullptr) {
835       auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
836                                             /*isVarArg=*/false)->getPointerTo();
837       Dtor = llvm::Constant::getNullValue(DtorTy);
838     }
839     if (!CGF) {
840       auto InitFunctionTy =
841           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
842       auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
843           InitFunctionTy, ".__omp_threadprivate_init_.");
844       CodeGenFunction InitCGF(CGM);
845       FunctionArgList ArgList;
846       InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
847                             CGM.getTypes().arrangeNullaryFunction(), ArgList,
848                             Loc);
849       emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
850       InitCGF.FinishFunction();
851       return InitFunction;
852     }
853     emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
854   }
855   return nullptr;
856 }
857 
858 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
859                                        llvm::Value *OutlinedFn,
860                                        llvm::Value *CapturedStruct) {
861   // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
862   llvm::Value *Args[] = {
863       emitUpdateLocation(CGF, Loc),
864       CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
865       // (there is only one additional argument - 'context')
866       CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
867       CGF.EmitCastToVoidPtr(CapturedStruct)};
868   auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
869   CGF.EmitRuntimeCall(RTLFn, Args);
870 }
871 
872 void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
873                                      llvm::Value *OutlinedFn,
874                                      llvm::Value *CapturedStruct) {
875   auto ThreadID = getThreadID(CGF, Loc);
876   // Build calls:
877   // __kmpc_serialized_parallel(&Loc, GTid);
878   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
879   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
880                       Args);
881 
882   // OutlinedFn(&GTid, &zero, CapturedStruct);
883   auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
884   auto Int32Ty =
885       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
886   auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
887   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
888   llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
889   CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
890 
891   // __kmpc_end_serialized_parallel(&Loc, GTid);
892   llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
893   CGF.EmitRuntimeCall(
894       createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
895 }
896 
897 // If we're inside an (outlined) parallel region, use the region info's
898 // thread-ID variable (it is passed in a first argument of the outlined function
899 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
900 // regular serial code region, get thread ID by calling kmp_int32
901 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
902 // return the address of that temp.
903 llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
904                                                   SourceLocation Loc) {
905   if (auto OMPRegionInfo =
906           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
907     if (OMPRegionInfo->getThreadIDVariable())
908       return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
909 
910   auto ThreadID = getThreadID(CGF, Loc);
911   auto Int32Ty =
912       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
913   auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
914   CGF.EmitStoreOfScalar(ThreadID,
915                         CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
916 
917   return ThreadIDTemp;
918 }
919 
920 llvm::Constant *
921 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
922                                              const llvm::Twine &Name) {
923   SmallString<256> Buffer;
924   llvm::raw_svector_ostream Out(Buffer);
925   Out << Name;
926   auto RuntimeName = Out.str();
927   auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
928   if (Elem.second) {
929     assert(Elem.second->getType()->getPointerElementType() == Ty &&
930            "OMP internal variable has different type than requested");
931     return &*Elem.second;
932   }
933 
934   return Elem.second = new llvm::GlobalVariable(
935              CGM.getModule(), Ty, /*IsConstant*/ false,
936              llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
937              Elem.first());
938 }
939 
940 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
941   llvm::Twine Name(".gomp_critical_user_", CriticalName);
942   return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
943 }
944 
945 void CGOpenMPRuntime::emitCriticalRegion(
946     CodeGenFunction &CGF, StringRef CriticalName,
947     const std::function<void()> &CriticalOpGen, SourceLocation Loc) {
948   auto RegionLock = getCriticalRegionLock(CriticalName);
949   // __kmpc_critical(ident_t *, gtid, Lock);
950   // CriticalOpGen();
951   // __kmpc_end_critical(ident_t *, gtid, Lock);
952   // Prepare arguments and build a call to __kmpc_critical
953   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
954                          RegionLock};
955   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
956   CriticalOpGen();
957   // Build a call to __kmpc_end_critical
958   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
959 }
960 
961 static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
962                        const std::function<void()> &BodyOpGen) {
963   llvm::Value *CallBool = CGF.EmitScalarConversion(
964       IfCond,
965       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
966       CGF.getContext().BoolTy);
967 
968   auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
969   auto *ContBlock = CGF.createBasicBlock("omp_if.end");
970   // Generate the branch (If-stmt)
971   CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
972   CGF.EmitBlock(ThenBlock);
973   BodyOpGen();
974   // Emit the rest of bblocks/branches
975   CGF.EmitBranch(ContBlock);
976   CGF.EmitBlock(ContBlock, true);
977 }
978 
979 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
980                                        const std::function<void()> &MasterOpGen,
981                                        SourceLocation Loc) {
982   // if(__kmpc_master(ident_t *, gtid)) {
983   //   MasterOpGen();
984   //   __kmpc_end_master(ident_t *, gtid);
985   // }
986   // Prepare arguments and build a call to __kmpc_master
987   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
988   auto *IsMaster =
989       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
990   emitIfStmt(CGF, IsMaster, [&]() -> void {
991     MasterOpGen();
992     // Build a call to __kmpc_end_master.
993     // OpenMP [1.2.2 OpenMP Language Terminology]
994     // For C/C++, an executable statement, possibly compound, with a single
995     // entry at the top and a single exit at the bottom, or an OpenMP construct.
996     // * Access to the structured block must not be the result of a branch.
997     // * The point of exit cannot be a branch out of the structured block.
998     // * The point of entry must not be a call to setjmp().
999     // * longjmp() and throw() must not violate the entry/exit criteria.
1000     // * An expression statement, iteration statement, selection statement, or
1001     // try block is considered to be a structured block if the corresponding
1002     // compound statement obtained by enclosing it in { and } would be a
1003     // structured block.
1004     // It is analyzed in Sema, so we can just call __kmpc_end_master() on
1005     // fallthrough rather than pushing a normal cleanup for it.
1006     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_master), Args);
1007   });
1008 }
1009 
1010 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1011                                         SourceLocation Loc) {
1012   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1013   llvm::Value *Args[] = {
1014       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1015       llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
1016   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
1017 }
1018 
1019 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
1020                                        const std::function<void()> &SingleOpGen,
1021                                        SourceLocation Loc) {
1022   // if(__kmpc_single(ident_t *, gtid)) {
1023   //   SingleOpGen();
1024   //   __kmpc_end_single(ident_t *, gtid);
1025   // }
1026   // Prepare arguments and build a call to __kmpc_single
1027   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1028   auto *IsSingle =
1029       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
1030   emitIfStmt(CGF, IsSingle, [&]() -> void {
1031     SingleOpGen();
1032     // Build a call to __kmpc_end_single.
1033     // OpenMP [1.2.2 OpenMP Language Terminology]
1034     // For C/C++, an executable statement, possibly compound, with a single
1035     // entry at the top and a single exit at the bottom, or an OpenMP construct.
1036     // * Access to the structured block must not be the result of a branch.
1037     // * The point of exit cannot be a branch out of the structured block.
1038     // * The point of entry must not be a call to setjmp().
1039     // * longjmp() and throw() must not violate the entry/exit criteria.
1040     // * An expression statement, iteration statement, selection statement, or
1041     // try block is considered to be a structured block if the corresponding
1042     // compound statement obtained by enclosing it in { and } would be a
1043     // structured block.
1044     // It is analyzed in Sema, so we can just call __kmpc_end_single() on
1045     // fallthrough rather than pushing a normal cleanup for it.
1046     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_single), Args);
1047   });
1048 }
1049 
1050 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
1051                                       bool IsExplicit) {
1052   // Build call __kmpc_cancel_barrier(loc, thread_id);
1053   auto Flags = static_cast<OpenMPLocationFlags>(
1054       OMP_IDENT_KMPC |
1055       (IsExplicit ? OMP_IDENT_BARRIER_EXPL : OMP_IDENT_BARRIER_IMPL));
1056   // Build call __kmpc_cancel_barrier(loc, thread_id);
1057   // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1058   // one provides the same functionality and adds initial support for
1059   // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1060   // is provided default by the runtime library so it safe to make such
1061   // replacement.
1062   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1063                          getThreadID(CGF, Loc)};
1064   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
1065 }
1066 
1067 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1068 /// the enum sched_type in kmp.h).
1069 enum OpenMPSchedType {
1070   /// \brief Lower bound for default (unordered) versions.
1071   OMP_sch_lower = 32,
1072   OMP_sch_static_chunked = 33,
1073   OMP_sch_static = 34,
1074   OMP_sch_dynamic_chunked = 35,
1075   OMP_sch_guided_chunked = 36,
1076   OMP_sch_runtime = 37,
1077   OMP_sch_auto = 38,
1078   /// \brief Lower bound for 'ordered' versions.
1079   OMP_ord_lower = 64,
1080   /// \brief Lower bound for 'nomerge' versions.
1081   OMP_nm_lower = 160,
1082 };
1083 
1084 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
1085 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1086                                           bool Chunked) {
1087   switch (ScheduleKind) {
1088   case OMPC_SCHEDULE_static:
1089     return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1090   case OMPC_SCHEDULE_dynamic:
1091     return OMP_sch_dynamic_chunked;
1092   case OMPC_SCHEDULE_guided:
1093     return OMP_sch_guided_chunked;
1094   case OMPC_SCHEDULE_auto:
1095     return OMP_sch_auto;
1096   case OMPC_SCHEDULE_runtime:
1097     return OMP_sch_runtime;
1098   case OMPC_SCHEDULE_unknown:
1099     assert(!Chunked && "chunk was specified but schedule kind not known");
1100     return OMP_sch_static;
1101   }
1102   llvm_unreachable("Unexpected runtime schedule");
1103 }
1104 
1105 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1106                                          bool Chunked) const {
1107   auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1108   return Schedule == OMP_sch_static;
1109 }
1110 
1111 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1112   auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1113   assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1114   return Schedule != OMP_sch_static;
1115 }
1116 
1117 void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1118                                   OpenMPScheduleClauseKind ScheduleKind,
1119                                   unsigned IVSize, bool IVSigned,
1120                                   llvm::Value *IL, llvm::Value *LB,
1121                                   llvm::Value *UB, llvm::Value *ST,
1122                                   llvm::Value *Chunk) {
1123   OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
1124   if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1125     // Call __kmpc_dispatch_init(
1126     //          ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1127     //          kmp_int[32|64] lower, kmp_int[32|64] upper,
1128     //          kmp_int[32|64] stride, kmp_int[32|64] chunk);
1129 
1130     // If the Chunk was not specified in the clause - use default value 1.
1131     if (Chunk == nullptr)
1132       Chunk = CGF.Builder.getIntN(IVSize, 1);
1133     llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1134                             getThreadID(CGF, Loc),
1135                             CGF.Builder.getInt32(Schedule), // Schedule type
1136                             CGF.Builder.getIntN(IVSize, 0), // Lower
1137                             UB,                             // Upper
1138                             CGF.Builder.getIntN(IVSize, 1), // Stride
1139                             Chunk                           // Chunk
1140     };
1141     CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1142   } else {
1143     // Call __kmpc_for_static_init(
1144     //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1145     //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1146     //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1147     //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
1148     if (Chunk == nullptr) {
1149       assert(Schedule == OMP_sch_static &&
1150              "expected static non-chunked schedule");
1151       // If the Chunk was not specified in the clause - use default value 1.
1152       Chunk = CGF.Builder.getIntN(IVSize, 1);
1153     } else
1154       assert(Schedule == OMP_sch_static_chunked &&
1155              "expected static chunked schedule");
1156     llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1157                             getThreadID(CGF, Loc),
1158                             CGF.Builder.getInt32(Schedule), // Schedule type
1159                             IL,                             // &isLastIter
1160                             LB,                             // &LB
1161                             UB,                             // &UB
1162                             ST,                             // &Stride
1163                             CGF.Builder.getIntN(IVSize, 1), // Incr
1164                             Chunk                           // Chunk
1165     };
1166     assert((IVSize == 32 || IVSize == 64) &&
1167            "Index size is not compatible with the omp runtime");
1168     auto F = IVSize == 32 ? (IVSigned ? OMPRTL__kmpc_for_static_init_4
1169                                       : OMPRTL__kmpc_for_static_init_4u)
1170                           : (IVSigned ? OMPRTL__kmpc_for_static_init_8
1171                                       : OMPRTL__kmpc_for_static_init_8u);
1172     CGF.EmitRuntimeCall(createRuntimeFunction(F), Args);
1173   }
1174 }
1175 
1176 void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1177                                     OpenMPScheduleClauseKind ScheduleKind) {
1178   assert((ScheduleKind == OMPC_SCHEDULE_static ||
1179           ScheduleKind == OMPC_SCHEDULE_unknown) &&
1180          "Non-static schedule kinds are not yet implemented");
1181   // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
1182   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1183                          getThreadID(CGF, Loc)};
1184   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1185                       Args);
1186 }
1187 
1188 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1189                                           SourceLocation Loc, unsigned IVSize,
1190                                           bool IVSigned, llvm::Value *IL,
1191                                           llvm::Value *LB, llvm::Value *UB,
1192                                           llvm::Value *ST) {
1193   // Call __kmpc_dispatch_next(
1194   //          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1195   //          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1196   //          kmp_int[32|64] *p_stride);
1197   llvm::Value *Args[] = {
1198       emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1199       IL, // &isLastIter
1200       LB, // &Lower
1201       UB, // &Upper
1202       ST  // &Stride
1203   };
1204   llvm::Value *Call =
1205       CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1206   return CGF.EmitScalarConversion(
1207       Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1208       CGF.getContext().BoolTy);
1209 }
1210 
1211 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1212                                            llvm::Value *NumThreads,
1213                                            SourceLocation Loc) {
1214   // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1215   llvm::Value *Args[] = {
1216       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1217       CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
1218   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1219                       Args);
1220 }
1221 
1222 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1223                                 SourceLocation Loc) {
1224   // Build call void __kmpc_flush(ident_t *loc)
1225   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1226                       emitUpdateLocation(CGF, Loc));
1227 }
1228 
1229 namespace {
1230 /// \brief Indexes of fields for type kmp_task_t.
1231 enum KmpTaskTFields {
1232   /// \brief List of shared variables.
1233   KmpTaskTShareds,
1234   /// \brief Task routine.
1235   KmpTaskTRoutine,
1236   /// \brief Partition id for the untied tasks.
1237   KmpTaskTPartId,
1238   /// \brief Function with call of destructors for private variables.
1239   KmpTaskTDestructors,
1240 };
1241 } // namespace
1242 
1243 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1244   if (!KmpRoutineEntryPtrTy) {
1245     // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1246     auto &C = CGM.getContext();
1247     QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1248     FunctionProtoType::ExtProtoInfo EPI;
1249     KmpRoutineEntryPtrQTy = C.getPointerType(
1250         C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1251     KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1252   }
1253 }
1254 
1255 static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1256                                  QualType FieldTy) {
1257   auto *Field = FieldDecl::Create(
1258       C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1259       C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1260       /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1261   Field->setAccess(AS_public);
1262   DC->addDecl(Field);
1263 }
1264 
1265 static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1266                                          QualType KmpInt32Ty,
1267                                          QualType KmpRoutineEntryPointerQTy) {
1268   auto &C = CGM.getContext();
1269   // Build struct kmp_task_t {
1270   //         void *              shareds;
1271   //         kmp_routine_entry_t routine;
1272   //         kmp_int32           part_id;
1273   //         kmp_routine_entry_t destructors;
1274   //         /*  private vars  */
1275   //       };
1276   auto *RD = C.buildImplicitRecord("kmp_task_t");
1277   RD->startDefinition();
1278   addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1279   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1280   addFieldToRecordDecl(C, RD, KmpInt32Ty);
1281   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1282   // TODO: add private fields.
1283   RD->completeDefinition();
1284   return C.getRecordType(RD);
1285 }
1286 
1287 /// \brief Emit a proxy function which accepts kmp_task_t as the second
1288 /// argument.
1289 /// \code
1290 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1291 ///   TaskFunction(gtid, tt->part_id, tt->shareds);
1292 ///   return 0;
1293 /// }
1294 /// \endcode
1295 static llvm::Value *
1296 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1297                       QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
1298                       QualType SharedsPtrTy, llvm::Value *TaskFunction) {
1299   auto &C = CGM.getContext();
1300   FunctionArgList Args;
1301   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1302   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1303                                 /*Id=*/nullptr, KmpTaskTPtrQTy);
1304   Args.push_back(&GtidArg);
1305   Args.push_back(&TaskTypeArg);
1306   FunctionType::ExtInfo Info;
1307   auto &TaskEntryFnInfo =
1308       CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1309                                                     /*isVariadic=*/false);
1310   auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1311   auto *TaskEntry =
1312       llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1313                              ".omp_task_entry.", &CGM.getModule());
1314   CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1315   CodeGenFunction CGF(CGM);
1316   CGF.disableDebugInfo();
1317   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1318 
1319   // TaskFunction(gtid, tt->part_id, tt->shareds);
1320   auto *GtidParam = CGF.EmitLoadOfScalar(
1321       CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1322       C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1323   auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1324       CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1325       CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
1326   auto *PartidPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1327                                                 /*Idx=*/KmpTaskTPartId);
1328   auto *PartidParam = CGF.EmitLoadOfScalar(
1329       PartidPtr, /*Volatile=*/false,
1330       C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1331   auto *SharedsPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1332                                                  /*Idx=*/KmpTaskTShareds);
1333   auto *SharedsParam =
1334       CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1335                            CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1336   llvm::Value *CallArgs[] = {
1337       GtidParam, PartidParam,
1338       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1339           SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1340   CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1341   CGF.EmitStoreThroughLValue(
1342       RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1343       CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1344   CGF.FinishFunction();
1345   return TaskEntry;
1346 }
1347 
1348 void CGOpenMPRuntime::emitTaskCall(
1349     CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1350     llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1351     llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1352   auto &C = CGM.getContext();
1353   auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1354   // Build type kmp_routine_entry_t (if not built yet).
1355   emitKmpRoutineEntryT(KmpInt32Ty);
1356   // Build particular struct kmp_task_t for the given task.
1357   auto KmpTaskQTy =
1358       createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1359   QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
1360   auto KmpTaskTPtrTy = CGF.ConvertType(KmpTaskQTy)->getPointerTo();
1361   auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1362   QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1363 
1364   // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1365   // kmp_task_t *tt);
1366   auto *TaskEntry = emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy,
1367                                           SharedsPtrTy, TaskFunction);
1368 
1369   // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1370   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1371   // kmp_routine_entry_t *task_entry);
1372   // Task flags. Format is taken from
1373   // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1374   // description of kmp_tasking_flags struct.
1375   const unsigned TiedFlag = 0x1;
1376   const unsigned FinalFlag = 0x2;
1377   unsigned Flags = Tied ? TiedFlag : 0;
1378   auto *TaskFlags =
1379       Final.getPointer()
1380           ? CGF.Builder.CreateSelect(Final.getPointer(),
1381                                      CGF.Builder.getInt32(FinalFlag),
1382                                      CGF.Builder.getInt32(/*C=*/0))
1383           : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1384   TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1385   auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1386   llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1387                               getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1388                               CGM.getSize(SharedsSize),
1389                               CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1390                                   TaskEntry, KmpRoutineEntryPtrTy)};
1391   auto *NewTask = CGF.EmitRuntimeCall(
1392       createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1393   auto *NewTaskNewTaskTTy =
1394       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1395   // Fill the data in the resulting kmp_task_t record.
1396   // Copy shareds if there are any.
1397   if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1398     CGF.EmitAggregateCopy(
1399         CGF.EmitLoadOfScalar(
1400             CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1401                                         /*Idx=*/KmpTaskTShareds),
1402             /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1403         Shareds, SharedsTy);
1404   // TODO: generate function with destructors for privates.
1405   // Provide pointer to function with destructors for privates.
1406   CGF.Builder.CreateAlignedStore(
1407       llvm::ConstantPointerNull::get(
1408           cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
1409       CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1410                                   /*Idx=*/KmpTaskTDestructors),
1411       CGM.PointerAlignInBytes);
1412 
1413   // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1414   // libcall.
1415   // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1416   // *new_task);
1417   llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1418                              getThreadID(CGF, Loc), NewTask};
1419   // TODO: add check for untied tasks.
1420   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1421 }
1422 
1423 InlinedOpenMPRegionRAII::InlinedOpenMPRegionRAII(
1424     CodeGenFunction &CGF, const OMPExecutableDirective &D)
1425     : CGF(CGF) {
1426   CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(D, CGF.CapturedStmtInfo);
1427   // 1.2.2 OpenMP Language Terminology
1428   // Structured block - An executable statement with a single entry at the
1429   // top and a single exit at the bottom.
1430   // The point of exit cannot be a branch out of the structured block.
1431   // longjmp() and throw() must not violate the entry/exit criteria.
1432   CGF.EHStack.pushTerminate();
1433 }
1434 
1435 InlinedOpenMPRegionRAII::~InlinedOpenMPRegionRAII() {
1436   CGF.EHStack.popTerminate();
1437   auto *OldCSI =
1438       cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
1439   delete CGF.CapturedStmtInfo;
1440   CGF.CapturedStmtInfo = OldCSI;
1441 }
1442 
1443