CGOpenMPRuntimeNVPTX.cpp 214 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203
  1. //===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
  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. //
  9. // This provides a class for OpenMP runtime code generation specialized to NVPTX
  10. // targets.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGOpenMPRuntimeNVPTX.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/DeclOpenMP.h"
  16. #include "clang/AST/StmtOpenMP.h"
  17. #include "clang/AST/StmtVisitor.h"
  18. #include "clang/Basic/Cuda.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. namespace {
  23. enum OpenMPRTLFunctionNVPTX {
  24. /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
  25. /// int16_t RequiresOMPRuntime);
  26. OMPRTL_NVPTX__kmpc_kernel_init,
  27. /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
  28. OMPRTL_NVPTX__kmpc_kernel_deinit,
  29. /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
  30. /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
  31. OMPRTL_NVPTX__kmpc_spmd_kernel_init,
  32. /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
  33. OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
  34. /// Call to void __kmpc_kernel_prepare_parallel(void
  35. /// *outlined_function, int16_t
  36. /// IsOMPRuntimeInitialized);
  37. OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
  38. /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
  39. /// int16_t IsOMPRuntimeInitialized);
  40. OMPRTL_NVPTX__kmpc_kernel_parallel,
  41. /// Call to void __kmpc_kernel_end_parallel();
  42. OMPRTL_NVPTX__kmpc_kernel_end_parallel,
  43. /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  44. /// global_tid);
  45. OMPRTL_NVPTX__kmpc_serialized_parallel,
  46. /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  47. /// global_tid);
  48. OMPRTL_NVPTX__kmpc_end_serialized_parallel,
  49. /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
  50. /// int16_t lane_offset, int16_t warp_size);
  51. OMPRTL_NVPTX__kmpc_shuffle_int32,
  52. /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
  53. /// int16_t lane_offset, int16_t warp_size);
  54. OMPRTL_NVPTX__kmpc_shuffle_int64,
  55. /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
  56. /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
  57. /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
  58. /// lane_offset, int16_t shortCircuit),
  59. /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
  60. OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
  61. /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
  62. /// global_tid, void *global_buffer, int32_t num_of_records, void*
  63. /// reduce_data,
  64. /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
  65. /// lane_offset, int16_t shortCircuit),
  66. /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
  67. /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
  68. /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
  69. /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
  70. /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
  71. /// *buffer, int idx, void *reduce_data));
  72. OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
  73. /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
  74. OMPRTL_NVPTX__kmpc_end_reduce_nowait,
  75. /// Call to void __kmpc_data_sharing_init_stack();
  76. OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
  77. /// Call to void __kmpc_data_sharing_init_stack_spmd();
  78. OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
  79. /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
  80. /// int16_t UseSharedMemory);
  81. OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
  82. /// Call to void __kmpc_data_sharing_pop_stack(void *a);
  83. OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
  84. /// Call to void __kmpc_begin_sharing_variables(void ***args,
  85. /// size_t n_args);
  86. OMPRTL_NVPTX__kmpc_begin_sharing_variables,
  87. /// Call to void __kmpc_end_sharing_variables();
  88. OMPRTL_NVPTX__kmpc_end_sharing_variables,
  89. /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
  90. OMPRTL_NVPTX__kmpc_get_shared_variables,
  91. /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
  92. /// global_tid);
  93. OMPRTL_NVPTX__kmpc_parallel_level,
  94. /// Call to int8_t __kmpc_is_spmd_exec_mode();
  95. OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
  96. /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
  97. /// const void *buf, size_t size, int16_t is_shared, const void **res);
  98. OMPRTL_NVPTX__kmpc_get_team_static_memory,
  99. /// Call to void __kmpc_restore_team_static_memory(int16_t
  100. /// isSPMDExecutionMode, int16_t is_shared);
  101. OMPRTL_NVPTX__kmpc_restore_team_static_memory,
  102. /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  103. OMPRTL__kmpc_barrier,
  104. /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
  105. /// global_tid);
  106. OMPRTL__kmpc_barrier_simple_spmd,
  107. /// Call to int32_t __kmpc_warp_active_thread_mask(void);
  108. OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
  109. /// Call to void __kmpc_syncwarp(int32_t Mask);
  110. OMPRTL_NVPTX__kmpc_syncwarp,
  111. };
  112. /// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
  113. class NVPTXActionTy final : public PrePostActionTy {
  114. llvm::FunctionCallee EnterCallee = nullptr;
  115. ArrayRef<llvm::Value *> EnterArgs;
  116. llvm::FunctionCallee ExitCallee = nullptr;
  117. ArrayRef<llvm::Value *> ExitArgs;
  118. bool Conditional = false;
  119. llvm::BasicBlock *ContBlock = nullptr;
  120. public:
  121. NVPTXActionTy(llvm::FunctionCallee EnterCallee,
  122. ArrayRef<llvm::Value *> EnterArgs,
  123. llvm::FunctionCallee ExitCallee,
  124. ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
  125. : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
  126. ExitArgs(ExitArgs), Conditional(Conditional) {}
  127. void Enter(CodeGenFunction &CGF) override {
  128. llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
  129. if (Conditional) {
  130. llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
  131. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  132. ContBlock = CGF.createBasicBlock("omp_if.end");
  133. // Generate the branch (If-stmt)
  134. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  135. CGF.EmitBlock(ThenBlock);
  136. }
  137. }
  138. void Done(CodeGenFunction &CGF) {
  139. // Emit the rest of blocks/branches
  140. CGF.EmitBranch(ContBlock);
  141. CGF.EmitBlock(ContBlock, true);
  142. }
  143. void Exit(CodeGenFunction &CGF) override {
  144. CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
  145. }
  146. };
  147. /// A class to track the execution mode when codegening directives within
  148. /// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
  149. /// to the target region and used by containing directives such as 'parallel'
  150. /// to emit optimized code.
  151. class ExecutionRuntimeModesRAII {
  152. private:
  153. CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
  154. CGOpenMPRuntimeNVPTX::EM_Unknown;
  155. CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
  156. bool SavedRuntimeMode = false;
  157. bool *RuntimeMode = nullptr;
  158. public:
  159. /// Constructor for Non-SPMD mode.
  160. ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
  161. : ExecMode(ExecMode) {
  162. SavedExecMode = ExecMode;
  163. ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
  164. }
  165. /// Constructor for SPMD mode.
  166. ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
  167. bool &RuntimeMode, bool FullRuntimeMode)
  168. : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
  169. SavedExecMode = ExecMode;
  170. SavedRuntimeMode = RuntimeMode;
  171. ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
  172. RuntimeMode = FullRuntimeMode;
  173. }
  174. ~ExecutionRuntimeModesRAII() {
  175. ExecMode = SavedExecMode;
  176. if (RuntimeMode)
  177. *RuntimeMode = SavedRuntimeMode;
  178. }
  179. };
  180. /// GPU Configuration: This information can be derived from cuda registers,
  181. /// however, providing compile time constants helps generate more efficient
  182. /// code. For all practical purposes this is fine because the configuration
  183. /// is the same for all known NVPTX architectures.
  184. enum MachineConfiguration : unsigned {
  185. WarpSize = 32,
  186. /// Number of bits required to represent a lane identifier, which is
  187. /// computed as log_2(WarpSize).
  188. LaneIDBits = 5,
  189. LaneIDMask = WarpSize - 1,
  190. /// Global memory alignment for performance.
  191. GlobalMemoryAlignment = 128,
  192. /// Maximal size of the shared memory buffer.
  193. SharedMemorySize = 128,
  194. };
  195. static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
  196. RefExpr = RefExpr->IgnoreParens();
  197. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
  198. const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  199. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  200. Base = TempASE->getBase()->IgnoreParenImpCasts();
  201. RefExpr = Base;
  202. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
  203. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  204. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  205. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  206. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  207. Base = TempASE->getBase()->IgnoreParenImpCasts();
  208. RefExpr = Base;
  209. }
  210. RefExpr = RefExpr->IgnoreParenImpCasts();
  211. if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
  212. return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
  213. const auto *ME = cast<MemberExpr>(RefExpr);
  214. return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
  215. }
  216. static RecordDecl *buildRecordForGlobalizedVars(
  217. ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
  218. ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
  219. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  220. &MappedDeclsFields, int BufSize) {
  221. using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
  222. if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
  223. return nullptr;
  224. SmallVector<VarsDataTy, 4> GlobalizedVars;
  225. for (const ValueDecl *D : EscapedDecls)
  226. GlobalizedVars.emplace_back(
  227. CharUnits::fromQuantity(std::max(
  228. C.getDeclAlign(D).getQuantity(),
  229. static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
  230. D);
  231. for (const ValueDecl *D : EscapedDeclsForTeams)
  232. GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
  233. llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
  234. return L.first > R.first;
  235. });
  236. // Build struct _globalized_locals_ty {
  237. // /* globalized vars */[WarSize] align (max(decl_align,
  238. // GlobalMemoryAlignment))
  239. // /* globalized vars */ for EscapedDeclsForTeams
  240. // };
  241. RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
  242. GlobalizedRD->startDefinition();
  243. llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
  244. EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
  245. for (const auto &Pair : GlobalizedVars) {
  246. const ValueDecl *VD = Pair.second;
  247. QualType Type = VD->getType();
  248. if (Type->isLValueReferenceType())
  249. Type = C.getPointerType(Type.getNonReferenceType());
  250. else
  251. Type = Type.getNonReferenceType();
  252. SourceLocation Loc = VD->getLocation();
  253. FieldDecl *Field;
  254. if (SingleEscaped.count(VD)) {
  255. Field = FieldDecl::Create(
  256. C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
  257. C.getTrivialTypeSourceInfo(Type, SourceLocation()),
  258. /*BW=*/nullptr, /*Mutable=*/false,
  259. /*InitStyle=*/ICIS_NoInit);
  260. Field->setAccess(AS_public);
  261. if (VD->hasAttrs()) {
  262. for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
  263. E(VD->getAttrs().end());
  264. I != E; ++I)
  265. Field->addAttr(*I);
  266. }
  267. } else {
  268. llvm::APInt ArraySize(32, BufSize);
  269. Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
  270. 0);
  271. Field = FieldDecl::Create(
  272. C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
  273. C.getTrivialTypeSourceInfo(Type, SourceLocation()),
  274. /*BW=*/nullptr, /*Mutable=*/false,
  275. /*InitStyle=*/ICIS_NoInit);
  276. Field->setAccess(AS_public);
  277. llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
  278. static_cast<CharUnits::QuantityType>(
  279. GlobalMemoryAlignment)));
  280. Field->addAttr(AlignedAttr::CreateImplicit(
  281. C, /*IsAlignmentExpr=*/true,
  282. IntegerLiteral::Create(C, Align,
  283. C.getIntTypeForBitwidth(32, /*Signed=*/0),
  284. SourceLocation()),
  285. {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
  286. }
  287. GlobalizedRD->addDecl(Field);
  288. MappedDeclsFields.try_emplace(VD, Field);
  289. }
  290. GlobalizedRD->completeDefinition();
  291. return GlobalizedRD;
  292. }
  293. /// Get the list of variables that can escape their declaration context.
  294. class CheckVarsEscapingDeclContext final
  295. : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
  296. CodeGenFunction &CGF;
  297. llvm::SetVector<const ValueDecl *> EscapedDecls;
  298. llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
  299. llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
  300. RecordDecl *GlobalizedRD = nullptr;
  301. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
  302. bool AllEscaped = false;
  303. bool IsForCombinedParallelRegion = false;
  304. void markAsEscaped(const ValueDecl *VD) {
  305. // Do not globalize declare target variables.
  306. if (!isa<VarDecl>(VD) ||
  307. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  308. return;
  309. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  310. // Use user-specified allocation.
  311. if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
  312. return;
  313. // Variables captured by value must be globalized.
  314. if (auto *CSI = CGF.CapturedStmtInfo) {
  315. if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
  316. // Check if need to capture the variable that was already captured by
  317. // value in the outer region.
  318. if (!IsForCombinedParallelRegion) {
  319. if (!FD->hasAttrs())
  320. return;
  321. const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
  322. if (!Attr)
  323. return;
  324. if (((Attr->getCaptureKind() != OMPC_map) &&
  325. !isOpenMPPrivate(
  326. static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
  327. ((Attr->getCaptureKind() == OMPC_map) &&
  328. !FD->getType()->isAnyPointerType()))
  329. return;
  330. }
  331. if (!FD->getType()->isReferenceType()) {
  332. assert(!VD->getType()->isVariablyModifiedType() &&
  333. "Parameter captured by value with variably modified type");
  334. EscapedParameters.insert(VD);
  335. } else if (!IsForCombinedParallelRegion) {
  336. return;
  337. }
  338. }
  339. }
  340. if ((!CGF.CapturedStmtInfo ||
  341. (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
  342. VD->getType()->isReferenceType())
  343. // Do not globalize variables with reference type.
  344. return;
  345. if (VD->getType()->isVariablyModifiedType())
  346. EscapedVariableLengthDecls.insert(VD);
  347. else
  348. EscapedDecls.insert(VD);
  349. }
  350. void VisitValueDecl(const ValueDecl *VD) {
  351. if (VD->getType()->isLValueReferenceType())
  352. markAsEscaped(VD);
  353. if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
  354. if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
  355. const bool SavedAllEscaped = AllEscaped;
  356. AllEscaped = VD->getType()->isLValueReferenceType();
  357. Visit(VarD->getInit());
  358. AllEscaped = SavedAllEscaped;
  359. }
  360. }
  361. }
  362. void VisitOpenMPCapturedStmt(const CapturedStmt *S,
  363. ArrayRef<OMPClause *> Clauses,
  364. bool IsCombinedParallelRegion) {
  365. if (!S)
  366. return;
  367. for (const CapturedStmt::Capture &C : S->captures()) {
  368. if (C.capturesVariable() && !C.capturesVariableByCopy()) {
  369. const ValueDecl *VD = C.getCapturedVar();
  370. bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
  371. if (IsCombinedParallelRegion) {
  372. // Check if the variable is privatized in the combined construct and
  373. // those private copies must be shared in the inner parallel
  374. // directive.
  375. IsForCombinedParallelRegion = false;
  376. for (const OMPClause *C : Clauses) {
  377. if (!isOpenMPPrivate(C->getClauseKind()) ||
  378. C->getClauseKind() == OMPC_reduction ||
  379. C->getClauseKind() == OMPC_linear ||
  380. C->getClauseKind() == OMPC_private)
  381. continue;
  382. ArrayRef<const Expr *> Vars;
  383. if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
  384. Vars = PC->getVarRefs();
  385. else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
  386. Vars = PC->getVarRefs();
  387. else
  388. llvm_unreachable("Unexpected clause.");
  389. for (const auto *E : Vars) {
  390. const Decl *D =
  391. cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
  392. if (D == VD->getCanonicalDecl()) {
  393. IsForCombinedParallelRegion = true;
  394. break;
  395. }
  396. }
  397. if (IsForCombinedParallelRegion)
  398. break;
  399. }
  400. }
  401. markAsEscaped(VD);
  402. if (isa<OMPCapturedExprDecl>(VD))
  403. VisitValueDecl(VD);
  404. IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
  405. }
  406. }
  407. }
  408. void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
  409. assert(!GlobalizedRD &&
  410. "Record for globalized variables is built already.");
  411. ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
  412. if (IsInTTDRegion)
  413. EscapedDeclsForTeams = EscapedDecls.getArrayRef();
  414. else
  415. EscapedDeclsForParallel = EscapedDecls.getArrayRef();
  416. GlobalizedRD = ::buildRecordForGlobalizedVars(
  417. CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
  418. MappedDeclsFields, WarpSize);
  419. }
  420. public:
  421. CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
  422. ArrayRef<const ValueDecl *> TeamsReductions)
  423. : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
  424. }
  425. virtual ~CheckVarsEscapingDeclContext() = default;
  426. void VisitDeclStmt(const DeclStmt *S) {
  427. if (!S)
  428. return;
  429. for (const Decl *D : S->decls())
  430. if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
  431. VisitValueDecl(VD);
  432. }
  433. void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
  434. if (!D)
  435. return;
  436. if (!D->hasAssociatedStmt())
  437. return;
  438. if (const auto *S =
  439. dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
  440. // Do not analyze directives that do not actually require capturing,
  441. // like `omp for` or `omp simd` directives.
  442. llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  443. getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
  444. if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
  445. VisitStmt(S->getCapturedStmt());
  446. return;
  447. }
  448. VisitOpenMPCapturedStmt(
  449. S, D->clauses(),
  450. CaptureRegions.back() == OMPD_parallel &&
  451. isOpenMPDistributeDirective(D->getDirectiveKind()));
  452. }
  453. }
  454. void VisitCapturedStmt(const CapturedStmt *S) {
  455. if (!S)
  456. return;
  457. for (const CapturedStmt::Capture &C : S->captures()) {
  458. if (C.capturesVariable() && !C.capturesVariableByCopy()) {
  459. const ValueDecl *VD = C.getCapturedVar();
  460. markAsEscaped(VD);
  461. if (isa<OMPCapturedExprDecl>(VD))
  462. VisitValueDecl(VD);
  463. }
  464. }
  465. }
  466. void VisitLambdaExpr(const LambdaExpr *E) {
  467. if (!E)
  468. return;
  469. for (const LambdaCapture &C : E->captures()) {
  470. if (C.capturesVariable()) {
  471. if (C.getCaptureKind() == LCK_ByRef) {
  472. const ValueDecl *VD = C.getCapturedVar();
  473. markAsEscaped(VD);
  474. if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
  475. VisitValueDecl(VD);
  476. }
  477. }
  478. }
  479. }
  480. void VisitBlockExpr(const BlockExpr *E) {
  481. if (!E)
  482. return;
  483. for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
  484. if (C.isByRef()) {
  485. const VarDecl *VD = C.getVariable();
  486. markAsEscaped(VD);
  487. if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
  488. VisitValueDecl(VD);
  489. }
  490. }
  491. }
  492. void VisitCallExpr(const CallExpr *E) {
  493. if (!E)
  494. return;
  495. for (const Expr *Arg : E->arguments()) {
  496. if (!Arg)
  497. continue;
  498. if (Arg->isLValue()) {
  499. const bool SavedAllEscaped = AllEscaped;
  500. AllEscaped = true;
  501. Visit(Arg);
  502. AllEscaped = SavedAllEscaped;
  503. } else {
  504. Visit(Arg);
  505. }
  506. }
  507. Visit(E->getCallee());
  508. }
  509. void VisitDeclRefExpr(const DeclRefExpr *E) {
  510. if (!E)
  511. return;
  512. const ValueDecl *VD = E->getDecl();
  513. if (AllEscaped)
  514. markAsEscaped(VD);
  515. if (isa<OMPCapturedExprDecl>(VD))
  516. VisitValueDecl(VD);
  517. else if (const auto *VarD = dyn_cast<VarDecl>(VD))
  518. if (VarD->isInitCapture())
  519. VisitValueDecl(VD);
  520. }
  521. void VisitUnaryOperator(const UnaryOperator *E) {
  522. if (!E)
  523. return;
  524. if (E->getOpcode() == UO_AddrOf) {
  525. const bool SavedAllEscaped = AllEscaped;
  526. AllEscaped = true;
  527. Visit(E->getSubExpr());
  528. AllEscaped = SavedAllEscaped;
  529. } else {
  530. Visit(E->getSubExpr());
  531. }
  532. }
  533. void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
  534. if (!E)
  535. return;
  536. if (E->getCastKind() == CK_ArrayToPointerDecay) {
  537. const bool SavedAllEscaped = AllEscaped;
  538. AllEscaped = true;
  539. Visit(E->getSubExpr());
  540. AllEscaped = SavedAllEscaped;
  541. } else {
  542. Visit(E->getSubExpr());
  543. }
  544. }
  545. void VisitExpr(const Expr *E) {
  546. if (!E)
  547. return;
  548. bool SavedAllEscaped = AllEscaped;
  549. if (!E->isLValue())
  550. AllEscaped = false;
  551. for (const Stmt *Child : E->children())
  552. if (Child)
  553. Visit(Child);
  554. AllEscaped = SavedAllEscaped;
  555. }
  556. void VisitStmt(const Stmt *S) {
  557. if (!S)
  558. return;
  559. for (const Stmt *Child : S->children())
  560. if (Child)
  561. Visit(Child);
  562. }
  563. /// Returns the record that handles all the escaped local variables and used
  564. /// instead of their original storage.
  565. const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
  566. if (!GlobalizedRD)
  567. buildRecordForGlobalizedVars(IsInTTDRegion);
  568. return GlobalizedRD;
  569. }
  570. /// Returns the field in the globalized record for the escaped variable.
  571. const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
  572. assert(GlobalizedRD &&
  573. "Record for globalized variables must be generated already.");
  574. auto I = MappedDeclsFields.find(VD);
  575. if (I == MappedDeclsFields.end())
  576. return nullptr;
  577. return I->getSecond();
  578. }
  579. /// Returns the list of the escaped local variables/parameters.
  580. ArrayRef<const ValueDecl *> getEscapedDecls() const {
  581. return EscapedDecls.getArrayRef();
  582. }
  583. /// Checks if the escaped local variable is actually a parameter passed by
  584. /// value.
  585. const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
  586. return EscapedParameters;
  587. }
  588. /// Returns the list of the escaped variables with the variably modified
  589. /// types.
  590. ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
  591. return EscapedVariableLengthDecls.getArrayRef();
  592. }
  593. };
  594. } // anonymous namespace
  595. /// Get the GPU warp size.
  596. static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
  597. return CGF.EmitRuntimeCall(
  598. llvm::Intrinsic::getDeclaration(
  599. &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
  600. "nvptx_warp_size");
  601. }
  602. /// Get the id of the current thread on the GPU.
  603. static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
  604. return CGF.EmitRuntimeCall(
  605. llvm::Intrinsic::getDeclaration(
  606. &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
  607. "nvptx_tid");
  608. }
  609. /// Get the id of the warp in the block.
  610. /// We assume that the warp size is 32, which is always the case
  611. /// on the NVPTX device, to generate more efficient code.
  612. static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
  613. CGBuilderTy &Bld = CGF.Builder;
  614. return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
  615. }
  616. /// Get the id of the current lane in the Warp.
  617. /// We assume that the warp size is 32, which is always the case
  618. /// on the NVPTX device, to generate more efficient code.
  619. static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
  620. CGBuilderTy &Bld = CGF.Builder;
  621. return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
  622. "nvptx_lane_id");
  623. }
  624. /// Get the maximum number of threads in a block of the GPU.
  625. static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
  626. return CGF.EmitRuntimeCall(
  627. llvm::Intrinsic::getDeclaration(
  628. &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
  629. "nvptx_num_threads");
  630. }
  631. /// Get the value of the thread_limit clause in the teams directive.
  632. /// For the 'generic' execution mode, the runtime encodes thread_limit in
  633. /// the launch parameters, always starting thread_limit+warpSize threads per
  634. /// CTA. The threads in the last warp are reserved for master execution.
  635. /// For the 'spmd' execution mode, all threads in a CTA are part of the team.
  636. static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
  637. bool IsInSPMDExecutionMode = false) {
  638. CGBuilderTy &Bld = CGF.Builder;
  639. return IsInSPMDExecutionMode
  640. ? getNVPTXNumThreads(CGF)
  641. : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
  642. "thread_limit");
  643. }
  644. /// Get the thread id of the OMP master thread.
  645. /// The master thread id is the first thread (lane) of the last warp in the
  646. /// GPU block. Warp size is assumed to be some power of 2.
  647. /// Thread id is 0 indexed.
  648. /// E.g: If NumThreads is 33, master id is 32.
  649. /// If NumThreads is 64, master id is 32.
  650. /// If NumThreads is 1024, master id is 992.
  651. static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
  652. CGBuilderTy &Bld = CGF.Builder;
  653. llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
  654. // We assume that the warp size is a power of 2.
  655. llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
  656. return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
  657. Bld.CreateNot(Mask), "master_tid");
  658. }
  659. CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
  660. CodeGenModule &CGM, SourceLocation Loc)
  661. : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
  662. Loc(Loc) {
  663. createWorkerFunction(CGM);
  664. }
  665. void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
  666. CodeGenModule &CGM) {
  667. // Create an worker function with no arguments.
  668. WorkerFn = llvm::Function::Create(
  669. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  670. /*placeholder=*/"_worker", &CGM.getModule());
  671. CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
  672. WorkerFn->setDoesNotRecurse();
  673. }
  674. CGOpenMPRuntimeNVPTX::ExecutionMode
  675. CGOpenMPRuntimeNVPTX::getExecutionMode() const {
  676. return CurrentExecutionMode;
  677. }
  678. static CGOpenMPRuntimeNVPTX::DataSharingMode
  679. getDataSharingMode(CodeGenModule &CGM) {
  680. return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
  681. : CGOpenMPRuntimeNVPTX::Generic;
  682. }
  683. /// Check for inner (nested) SPMD construct, if any
  684. static bool hasNestedSPMDDirective(ASTContext &Ctx,
  685. const OMPExecutableDirective &D) {
  686. const auto *CS = D.getInnermostCapturedStmt();
  687. const auto *Body =
  688. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  689. const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  690. if (const auto *NestedDir =
  691. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  692. OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
  693. switch (D.getDirectiveKind()) {
  694. case OMPD_target:
  695. if (isOpenMPParallelDirective(DKind))
  696. return true;
  697. if (DKind == OMPD_teams) {
  698. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  699. /*IgnoreCaptured=*/true);
  700. if (!Body)
  701. return false;
  702. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  703. if (const auto *NND =
  704. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  705. DKind = NND->getDirectiveKind();
  706. if (isOpenMPParallelDirective(DKind))
  707. return true;
  708. }
  709. }
  710. return false;
  711. case OMPD_target_teams:
  712. return isOpenMPParallelDirective(DKind);
  713. case OMPD_target_simd:
  714. case OMPD_target_parallel:
  715. case OMPD_target_parallel_for:
  716. case OMPD_target_parallel_for_simd:
  717. case OMPD_target_teams_distribute:
  718. case OMPD_target_teams_distribute_simd:
  719. case OMPD_target_teams_distribute_parallel_for:
  720. case OMPD_target_teams_distribute_parallel_for_simd:
  721. case OMPD_parallel:
  722. case OMPD_for:
  723. case OMPD_parallel_for:
  724. case OMPD_parallel_sections:
  725. case OMPD_for_simd:
  726. case OMPD_parallel_for_simd:
  727. case OMPD_cancel:
  728. case OMPD_cancellation_point:
  729. case OMPD_ordered:
  730. case OMPD_threadprivate:
  731. case OMPD_allocate:
  732. case OMPD_task:
  733. case OMPD_simd:
  734. case OMPD_sections:
  735. case OMPD_section:
  736. case OMPD_single:
  737. case OMPD_master:
  738. case OMPD_critical:
  739. case OMPD_taskyield:
  740. case OMPD_barrier:
  741. case OMPD_taskwait:
  742. case OMPD_taskgroup:
  743. case OMPD_atomic:
  744. case OMPD_flush:
  745. case OMPD_teams:
  746. case OMPD_target_data:
  747. case OMPD_target_exit_data:
  748. case OMPD_target_enter_data:
  749. case OMPD_distribute:
  750. case OMPD_distribute_simd:
  751. case OMPD_distribute_parallel_for:
  752. case OMPD_distribute_parallel_for_simd:
  753. case OMPD_teams_distribute:
  754. case OMPD_teams_distribute_simd:
  755. case OMPD_teams_distribute_parallel_for:
  756. case OMPD_teams_distribute_parallel_for_simd:
  757. case OMPD_target_update:
  758. case OMPD_declare_simd:
  759. case OMPD_declare_variant:
  760. case OMPD_declare_target:
  761. case OMPD_end_declare_target:
  762. case OMPD_declare_reduction:
  763. case OMPD_declare_mapper:
  764. case OMPD_taskloop:
  765. case OMPD_taskloop_simd:
  766. case OMPD_master_taskloop:
  767. case OMPD_master_taskloop_simd:
  768. case OMPD_parallel_master_taskloop:
  769. case OMPD_requires:
  770. case OMPD_unknown:
  771. llvm_unreachable("Unexpected directive.");
  772. }
  773. }
  774. return false;
  775. }
  776. static bool supportsSPMDExecutionMode(ASTContext &Ctx,
  777. const OMPExecutableDirective &D) {
  778. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  779. switch (DirectiveKind) {
  780. case OMPD_target:
  781. case OMPD_target_teams:
  782. return hasNestedSPMDDirective(Ctx, D);
  783. case OMPD_target_parallel:
  784. case OMPD_target_parallel_for:
  785. case OMPD_target_parallel_for_simd:
  786. case OMPD_target_teams_distribute_parallel_for:
  787. case OMPD_target_teams_distribute_parallel_for_simd:
  788. case OMPD_target_simd:
  789. case OMPD_target_teams_distribute_simd:
  790. return true;
  791. case OMPD_target_teams_distribute:
  792. return false;
  793. case OMPD_parallel:
  794. case OMPD_for:
  795. case OMPD_parallel_for:
  796. case OMPD_parallel_sections:
  797. case OMPD_for_simd:
  798. case OMPD_parallel_for_simd:
  799. case OMPD_cancel:
  800. case OMPD_cancellation_point:
  801. case OMPD_ordered:
  802. case OMPD_threadprivate:
  803. case OMPD_allocate:
  804. case OMPD_task:
  805. case OMPD_simd:
  806. case OMPD_sections:
  807. case OMPD_section:
  808. case OMPD_single:
  809. case OMPD_master:
  810. case OMPD_critical:
  811. case OMPD_taskyield:
  812. case OMPD_barrier:
  813. case OMPD_taskwait:
  814. case OMPD_taskgroup:
  815. case OMPD_atomic:
  816. case OMPD_flush:
  817. case OMPD_teams:
  818. case OMPD_target_data:
  819. case OMPD_target_exit_data:
  820. case OMPD_target_enter_data:
  821. case OMPD_distribute:
  822. case OMPD_distribute_simd:
  823. case OMPD_distribute_parallel_for:
  824. case OMPD_distribute_parallel_for_simd:
  825. case OMPD_teams_distribute:
  826. case OMPD_teams_distribute_simd:
  827. case OMPD_teams_distribute_parallel_for:
  828. case OMPD_teams_distribute_parallel_for_simd:
  829. case OMPD_target_update:
  830. case OMPD_declare_simd:
  831. case OMPD_declare_variant:
  832. case OMPD_declare_target:
  833. case OMPD_end_declare_target:
  834. case OMPD_declare_reduction:
  835. case OMPD_declare_mapper:
  836. case OMPD_taskloop:
  837. case OMPD_taskloop_simd:
  838. case OMPD_master_taskloop:
  839. case OMPD_master_taskloop_simd:
  840. case OMPD_parallel_master_taskloop:
  841. case OMPD_requires:
  842. case OMPD_unknown:
  843. break;
  844. }
  845. llvm_unreachable(
  846. "Unknown programming model for OpenMP directive on NVPTX target.");
  847. }
  848. /// Check if the directive is loops based and has schedule clause at all or has
  849. /// static scheduling.
  850. static bool hasStaticScheduling(const OMPExecutableDirective &D) {
  851. assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
  852. isOpenMPLoopDirective(D.getDirectiveKind()) &&
  853. "Expected loop-based directive.");
  854. return !D.hasClausesOfKind<OMPOrderedClause>() &&
  855. (!D.hasClausesOfKind<OMPScheduleClause>() ||
  856. llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
  857. [](const OMPScheduleClause *C) {
  858. return C->getScheduleKind() == OMPC_SCHEDULE_static;
  859. }));
  860. }
  861. /// Check for inner (nested) lightweight runtime construct, if any
  862. static bool hasNestedLightweightDirective(ASTContext &Ctx,
  863. const OMPExecutableDirective &D) {
  864. assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
  865. const auto *CS = D.getInnermostCapturedStmt();
  866. const auto *Body =
  867. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  868. const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  869. if (const auto *NestedDir =
  870. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  871. OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
  872. switch (D.getDirectiveKind()) {
  873. case OMPD_target:
  874. if (isOpenMPParallelDirective(DKind) &&
  875. isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
  876. hasStaticScheduling(*NestedDir))
  877. return true;
  878. if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
  879. return true;
  880. if (DKind == OMPD_parallel) {
  881. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  882. /*IgnoreCaptured=*/true);
  883. if (!Body)
  884. return false;
  885. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  886. if (const auto *NND =
  887. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  888. DKind = NND->getDirectiveKind();
  889. if (isOpenMPWorksharingDirective(DKind) &&
  890. isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
  891. return true;
  892. }
  893. } else if (DKind == OMPD_teams) {
  894. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  895. /*IgnoreCaptured=*/true);
  896. if (!Body)
  897. return false;
  898. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  899. if (const auto *NND =
  900. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  901. DKind = NND->getDirectiveKind();
  902. if (isOpenMPParallelDirective(DKind) &&
  903. isOpenMPWorksharingDirective(DKind) &&
  904. isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
  905. return true;
  906. if (DKind == OMPD_parallel) {
  907. Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
  908. /*IgnoreCaptured=*/true);
  909. if (!Body)
  910. return false;
  911. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  912. if (const auto *NND =
  913. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  914. DKind = NND->getDirectiveKind();
  915. if (isOpenMPWorksharingDirective(DKind) &&
  916. isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
  917. return true;
  918. }
  919. }
  920. }
  921. }
  922. return false;
  923. case OMPD_target_teams:
  924. if (isOpenMPParallelDirective(DKind) &&
  925. isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
  926. hasStaticScheduling(*NestedDir))
  927. return true;
  928. if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
  929. return true;
  930. if (DKind == OMPD_parallel) {
  931. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  932. /*IgnoreCaptured=*/true);
  933. if (!Body)
  934. return false;
  935. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  936. if (const auto *NND =
  937. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  938. DKind = NND->getDirectiveKind();
  939. if (isOpenMPWorksharingDirective(DKind) &&
  940. isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
  941. return true;
  942. }
  943. }
  944. return false;
  945. case OMPD_target_parallel:
  946. if (DKind == OMPD_simd)
  947. return true;
  948. return isOpenMPWorksharingDirective(DKind) &&
  949. isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
  950. case OMPD_target_teams_distribute:
  951. case OMPD_target_simd:
  952. case OMPD_target_parallel_for:
  953. case OMPD_target_parallel_for_simd:
  954. case OMPD_target_teams_distribute_simd:
  955. case OMPD_target_teams_distribute_parallel_for:
  956. case OMPD_target_teams_distribute_parallel_for_simd:
  957. case OMPD_parallel:
  958. case OMPD_for:
  959. case OMPD_parallel_for:
  960. case OMPD_parallel_sections:
  961. case OMPD_for_simd:
  962. case OMPD_parallel_for_simd:
  963. case OMPD_cancel:
  964. case OMPD_cancellation_point:
  965. case OMPD_ordered:
  966. case OMPD_threadprivate:
  967. case OMPD_allocate:
  968. case OMPD_task:
  969. case OMPD_simd:
  970. case OMPD_sections:
  971. case OMPD_section:
  972. case OMPD_single:
  973. case OMPD_master:
  974. case OMPD_critical:
  975. case OMPD_taskyield:
  976. case OMPD_barrier:
  977. case OMPD_taskwait:
  978. case OMPD_taskgroup:
  979. case OMPD_atomic:
  980. case OMPD_flush:
  981. case OMPD_teams:
  982. case OMPD_target_data:
  983. case OMPD_target_exit_data:
  984. case OMPD_target_enter_data:
  985. case OMPD_distribute:
  986. case OMPD_distribute_simd:
  987. case OMPD_distribute_parallel_for:
  988. case OMPD_distribute_parallel_for_simd:
  989. case OMPD_teams_distribute:
  990. case OMPD_teams_distribute_simd:
  991. case OMPD_teams_distribute_parallel_for:
  992. case OMPD_teams_distribute_parallel_for_simd:
  993. case OMPD_target_update:
  994. case OMPD_declare_simd:
  995. case OMPD_declare_variant:
  996. case OMPD_declare_target:
  997. case OMPD_end_declare_target:
  998. case OMPD_declare_reduction:
  999. case OMPD_declare_mapper:
  1000. case OMPD_taskloop:
  1001. case OMPD_taskloop_simd:
  1002. case OMPD_master_taskloop:
  1003. case OMPD_master_taskloop_simd:
  1004. case OMPD_parallel_master_taskloop:
  1005. case OMPD_requires:
  1006. case OMPD_unknown:
  1007. llvm_unreachable("Unexpected directive.");
  1008. }
  1009. }
  1010. return false;
  1011. }
  1012. /// Checks if the construct supports lightweight runtime. It must be SPMD
  1013. /// construct + inner loop-based construct with static scheduling.
  1014. static bool supportsLightweightRuntime(ASTContext &Ctx,
  1015. const OMPExecutableDirective &D) {
  1016. if (!supportsSPMDExecutionMode(Ctx, D))
  1017. return false;
  1018. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  1019. switch (DirectiveKind) {
  1020. case OMPD_target:
  1021. case OMPD_target_teams:
  1022. case OMPD_target_parallel:
  1023. return hasNestedLightweightDirective(Ctx, D);
  1024. case OMPD_target_parallel_for:
  1025. case OMPD_target_parallel_for_simd:
  1026. case OMPD_target_teams_distribute_parallel_for:
  1027. case OMPD_target_teams_distribute_parallel_for_simd:
  1028. // (Last|First)-privates must be shared in parallel region.
  1029. return hasStaticScheduling(D);
  1030. case OMPD_target_simd:
  1031. case OMPD_target_teams_distribute_simd:
  1032. return true;
  1033. case OMPD_target_teams_distribute:
  1034. return false;
  1035. case OMPD_parallel:
  1036. case OMPD_for:
  1037. case OMPD_parallel_for:
  1038. case OMPD_parallel_sections:
  1039. case OMPD_for_simd:
  1040. case OMPD_parallel_for_simd:
  1041. case OMPD_cancel:
  1042. case OMPD_cancellation_point:
  1043. case OMPD_ordered:
  1044. case OMPD_threadprivate:
  1045. case OMPD_allocate:
  1046. case OMPD_task:
  1047. case OMPD_simd:
  1048. case OMPD_sections:
  1049. case OMPD_section:
  1050. case OMPD_single:
  1051. case OMPD_master:
  1052. case OMPD_critical:
  1053. case OMPD_taskyield:
  1054. case OMPD_barrier:
  1055. case OMPD_taskwait:
  1056. case OMPD_taskgroup:
  1057. case OMPD_atomic:
  1058. case OMPD_flush:
  1059. case OMPD_teams:
  1060. case OMPD_target_data:
  1061. case OMPD_target_exit_data:
  1062. case OMPD_target_enter_data:
  1063. case OMPD_distribute:
  1064. case OMPD_distribute_simd:
  1065. case OMPD_distribute_parallel_for:
  1066. case OMPD_distribute_parallel_for_simd:
  1067. case OMPD_teams_distribute:
  1068. case OMPD_teams_distribute_simd:
  1069. case OMPD_teams_distribute_parallel_for:
  1070. case OMPD_teams_distribute_parallel_for_simd:
  1071. case OMPD_target_update:
  1072. case OMPD_declare_simd:
  1073. case OMPD_declare_variant:
  1074. case OMPD_declare_target:
  1075. case OMPD_end_declare_target:
  1076. case OMPD_declare_reduction:
  1077. case OMPD_declare_mapper:
  1078. case OMPD_taskloop:
  1079. case OMPD_taskloop_simd:
  1080. case OMPD_master_taskloop:
  1081. case OMPD_master_taskloop_simd:
  1082. case OMPD_parallel_master_taskloop:
  1083. case OMPD_requires:
  1084. case OMPD_unknown:
  1085. break;
  1086. }
  1087. llvm_unreachable(
  1088. "Unknown programming model for OpenMP directive on NVPTX target.");
  1089. }
  1090. void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
  1091. StringRef ParentName,
  1092. llvm::Function *&OutlinedFn,
  1093. llvm::Constant *&OutlinedFnID,
  1094. bool IsOffloadEntry,
  1095. const RegionCodeGenTy &CodeGen) {
  1096. ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
  1097. EntryFunctionState EST;
  1098. WorkerFunctionState WST(CGM, D.getBeginLoc());
  1099. Work.clear();
  1100. WrapperFunctionsMap.clear();
  1101. // Emit target region as a standalone region.
  1102. class NVPTXPrePostActionTy : public PrePostActionTy {
  1103. CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
  1104. CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
  1105. public:
  1106. NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
  1107. CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
  1108. : EST(EST), WST(WST) {}
  1109. void Enter(CodeGenFunction &CGF) override {
  1110. auto &RT =
  1111. static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
  1112. RT.emitNonSPMDEntryHeader(CGF, EST, WST);
  1113. // Skip target region initialization.
  1114. RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
  1115. }
  1116. void Exit(CodeGenFunction &CGF) override {
  1117. auto &RT =
  1118. static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
  1119. RT.clearLocThreadIdInsertPt(CGF);
  1120. RT.emitNonSPMDEntryFooter(CGF, EST);
  1121. }
  1122. } Action(EST, WST);
  1123. CodeGen.setAction(Action);
  1124. IsInTTDRegion = true;
  1125. // Reserve place for the globalized memory.
  1126. GlobalizedRecords.emplace_back();
  1127. if (!KernelStaticGlobalized) {
  1128. KernelStaticGlobalized = new llvm::GlobalVariable(
  1129. CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
  1130. llvm::GlobalValue::InternalLinkage,
  1131. llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
  1132. "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
  1133. llvm::GlobalValue::NotThreadLocal,
  1134. CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
  1135. }
  1136. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  1137. IsOffloadEntry, CodeGen);
  1138. IsInTTDRegion = false;
  1139. // Now change the name of the worker function to correspond to this target
  1140. // region's entry function.
  1141. WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
  1142. // Create the worker function
  1143. emitWorkerFunction(WST);
  1144. }
  1145. // Setup NVPTX threads for master-worker OpenMP scheme.
  1146. void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
  1147. EntryFunctionState &EST,
  1148. WorkerFunctionState &WST) {
  1149. CGBuilderTy &Bld = CGF.Builder;
  1150. llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
  1151. llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
  1152. llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
  1153. EST.ExitBB = CGF.createBasicBlock(".exit");
  1154. llvm::Value *IsWorker =
  1155. Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
  1156. Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
  1157. CGF.EmitBlock(WorkerBB);
  1158. emitCall(CGF, WST.Loc, WST.WorkerFn);
  1159. CGF.EmitBranch(EST.ExitBB);
  1160. CGF.EmitBlock(MasterCheckBB);
  1161. llvm::Value *IsMaster =
  1162. Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
  1163. Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
  1164. CGF.EmitBlock(MasterBB);
  1165. IsInTargetMasterThreadRegion = true;
  1166. // SEQUENTIAL (MASTER) REGION START
  1167. // First action in sequential region:
  1168. // Initialize the state of the OpenMP runtime library on the GPU.
  1169. // TODO: Optimize runtime initialization and pass in correct value.
  1170. llvm::Value *Args[] = {getThreadLimit(CGF),
  1171. Bld.getInt16(/*RequiresOMPRuntime=*/1)};
  1172. CGF.EmitRuntimeCall(
  1173. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
  1174. // For data sharing, we need to initialize the stack.
  1175. CGF.EmitRuntimeCall(
  1176. createNVPTXRuntimeFunction(
  1177. OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
  1178. emitGenericVarsProlog(CGF, WST.Loc);
  1179. }
  1180. void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
  1181. EntryFunctionState &EST) {
  1182. IsInTargetMasterThreadRegion = false;
  1183. if (!CGF.HaveInsertPoint())
  1184. return;
  1185. emitGenericVarsEpilog(CGF);
  1186. if (!EST.ExitBB)
  1187. EST.ExitBB = CGF.createBasicBlock(".exit");
  1188. llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
  1189. CGF.EmitBranch(TerminateBB);
  1190. CGF.EmitBlock(TerminateBB);
  1191. // Signal termination condition.
  1192. // TODO: Optimize runtime initialization and pass in correct value.
  1193. llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
  1194. CGF.EmitRuntimeCall(
  1195. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
  1196. // Barrier to terminate worker threads.
  1197. syncCTAThreads(CGF);
  1198. // Master thread jumps to exit point.
  1199. CGF.EmitBranch(EST.ExitBB);
  1200. CGF.EmitBlock(EST.ExitBB);
  1201. EST.ExitBB = nullptr;
  1202. }
  1203. void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
  1204. StringRef ParentName,
  1205. llvm::Function *&OutlinedFn,
  1206. llvm::Constant *&OutlinedFnID,
  1207. bool IsOffloadEntry,
  1208. const RegionCodeGenTy &CodeGen) {
  1209. ExecutionRuntimeModesRAII ModeRAII(
  1210. CurrentExecutionMode, RequiresFullRuntime,
  1211. CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
  1212. !supportsLightweightRuntime(CGM.getContext(), D));
  1213. EntryFunctionState EST;
  1214. // Emit target region as a standalone region.
  1215. class NVPTXPrePostActionTy : public PrePostActionTy {
  1216. CGOpenMPRuntimeNVPTX &RT;
  1217. CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
  1218. const OMPExecutableDirective &D;
  1219. public:
  1220. NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
  1221. CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
  1222. const OMPExecutableDirective &D)
  1223. : RT(RT), EST(EST), D(D) {}
  1224. void Enter(CodeGenFunction &CGF) override {
  1225. RT.emitSPMDEntryHeader(CGF, EST, D);
  1226. // Skip target region initialization.
  1227. RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
  1228. }
  1229. void Exit(CodeGenFunction &CGF) override {
  1230. RT.clearLocThreadIdInsertPt(CGF);
  1231. RT.emitSPMDEntryFooter(CGF, EST);
  1232. }
  1233. } Action(*this, EST, D);
  1234. CodeGen.setAction(Action);
  1235. IsInTTDRegion = true;
  1236. // Reserve place for the globalized memory.
  1237. GlobalizedRecords.emplace_back();
  1238. if (!KernelStaticGlobalized) {
  1239. KernelStaticGlobalized = new llvm::GlobalVariable(
  1240. CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
  1241. llvm::GlobalValue::InternalLinkage,
  1242. llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
  1243. "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
  1244. llvm::GlobalValue::NotThreadLocal,
  1245. CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
  1246. }
  1247. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  1248. IsOffloadEntry, CodeGen);
  1249. IsInTTDRegion = false;
  1250. }
  1251. void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
  1252. CodeGenFunction &CGF, EntryFunctionState &EST,
  1253. const OMPExecutableDirective &D) {
  1254. CGBuilderTy &Bld = CGF.Builder;
  1255. // Setup BBs in entry function.
  1256. llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
  1257. EST.ExitBB = CGF.createBasicBlock(".exit");
  1258. llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
  1259. /*RequiresOMPRuntime=*/
  1260. Bld.getInt16(RequiresFullRuntime ? 1 : 0),
  1261. /*RequiresDataSharing=*/Bld.getInt16(0)};
  1262. CGF.EmitRuntimeCall(
  1263. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
  1264. if (RequiresFullRuntime) {
  1265. // For data sharing, we need to initialize the stack.
  1266. CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
  1267. OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
  1268. }
  1269. CGF.EmitBranch(ExecuteBB);
  1270. CGF.EmitBlock(ExecuteBB);
  1271. IsInTargetMasterThreadRegion = true;
  1272. }
  1273. void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
  1274. EntryFunctionState &EST) {
  1275. IsInTargetMasterThreadRegion = false;
  1276. if (!CGF.HaveInsertPoint())
  1277. return;
  1278. if (!EST.ExitBB)
  1279. EST.ExitBB = CGF.createBasicBlock(".exit");
  1280. llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
  1281. CGF.EmitBranch(OMPDeInitBB);
  1282. CGF.EmitBlock(OMPDeInitBB);
  1283. // DeInitialize the OMP state in the runtime; called by all active threads.
  1284. llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
  1285. CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
  1286. CGF.EmitRuntimeCall(
  1287. createNVPTXRuntimeFunction(
  1288. OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
  1289. CGF.EmitBranch(EST.ExitBB);
  1290. CGF.EmitBlock(EST.ExitBB);
  1291. EST.ExitBB = nullptr;
  1292. }
  1293. // Create a unique global variable to indicate the execution mode of this target
  1294. // region. The execution mode is either 'generic', or 'spmd' depending on the
  1295. // target directive. This variable is picked up by the offload library to setup
  1296. // the device appropriately before kernel launch. If the execution mode is
  1297. // 'generic', the runtime reserves one warp for the master, otherwise, all
  1298. // warps participate in parallel work.
  1299. static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
  1300. bool Mode) {
  1301. auto *GVMode =
  1302. new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  1303. llvm::GlobalValue::WeakAnyLinkage,
  1304. llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
  1305. Twine(Name, "_exec_mode"));
  1306. CGM.addCompilerUsedGlobal(GVMode);
  1307. }
  1308. void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
  1309. ASTContext &Ctx = CGM.getContext();
  1310. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  1311. CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
  1312. WST.Loc, WST.Loc);
  1313. emitWorkerLoop(CGF, WST);
  1314. CGF.FinishFunction();
  1315. }
  1316. void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
  1317. WorkerFunctionState &WST) {
  1318. //
  1319. // The workers enter this loop and wait for parallel work from the master.
  1320. // When the master encounters a parallel region it sets up the work + variable
  1321. // arguments, and wakes up the workers. The workers first check to see if
  1322. // they are required for the parallel region, i.e., within the # of requested
  1323. // parallel threads. The activated workers load the variable arguments and
  1324. // execute the parallel work.
  1325. //
  1326. CGBuilderTy &Bld = CGF.Builder;
  1327. llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
  1328. llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
  1329. llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
  1330. llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
  1331. llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
  1332. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
  1333. CGF.EmitBranch(AwaitBB);
  1334. // Workers wait for work from master.
  1335. CGF.EmitBlock(AwaitBB);
  1336. // Wait for parallel work
  1337. syncCTAThreads(CGF);
  1338. Address WorkFn =
  1339. CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
  1340. Address ExecStatus =
  1341. CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
  1342. CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
  1343. CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
  1344. // TODO: Optimize runtime initialization and pass in correct value.
  1345. llvm::Value *Args[] = {WorkFn.getPointer(),
  1346. /*RequiresOMPRuntime=*/Bld.getInt16(1)};
  1347. llvm::Value *Ret = CGF.EmitRuntimeCall(
  1348. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
  1349. Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
  1350. // On termination condition (workid == 0), exit loop.
  1351. llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
  1352. llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
  1353. Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
  1354. // Activate requested workers.
  1355. CGF.EmitBlock(SelectWorkersBB);
  1356. llvm::Value *IsActive =
  1357. Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
  1358. Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
  1359. // Signal start of parallel region.
  1360. CGF.EmitBlock(ExecuteBB);
  1361. // Skip initialization.
  1362. setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
  1363. // Process work items: outlined parallel functions.
  1364. for (llvm::Function *W : Work) {
  1365. // Try to match this outlined function.
  1366. llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
  1367. llvm::Value *WorkFnMatch =
  1368. Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
  1369. llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
  1370. llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
  1371. Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
  1372. // Execute this outlined function.
  1373. CGF.EmitBlock(ExecuteFNBB);
  1374. // Insert call to work function via shared wrapper. The shared
  1375. // wrapper takes two arguments:
  1376. // - the parallelism level;
  1377. // - the thread ID;
  1378. emitCall(CGF, WST.Loc, W,
  1379. {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
  1380. // Go to end of parallel region.
  1381. CGF.EmitBranch(TerminateBB);
  1382. CGF.EmitBlock(CheckNextBB);
  1383. }
  1384. // Default case: call to outlined function through pointer if the target
  1385. // region makes a declare target call that may contain an orphaned parallel
  1386. // directive.
  1387. auto *ParallelFnTy =
  1388. llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
  1389. /*isVarArg=*/false);
  1390. llvm::Value *WorkFnCast =
  1391. Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
  1392. // Insert call to work function via shared wrapper. The shared
  1393. // wrapper takes two arguments:
  1394. // - the parallelism level;
  1395. // - the thread ID;
  1396. emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
  1397. {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
  1398. // Go to end of parallel region.
  1399. CGF.EmitBranch(TerminateBB);
  1400. // Signal end of parallel region.
  1401. CGF.EmitBlock(TerminateBB);
  1402. CGF.EmitRuntimeCall(
  1403. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
  1404. llvm::None);
  1405. CGF.EmitBranch(BarrierBB);
  1406. // All active and inactive workers wait at a barrier after parallel region.
  1407. CGF.EmitBlock(BarrierBB);
  1408. // Barrier after parallel region.
  1409. syncCTAThreads(CGF);
  1410. CGF.EmitBranch(AwaitBB);
  1411. // Exit target region.
  1412. CGF.EmitBlock(ExitBB);
  1413. // Skip initialization.
  1414. clearLocThreadIdInsertPt(CGF);
  1415. }
  1416. /// Returns specified OpenMP runtime function for the current OpenMP
  1417. /// implementation. Specialized for the NVPTX device.
  1418. /// \param Function OpenMP runtime function.
  1419. /// \return Specified function.
  1420. llvm::FunctionCallee
  1421. CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
  1422. llvm::FunctionCallee RTLFn = nullptr;
  1423. switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
  1424. case OMPRTL_NVPTX__kmpc_kernel_init: {
  1425. // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
  1426. // RequiresOMPRuntime);
  1427. llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
  1428. auto *FnTy =
  1429. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1430. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
  1431. break;
  1432. }
  1433. case OMPRTL_NVPTX__kmpc_kernel_deinit: {
  1434. // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
  1435. llvm::Type *TypeParams[] = {CGM.Int16Ty};
  1436. auto *FnTy =
  1437. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1438. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
  1439. break;
  1440. }
  1441. case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
  1442. // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
  1443. // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
  1444. llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
  1445. auto *FnTy =
  1446. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1447. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
  1448. break;
  1449. }
  1450. case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
  1451. // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
  1452. llvm::Type *TypeParams[] = {CGM.Int16Ty};
  1453. auto *FnTy =
  1454. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1455. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
  1456. break;
  1457. }
  1458. case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
  1459. /// Build void __kmpc_kernel_prepare_parallel(
  1460. /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
  1461. llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
  1462. auto *FnTy =
  1463. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1464. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
  1465. break;
  1466. }
  1467. case OMPRTL_NVPTX__kmpc_kernel_parallel: {
  1468. /// Build bool __kmpc_kernel_parallel(void **outlined_function,
  1469. /// int16_t IsOMPRuntimeInitialized);
  1470. llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
  1471. llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
  1472. auto *FnTy =
  1473. llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
  1474. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
  1475. break;
  1476. }
  1477. case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
  1478. /// Build void __kmpc_kernel_end_parallel();
  1479. auto *FnTy =
  1480. llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
  1481. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
  1482. break;
  1483. }
  1484. case OMPRTL_NVPTX__kmpc_serialized_parallel: {
  1485. // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  1486. // global_tid);
  1487. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1488. auto *FnTy =
  1489. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1490. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
  1491. break;
  1492. }
  1493. case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
  1494. // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  1495. // global_tid);
  1496. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1497. auto *FnTy =
  1498. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1499. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
  1500. break;
  1501. }
  1502. case OMPRTL_NVPTX__kmpc_shuffle_int32: {
  1503. // Build int32_t __kmpc_shuffle_int32(int32_t element,
  1504. // int16_t lane_offset, int16_t warp_size);
  1505. llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
  1506. auto *FnTy =
  1507. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1508. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
  1509. break;
  1510. }
  1511. case OMPRTL_NVPTX__kmpc_shuffle_int64: {
  1512. // Build int64_t __kmpc_shuffle_int64(int64_t element,
  1513. // int16_t lane_offset, int16_t warp_size);
  1514. llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
  1515. auto *FnTy =
  1516. llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
  1517. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
  1518. break;
  1519. }
  1520. case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
  1521. // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
  1522. // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
  1523. // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
  1524. // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
  1525. // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
  1526. llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
  1527. CGM.Int16Ty, CGM.Int16Ty};
  1528. auto *ShuffleReduceFnTy =
  1529. llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
  1530. /*isVarArg=*/false);
  1531. llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
  1532. auto *InterWarpCopyFnTy =
  1533. llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
  1534. /*isVarArg=*/false);
  1535. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  1536. CGM.Int32Ty,
  1537. CGM.Int32Ty,
  1538. CGM.SizeTy,
  1539. CGM.VoidPtrTy,
  1540. ShuffleReduceFnTy->getPointerTo(),
  1541. InterWarpCopyFnTy->getPointerTo()};
  1542. auto *FnTy =
  1543. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1544. RTLFn = CGM.CreateRuntimeFunction(
  1545. FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
  1546. break;
  1547. }
  1548. case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
  1549. // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
  1550. llvm::Type *TypeParams[] = {CGM.Int32Ty};
  1551. auto *FnTy =
  1552. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1553. RTLFn = CGM.CreateRuntimeFunction(
  1554. FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
  1555. break;
  1556. }
  1557. case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
  1558. // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
  1559. // global_tid, void *global_buffer, int32_t num_of_records, void*
  1560. // reduce_data,
  1561. // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
  1562. // lane_offset, int16_t shortCircuit),
  1563. // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
  1564. // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
  1565. // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
  1566. // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
  1567. // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
  1568. // *buffer, int idx, void *reduce_data));
  1569. llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
  1570. CGM.Int16Ty, CGM.Int16Ty};
  1571. auto *ShuffleReduceFnTy =
  1572. llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
  1573. /*isVarArg=*/false);
  1574. llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
  1575. auto *InterWarpCopyFnTy =
  1576. llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
  1577. /*isVarArg=*/false);
  1578. llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
  1579. CGM.VoidPtrTy};
  1580. auto *GlobalListFnTy =
  1581. llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
  1582. /*isVarArg=*/false);
  1583. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  1584. CGM.Int32Ty,
  1585. CGM.VoidPtrTy,
  1586. CGM.Int32Ty,
  1587. CGM.VoidPtrTy,
  1588. ShuffleReduceFnTy->getPointerTo(),
  1589. InterWarpCopyFnTy->getPointerTo(),
  1590. GlobalListFnTy->getPointerTo(),
  1591. GlobalListFnTy->getPointerTo(),
  1592. GlobalListFnTy->getPointerTo(),
  1593. GlobalListFnTy->getPointerTo()};
  1594. auto *FnTy =
  1595. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1596. RTLFn = CGM.CreateRuntimeFunction(
  1597. FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
  1598. break;
  1599. }
  1600. case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
  1601. /// Build void __kmpc_data_sharing_init_stack();
  1602. auto *FnTy =
  1603. llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
  1604. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
  1605. break;
  1606. }
  1607. case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
  1608. /// Build void __kmpc_data_sharing_init_stack_spmd();
  1609. auto *FnTy =
  1610. llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
  1611. RTLFn =
  1612. CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
  1613. break;
  1614. }
  1615. case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
  1616. // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
  1617. // int16_t UseSharedMemory);
  1618. llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
  1619. auto *FnTy =
  1620. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1621. RTLFn = CGM.CreateRuntimeFunction(
  1622. FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
  1623. break;
  1624. }
  1625. case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
  1626. // Build void __kmpc_data_sharing_pop_stack(void *a);
  1627. llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
  1628. auto *FnTy =
  1629. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1630. RTLFn = CGM.CreateRuntimeFunction(FnTy,
  1631. /*Name=*/"__kmpc_data_sharing_pop_stack");
  1632. break;
  1633. }
  1634. case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
  1635. /// Build void __kmpc_begin_sharing_variables(void ***args,
  1636. /// size_t n_args);
  1637. llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
  1638. auto *FnTy =
  1639. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1640. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
  1641. break;
  1642. }
  1643. case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
  1644. /// Build void __kmpc_end_sharing_variables();
  1645. auto *FnTy =
  1646. llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
  1647. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
  1648. break;
  1649. }
  1650. case OMPRTL_NVPTX__kmpc_get_shared_variables: {
  1651. /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
  1652. llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
  1653. auto *FnTy =
  1654. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1655. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
  1656. break;
  1657. }
  1658. case OMPRTL_NVPTX__kmpc_parallel_level: {
  1659. // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
  1660. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1661. auto *FnTy =
  1662. llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
  1663. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
  1664. break;
  1665. }
  1666. case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
  1667. // Build int8_t __kmpc_is_spmd_exec_mode();
  1668. auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
  1669. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
  1670. break;
  1671. }
  1672. case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
  1673. // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
  1674. // const void *buf, size_t size, int16_t is_shared, const void **res);
  1675. llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
  1676. CGM.Int16Ty, CGM.VoidPtrPtrTy};
  1677. auto *FnTy =
  1678. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1679. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
  1680. break;
  1681. }
  1682. case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
  1683. // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
  1684. // int16_t is_shared);
  1685. llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
  1686. auto *FnTy =
  1687. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1688. RTLFn =
  1689. CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
  1690. break;
  1691. }
  1692. case OMPRTL__kmpc_barrier: {
  1693. // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  1694. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1695. auto *FnTy =
  1696. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1697. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
  1698. cast<llvm::Function>(RTLFn.getCallee())
  1699. ->addFnAttr(llvm::Attribute::Convergent);
  1700. break;
  1701. }
  1702. case OMPRTL__kmpc_barrier_simple_spmd: {
  1703. // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
  1704. // global_tid);
  1705. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1706. auto *FnTy =
  1707. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1708. RTLFn =
  1709. CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
  1710. cast<llvm::Function>(RTLFn.getCallee())
  1711. ->addFnAttr(llvm::Attribute::Convergent);
  1712. break;
  1713. }
  1714. case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
  1715. // Build int32_t __kmpc_warp_active_thread_mask(void);
  1716. auto *FnTy =
  1717. llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
  1718. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
  1719. break;
  1720. }
  1721. case OMPRTL_NVPTX__kmpc_syncwarp: {
  1722. // Build void __kmpc_syncwarp(kmp_int32 Mask);
  1723. auto *FnTy =
  1724. llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
  1725. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
  1726. break;
  1727. }
  1728. }
  1729. return RTLFn;
  1730. }
  1731. void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
  1732. llvm::Constant *Addr,
  1733. uint64_t Size, int32_t,
  1734. llvm::GlobalValue::LinkageTypes) {
  1735. // TODO: Add support for global variables on the device after declare target
  1736. // support.
  1737. if (!isa<llvm::Function>(Addr))
  1738. return;
  1739. llvm::Module &M = CGM.getModule();
  1740. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  1741. // Get "nvvm.annotations" metadata node
  1742. llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
  1743. llvm::Metadata *MDVals[] = {
  1744. llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
  1745. llvm::ConstantAsMetadata::get(
  1746. llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
  1747. // Append metadata to nvvm.annotations
  1748. MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
  1749. }
  1750. void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
  1751. const OMPExecutableDirective &D, StringRef ParentName,
  1752. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  1753. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  1754. if (!IsOffloadEntry) // Nothing to do.
  1755. return;
  1756. assert(!ParentName.empty() && "Invalid target region parent name!");
  1757. bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
  1758. if (Mode)
  1759. emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
  1760. CodeGen);
  1761. else
  1762. emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
  1763. CodeGen);
  1764. setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
  1765. }
  1766. namespace {
  1767. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  1768. /// Enum for accesseing the reserved_2 field of the ident_t struct.
  1769. enum ModeFlagsTy : unsigned {
  1770. /// Bit set to 1 when in SPMD mode.
  1771. KMP_IDENT_SPMD_MODE = 0x01,
  1772. /// Bit set to 1 when a simplified runtime is used.
  1773. KMP_IDENT_SIMPLE_RT_MODE = 0x02,
  1774. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
  1775. };
  1776. /// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
  1777. static const ModeFlagsTy UndefinedMode =
  1778. (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
  1779. } // anonymous namespace
  1780. unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
  1781. switch (getExecutionMode()) {
  1782. case EM_SPMD:
  1783. if (requiresFullRuntime())
  1784. return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
  1785. return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
  1786. case EM_NonSPMD:
  1787. assert(requiresFullRuntime() && "Expected full runtime.");
  1788. return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
  1789. case EM_Unknown:
  1790. return UndefinedMode;
  1791. }
  1792. llvm_unreachable("Unknown flags are requested.");
  1793. }
  1794. bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
  1795. const GlobalDecl &OldGD,
  1796. llvm::GlobalValue *OrigAddr,
  1797. bool IsForDefinition) {
  1798. // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
  1799. auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
  1800. if (NewFD->isDefined()) {
  1801. CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
  1802. return true;
  1803. }
  1804. return false;
  1805. }
  1806. CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
  1807. : CGOpenMPRuntime(CGM, "_", "$") {
  1808. if (!CGM.getLangOpts().OpenMPIsDevice)
  1809. llvm_unreachable("OpenMP NVPTX can only handle device code.");
  1810. }
  1811. void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
  1812. OpenMPProcBindClauseKind ProcBind,
  1813. SourceLocation Loc) {
  1814. // Do nothing in case of SPMD mode and L0 parallel.
  1815. if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
  1816. return;
  1817. CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
  1818. }
  1819. void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
  1820. llvm::Value *NumThreads,
  1821. SourceLocation Loc) {
  1822. // Do nothing in case of SPMD mode and L0 parallel.
  1823. if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
  1824. return;
  1825. CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
  1826. }
  1827. void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
  1828. const Expr *NumTeams,
  1829. const Expr *ThreadLimit,
  1830. SourceLocation Loc) {}
  1831. llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
  1832. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1833. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1834. // Emit target region as a standalone region.
  1835. class NVPTXPrePostActionTy : public PrePostActionTy {
  1836. bool &IsInParallelRegion;
  1837. bool PrevIsInParallelRegion;
  1838. public:
  1839. NVPTXPrePostActionTy(bool &IsInParallelRegion)
  1840. : IsInParallelRegion(IsInParallelRegion) {}
  1841. void Enter(CodeGenFunction &CGF) override {
  1842. PrevIsInParallelRegion = IsInParallelRegion;
  1843. IsInParallelRegion = true;
  1844. }
  1845. void Exit(CodeGenFunction &CGF) override {
  1846. IsInParallelRegion = PrevIsInParallelRegion;
  1847. }
  1848. } Action(IsInParallelRegion);
  1849. CodeGen.setAction(Action);
  1850. bool PrevIsInTTDRegion = IsInTTDRegion;
  1851. IsInTTDRegion = false;
  1852. bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
  1853. IsInTargetMasterThreadRegion = false;
  1854. auto *OutlinedFun =
  1855. cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
  1856. D, ThreadIDVar, InnermostKind, CodeGen));
  1857. if (CGM.getLangOpts().Optimize) {
  1858. OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
  1859. OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
  1860. OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
  1861. }
  1862. IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
  1863. IsInTTDRegion = PrevIsInTTDRegion;
  1864. if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
  1865. !IsInParallelRegion) {
  1866. llvm::Function *WrapperFun =
  1867. createParallelDataSharingWrapper(OutlinedFun, D);
  1868. WrapperFunctionsMap[OutlinedFun] = WrapperFun;
  1869. }
  1870. return OutlinedFun;
  1871. }
  1872. /// Get list of lastprivate variables from the teams distribute ... or
  1873. /// teams {distribute ...} directives.
  1874. static void
  1875. getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
  1876. llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
  1877. assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
  1878. "expected teams directive.");
  1879. const OMPExecutableDirective *Dir = &D;
  1880. if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
  1881. if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
  1882. Ctx,
  1883. D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
  1884. /*IgnoreCaptured=*/true))) {
  1885. Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
  1886. if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
  1887. Dir = nullptr;
  1888. }
  1889. }
  1890. if (!Dir)
  1891. return;
  1892. for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
  1893. for (const Expr *E : C->getVarRefs())
  1894. Vars.push_back(getPrivateItem(E));
  1895. }
  1896. }
  1897. /// Get list of reduction variables from the teams ... directives.
  1898. static void
  1899. getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
  1900. llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
  1901. assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
  1902. "expected teams directive.");
  1903. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1904. for (const Expr *E : C->privates())
  1905. Vars.push_back(getPrivateItem(E));
  1906. }
  1907. }
  1908. llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
  1909. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1910. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1911. SourceLocation Loc = D.getBeginLoc();
  1912. const RecordDecl *GlobalizedRD = nullptr;
  1913. llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
  1914. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
  1915. // Globalize team reductions variable unconditionally in all modes.
  1916. if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
  1917. getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
  1918. if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
  1919. getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
  1920. if (!LastPrivatesReductions.empty()) {
  1921. GlobalizedRD = ::buildRecordForGlobalizedVars(
  1922. CGM.getContext(), llvm::None, LastPrivatesReductions,
  1923. MappedDeclsFields, WarpSize);
  1924. }
  1925. } else if (!LastPrivatesReductions.empty()) {
  1926. assert(!TeamAndReductions.first &&
  1927. "Previous team declaration is not expected.");
  1928. TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
  1929. std::swap(TeamAndReductions.second, LastPrivatesReductions);
  1930. }
  1931. // Emit target region as a standalone region.
  1932. class NVPTXPrePostActionTy : public PrePostActionTy {
  1933. SourceLocation &Loc;
  1934. const RecordDecl *GlobalizedRD;
  1935. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  1936. &MappedDeclsFields;
  1937. public:
  1938. NVPTXPrePostActionTy(
  1939. SourceLocation &Loc, const RecordDecl *GlobalizedRD,
  1940. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  1941. &MappedDeclsFields)
  1942. : Loc(Loc), GlobalizedRD(GlobalizedRD),
  1943. MappedDeclsFields(MappedDeclsFields) {}
  1944. void Enter(CodeGenFunction &CGF) override {
  1945. auto &Rt =
  1946. static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
  1947. if (GlobalizedRD) {
  1948. auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
  1949. I->getSecond().GlobalRecord = GlobalizedRD;
  1950. I->getSecond().MappedParams =
  1951. std::make_unique<CodeGenFunction::OMPMapVars>();
  1952. DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
  1953. for (const auto &Pair : MappedDeclsFields) {
  1954. assert(Pair.getFirst()->isCanonicalDecl() &&
  1955. "Expected canonical declaration");
  1956. Data.insert(std::make_pair(Pair.getFirst(),
  1957. MappedVarData(Pair.getSecond(),
  1958. /*IsOnePerTeam=*/true)));
  1959. }
  1960. }
  1961. Rt.emitGenericVarsProlog(CGF, Loc);
  1962. }
  1963. void Exit(CodeGenFunction &CGF) override {
  1964. static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
  1965. .emitGenericVarsEpilog(CGF);
  1966. }
  1967. } Action(Loc, GlobalizedRD, MappedDeclsFields);
  1968. CodeGen.setAction(Action);
  1969. llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
  1970. D, ThreadIDVar, InnermostKind, CodeGen);
  1971. if (CGM.getLangOpts().Optimize) {
  1972. OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
  1973. OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
  1974. OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
  1975. }
  1976. return OutlinedFun;
  1977. }
  1978. void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
  1979. SourceLocation Loc,
  1980. bool WithSPMDCheck) {
  1981. if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
  1982. getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
  1983. return;
  1984. CGBuilderTy &Bld = CGF.Builder;
  1985. const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  1986. if (I == FunctionGlobalizedDecls.end())
  1987. return;
  1988. if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
  1989. QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
  1990. QualType SecGlobalRecTy;
  1991. // Recover pointer to this function's global record. The runtime will
  1992. // handle the specifics of the allocation of the memory.
  1993. // Use actual memory size of the record including the padding
  1994. // for alignment purposes.
  1995. unsigned Alignment =
  1996. CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
  1997. unsigned GlobalRecordSize =
  1998. CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
  1999. GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
  2000. llvm::PointerType *GlobalRecPtrTy =
  2001. CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
  2002. llvm::Value *GlobalRecCastAddr;
  2003. llvm::Value *IsTTD = nullptr;
  2004. if (!IsInTTDRegion &&
  2005. (WithSPMDCheck ||
  2006. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
  2007. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
  2008. llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
  2009. llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
  2010. if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
  2011. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2012. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2013. llvm::Value *PL = CGF.EmitRuntimeCall(
  2014. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
  2015. {RTLoc, ThreadID});
  2016. IsTTD = Bld.CreateIsNull(PL);
  2017. }
  2018. llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
  2019. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
  2020. Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
  2021. // There is no need to emit line number for unconditional branch.
  2022. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2023. CGF.EmitBlock(SPMDBB);
  2024. Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
  2025. CharUnits::fromQuantity(Alignment));
  2026. CGF.EmitBranch(ExitBB);
  2027. // There is no need to emit line number for unconditional branch.
  2028. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2029. CGF.EmitBlock(NonSPMDBB);
  2030. llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
  2031. if (const RecordDecl *SecGlobalizedVarsRecord =
  2032. I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
  2033. SecGlobalRecTy =
  2034. CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
  2035. // Recover pointer to this function's global record. The runtime will
  2036. // handle the specifics of the allocation of the memory.
  2037. // Use actual memory size of the record including the padding
  2038. // for alignment purposes.
  2039. unsigned Alignment =
  2040. CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
  2041. unsigned GlobalRecordSize =
  2042. CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
  2043. GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
  2044. Size = Bld.CreateSelect(
  2045. IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
  2046. }
  2047. // TODO: allow the usage of shared memory to be controlled by
  2048. // the user, for now, default to global.
  2049. llvm::Value *GlobalRecordSizeArg[] = {
  2050. Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
  2051. llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
  2052. createNVPTXRuntimeFunction(
  2053. OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
  2054. GlobalRecordSizeArg);
  2055. GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2056. GlobalRecValue, GlobalRecPtrTy);
  2057. CGF.EmitBlock(ExitBB);
  2058. auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
  2059. /*NumReservedValues=*/2, "_select_stack");
  2060. Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
  2061. Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
  2062. GlobalRecCastAddr = Phi;
  2063. I->getSecond().GlobalRecordAddr = Phi;
  2064. I->getSecond().IsInSPMDModeFlag = IsSPMD;
  2065. } else if (IsInTTDRegion) {
  2066. assert(GlobalizedRecords.back().Records.size() < 2 &&
  2067. "Expected less than 2 globalized records: one for target and one "
  2068. "for teams.");
  2069. unsigned Offset = 0;
  2070. for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
  2071. QualType RDTy = CGM.getContext().getRecordType(RD);
  2072. unsigned Alignment =
  2073. CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
  2074. unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
  2075. Offset =
  2076. llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
  2077. }
  2078. unsigned Alignment =
  2079. CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
  2080. Offset = llvm::alignTo(Offset, Alignment);
  2081. GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
  2082. ++GlobalizedRecords.back().RegionCounter;
  2083. if (GlobalizedRecords.back().Records.size() == 1) {
  2084. assert(KernelStaticGlobalized &&
  2085. "Kernel static pointer must be initialized already.");
  2086. auto *UseSharedMemory = new llvm::GlobalVariable(
  2087. CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
  2088. llvm::GlobalValue::InternalLinkage, nullptr,
  2089. "_openmp_static_kernel$is_shared");
  2090. UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2091. QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
  2092. /*DestWidth=*/16, /*Signed=*/0);
  2093. llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
  2094. Address(UseSharedMemory,
  2095. CGM.getContext().getTypeAlignInChars(Int16Ty)),
  2096. /*Volatile=*/false, Int16Ty, Loc);
  2097. auto *StaticGlobalized = new llvm::GlobalVariable(
  2098. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
  2099. llvm::GlobalValue::CommonLinkage, nullptr);
  2100. auto *RecSize = new llvm::GlobalVariable(
  2101. CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
  2102. llvm::GlobalValue::InternalLinkage, nullptr,
  2103. "_openmp_static_kernel$size");
  2104. RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2105. llvm::Value *Ld = CGF.EmitLoadOfScalar(
  2106. Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
  2107. CGM.getContext().getSizeType(), Loc);
  2108. llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2109. KernelStaticGlobalized, CGM.VoidPtrPtrTy);
  2110. llvm::Value *GlobalRecordSizeArg[] = {
  2111. llvm::ConstantInt::get(
  2112. CGM.Int16Ty,
  2113. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
  2114. StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
  2115. CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
  2116. OMPRTL_NVPTX__kmpc_get_team_static_memory),
  2117. GlobalRecordSizeArg);
  2118. GlobalizedRecords.back().Buffer = StaticGlobalized;
  2119. GlobalizedRecords.back().RecSize = RecSize;
  2120. GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
  2121. GlobalizedRecords.back().Loc = Loc;
  2122. }
  2123. assert(KernelStaticGlobalized && "Global address must be set already.");
  2124. Address FrameAddr = CGF.EmitLoadOfPointer(
  2125. Address(KernelStaticGlobalized, CGM.getPointerAlign()),
  2126. CGM.getContext()
  2127. .getPointerType(CGM.getContext().VoidPtrTy)
  2128. .castAs<PointerType>());
  2129. llvm::Value *GlobalRecValue =
  2130. Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
  2131. I->getSecond().GlobalRecordAddr = GlobalRecValue;
  2132. I->getSecond().IsInSPMDModeFlag = nullptr;
  2133. GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2134. GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
  2135. } else {
  2136. // TODO: allow the usage of shared memory to be controlled by
  2137. // the user, for now, default to global.
  2138. llvm::Value *GlobalRecordSizeArg[] = {
  2139. llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
  2140. CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
  2141. llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
  2142. createNVPTXRuntimeFunction(
  2143. OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
  2144. GlobalRecordSizeArg);
  2145. GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2146. GlobalRecValue, GlobalRecPtrTy);
  2147. I->getSecond().GlobalRecordAddr = GlobalRecValue;
  2148. I->getSecond().IsInSPMDModeFlag = nullptr;
  2149. }
  2150. LValue Base =
  2151. CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
  2152. // Emit the "global alloca" which is a GEP from the global declaration
  2153. // record using the pointer returned by the runtime.
  2154. LValue SecBase;
  2155. decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
  2156. if (IsTTD) {
  2157. SecIt = I->getSecond().SecondaryLocalVarData->begin();
  2158. llvm::PointerType *SecGlobalRecPtrTy =
  2159. CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
  2160. SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
  2161. Bld.CreatePointerBitCastOrAddrSpaceCast(
  2162. I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
  2163. SecGlobalRecTy);
  2164. }
  2165. for (auto &Rec : I->getSecond().LocalVarData) {
  2166. bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
  2167. llvm::Value *ParValue;
  2168. if (EscapedParam) {
  2169. const auto *VD = cast<VarDecl>(Rec.first);
  2170. LValue ParLVal =
  2171. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
  2172. ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
  2173. }
  2174. LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
  2175. // Emit VarAddr basing on lane-id if required.
  2176. QualType VarTy;
  2177. if (Rec.second.IsOnePerTeam) {
  2178. VarTy = Rec.second.FD->getType();
  2179. } else {
  2180. llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
  2181. VarAddr.getAddress().getPointer(),
  2182. {Bld.getInt32(0), getNVPTXLaneID(CGF)});
  2183. VarTy =
  2184. Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
  2185. VarAddr = CGF.MakeAddrLValue(
  2186. Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
  2187. AlignmentSource::Decl);
  2188. }
  2189. Rec.second.PrivateAddr = VarAddr.getAddress();
  2190. if (!IsInTTDRegion &&
  2191. (WithSPMDCheck ||
  2192. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
  2193. assert(I->getSecond().IsInSPMDModeFlag &&
  2194. "Expected unknown execution mode or required SPMD check.");
  2195. if (IsTTD) {
  2196. assert(SecIt->second.IsOnePerTeam &&
  2197. "Secondary glob data must be one per team.");
  2198. LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
  2199. VarAddr.setAddress(
  2200. Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
  2201. VarAddr.getPointer()),
  2202. VarAddr.getAlignment()));
  2203. Rec.second.PrivateAddr = VarAddr.getAddress();
  2204. }
  2205. Address GlobalPtr = Rec.second.PrivateAddr;
  2206. Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
  2207. Rec.second.PrivateAddr = Address(
  2208. Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
  2209. LocalAddr.getPointer(), GlobalPtr.getPointer()),
  2210. LocalAddr.getAlignment());
  2211. }
  2212. if (EscapedParam) {
  2213. const auto *VD = cast<VarDecl>(Rec.first);
  2214. CGF.EmitStoreOfScalar(ParValue, VarAddr);
  2215. I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
  2216. }
  2217. if (IsTTD)
  2218. ++SecIt;
  2219. }
  2220. }
  2221. for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
  2222. // Recover pointer to this function's global record. The runtime will
  2223. // handle the specifics of the allocation of the memory.
  2224. // Use actual memory size of the record including the padding
  2225. // for alignment purposes.
  2226. CGBuilderTy &Bld = CGF.Builder;
  2227. llvm::Value *Size = CGF.getTypeSize(VD->getType());
  2228. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2229. Size = Bld.CreateNUWAdd(
  2230. Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
  2231. llvm::Value *AlignVal =
  2232. llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
  2233. Size = Bld.CreateUDiv(Size, AlignVal);
  2234. Size = Bld.CreateNUWMul(Size, AlignVal);
  2235. // TODO: allow the usage of shared memory to be controlled by
  2236. // the user, for now, default to global.
  2237. llvm::Value *GlobalRecordSizeArg[] = {
  2238. Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
  2239. llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
  2240. createNVPTXRuntimeFunction(
  2241. OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
  2242. GlobalRecordSizeArg);
  2243. llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2244. GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
  2245. LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
  2246. CGM.getContext().getDeclAlign(VD),
  2247. AlignmentSource::Decl);
  2248. I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
  2249. Base.getAddress());
  2250. I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
  2251. }
  2252. I->getSecond().MappedParams->apply(CGF);
  2253. }
  2254. void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
  2255. bool WithSPMDCheck) {
  2256. if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
  2257. getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
  2258. return;
  2259. const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  2260. if (I != FunctionGlobalizedDecls.end()) {
  2261. I->getSecond().MappedParams->restore(CGF);
  2262. if (!CGF.HaveInsertPoint())
  2263. return;
  2264. for (llvm::Value *Addr :
  2265. llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
  2266. CGF.EmitRuntimeCall(
  2267. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
  2268. Addr);
  2269. }
  2270. if (I->getSecond().GlobalRecordAddr) {
  2271. if (!IsInTTDRegion &&
  2272. (WithSPMDCheck ||
  2273. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
  2274. CGBuilderTy &Bld = CGF.Builder;
  2275. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
  2276. llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
  2277. Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
  2278. // There is no need to emit line number for unconditional branch.
  2279. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2280. CGF.EmitBlock(NonSPMDBB);
  2281. CGF.EmitRuntimeCall(
  2282. createNVPTXRuntimeFunction(
  2283. OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
  2284. CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
  2285. CGF.EmitBlock(ExitBB);
  2286. } else if (IsInTTDRegion) {
  2287. assert(GlobalizedRecords.back().RegionCounter > 0 &&
  2288. "region counter must be > 0.");
  2289. --GlobalizedRecords.back().RegionCounter;
  2290. // Emit the restore function only in the target region.
  2291. if (GlobalizedRecords.back().RegionCounter == 0) {
  2292. QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
  2293. /*DestWidth=*/16, /*Signed=*/0);
  2294. llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
  2295. Address(GlobalizedRecords.back().UseSharedMemory,
  2296. CGM.getContext().getTypeAlignInChars(Int16Ty)),
  2297. /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
  2298. llvm::Value *Args[] = {
  2299. llvm::ConstantInt::get(
  2300. CGM.Int16Ty,
  2301. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
  2302. IsInSharedMemory};
  2303. CGF.EmitRuntimeCall(
  2304. createNVPTXRuntimeFunction(
  2305. OMPRTL_NVPTX__kmpc_restore_team_static_memory),
  2306. Args);
  2307. }
  2308. } else {
  2309. CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
  2310. OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
  2311. I->getSecond().GlobalRecordAddr);
  2312. }
  2313. }
  2314. }
  2315. }
  2316. void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
  2317. const OMPExecutableDirective &D,
  2318. SourceLocation Loc,
  2319. llvm::Function *OutlinedFn,
  2320. ArrayRef<llvm::Value *> CapturedVars) {
  2321. if (!CGF.HaveInsertPoint())
  2322. return;
  2323. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2324. /*Name=*/".zero.addr");
  2325. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2326. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2327. OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
  2328. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2329. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2330. emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  2331. }
  2332. void CGOpenMPRuntimeNVPTX::emitParallelCall(
  2333. CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
  2334. ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
  2335. if (!CGF.HaveInsertPoint())
  2336. return;
  2337. if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
  2338. emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
  2339. else
  2340. emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
  2341. }
  2342. void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
  2343. CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
  2344. ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
  2345. llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
  2346. // Force inline this outlined function at its call site.
  2347. Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
  2348. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2349. /*Name=*/".zero.addr");
  2350. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2351. // ThreadId for serialized parallels is 0.
  2352. Address ThreadIDAddr = ZeroAddr;
  2353. auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
  2354. CodeGenFunction &CGF, PrePostActionTy &Action) {
  2355. Action.Enter(CGF);
  2356. Address ZeroAddr =
  2357. CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2358. /*Name=*/".bound.zero.addr");
  2359. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2360. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2361. OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
  2362. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2363. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2364. emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
  2365. };
  2366. auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
  2367. PrePostActionTy &) {
  2368. RegionCodeGenTy RCG(CodeGen);
  2369. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2370. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2371. llvm::Value *Args[] = {RTLoc, ThreadID};
  2372. NVPTXActionTy Action(
  2373. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
  2374. Args,
  2375. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
  2376. Args);
  2377. RCG.setAction(Action);
  2378. RCG(CGF);
  2379. };
  2380. auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
  2381. PrePostActionTy &Action) {
  2382. CGBuilderTy &Bld = CGF.Builder;
  2383. llvm::Function *WFn = WrapperFunctionsMap[Fn];
  2384. assert(WFn && "Wrapper function does not exist!");
  2385. llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
  2386. // Prepare for parallel region. Indicate the outlined function.
  2387. llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
  2388. CGF.EmitRuntimeCall(
  2389. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
  2390. Args);
  2391. // Create a private scope that will globalize the arguments
  2392. // passed from the outside of the target region.
  2393. CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
  2394. // There's something to share.
  2395. if (!CapturedVars.empty()) {
  2396. // Prepare for parallel region. Indicate the outlined function.
  2397. Address SharedArgs =
  2398. CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
  2399. llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
  2400. llvm::Value *DataSharingArgs[] = {
  2401. SharedArgsPtr,
  2402. llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
  2403. CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
  2404. OMPRTL_NVPTX__kmpc_begin_sharing_variables),
  2405. DataSharingArgs);
  2406. // Store variable address in a list of references to pass to workers.
  2407. unsigned Idx = 0;
  2408. ASTContext &Ctx = CGF.getContext();
  2409. Address SharedArgListAddress = CGF.EmitLoadOfPointer(
  2410. SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
  2411. .castAs<PointerType>());
  2412. for (llvm::Value *V : CapturedVars) {
  2413. Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
  2414. llvm::Value *PtrV;
  2415. if (V->getType()->isIntegerTy())
  2416. PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
  2417. else
  2418. PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
  2419. CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
  2420. Ctx.getPointerType(Ctx.VoidPtrTy));
  2421. ++Idx;
  2422. }
  2423. }
  2424. // Activate workers. This barrier is used by the master to signal
  2425. // work for the workers.
  2426. syncCTAThreads(CGF);
  2427. // OpenMP [2.5, Parallel Construct, p.49]
  2428. // There is an implied barrier at the end of a parallel region. After the
  2429. // end of a parallel region, only the master thread of the team resumes
  2430. // execution of the enclosing task region.
  2431. //
  2432. // The master waits at this barrier until all workers are done.
  2433. syncCTAThreads(CGF);
  2434. if (!CapturedVars.empty())
  2435. CGF.EmitRuntimeCall(
  2436. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
  2437. // Remember for post-processing in worker loop.
  2438. Work.emplace_back(WFn);
  2439. };
  2440. auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
  2441. CodeGenFunction &CGF, PrePostActionTy &Action) {
  2442. if (IsInParallelRegion) {
  2443. SeqGen(CGF, Action);
  2444. } else if (IsInTargetMasterThreadRegion) {
  2445. L0ParallelGen(CGF, Action);
  2446. } else {
  2447. // Check for master and then parallelism:
  2448. // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
  2449. // Serialized execution.
  2450. // } else {
  2451. // Worker call.
  2452. // }
  2453. CGBuilderTy &Bld = CGF.Builder;
  2454. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
  2455. llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
  2456. llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
  2457. llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
  2458. llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
  2459. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
  2460. Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
  2461. // There is no need to emit line number for unconditional branch.
  2462. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2463. CGF.EmitBlock(ParallelCheckBB);
  2464. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2465. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2466. llvm::Value *PL = CGF.EmitRuntimeCall(
  2467. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
  2468. {RTLoc, ThreadID});
  2469. llvm::Value *Res = Bld.CreateIsNotNull(PL);
  2470. Bld.CreateCondBr(Res, SeqBB, MasterBB);
  2471. CGF.EmitBlock(SeqBB);
  2472. SeqGen(CGF, Action);
  2473. CGF.EmitBranch(ExitBB);
  2474. // There is no need to emit line number for unconditional branch.
  2475. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2476. CGF.EmitBlock(MasterBB);
  2477. L0ParallelGen(CGF, Action);
  2478. CGF.EmitBranch(ExitBB);
  2479. // There is no need to emit line number for unconditional branch.
  2480. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2481. // Emit the continuation block for code after the if.
  2482. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  2483. }
  2484. };
  2485. if (IfCond) {
  2486. emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
  2487. } else {
  2488. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2489. RegionCodeGenTy ThenRCG(LNParallelGen);
  2490. ThenRCG(CGF);
  2491. }
  2492. }
  2493. void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
  2494. CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
  2495. ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
  2496. // Just call the outlined function to execute the parallel region.
  2497. // OutlinedFn(&GTid, &zero, CapturedStruct);
  2498. //
  2499. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2500. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2501. /*Name=*/".zero.addr");
  2502. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2503. // ThreadId for serialized parallels is 0.
  2504. Address ThreadIDAddr = ZeroAddr;
  2505. auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
  2506. CodeGenFunction &CGF, PrePostActionTy &Action) {
  2507. Action.Enter(CGF);
  2508. Address ZeroAddr =
  2509. CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2510. /*Name=*/".bound.zero.addr");
  2511. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2512. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2513. OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
  2514. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2515. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2516. emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  2517. };
  2518. auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
  2519. PrePostActionTy &) {
  2520. RegionCodeGenTy RCG(CodeGen);
  2521. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2522. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2523. llvm::Value *Args[] = {RTLoc, ThreadID};
  2524. NVPTXActionTy Action(
  2525. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
  2526. Args,
  2527. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
  2528. Args);
  2529. RCG.setAction(Action);
  2530. RCG(CGF);
  2531. };
  2532. if (IsInTargetMasterThreadRegion) {
  2533. // In the worker need to use the real thread id.
  2534. ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
  2535. RegionCodeGenTy RCG(CodeGen);
  2536. RCG(CGF);
  2537. } else {
  2538. // If we are not in the target region, it is definitely L2 parallelism or
  2539. // more, because for SPMD mode we always has L1 parallel level, sowe don't
  2540. // need to check for orphaned directives.
  2541. RegionCodeGenTy RCG(SeqGen);
  2542. RCG(CGF);
  2543. }
  2544. }
  2545. void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
  2546. // Always emit simple barriers!
  2547. if (!CGF.HaveInsertPoint())
  2548. return;
  2549. // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
  2550. // This function does not use parameters, so we can emit just default values.
  2551. llvm::Value *Args[] = {
  2552. llvm::ConstantPointerNull::get(
  2553. cast<llvm::PointerType>(getIdentTyPointerTy())),
  2554. llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
  2555. llvm::CallInst *Call = CGF.EmitRuntimeCall(
  2556. createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
  2557. Call->setConvergent();
  2558. }
  2559. void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
  2560. SourceLocation Loc,
  2561. OpenMPDirectiveKind Kind, bool,
  2562. bool) {
  2563. // Always emit simple barriers!
  2564. if (!CGF.HaveInsertPoint())
  2565. return;
  2566. // Build call __kmpc_cancel_barrier(loc, thread_id);
  2567. unsigned Flags = getDefaultFlagsForBarriers(Kind);
  2568. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  2569. getThreadID(CGF, Loc)};
  2570. llvm::CallInst *Call = CGF.EmitRuntimeCall(
  2571. createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
  2572. Call->setConvergent();
  2573. }
  2574. void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
  2575. CodeGenFunction &CGF, StringRef CriticalName,
  2576. const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
  2577. const Expr *Hint) {
  2578. llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
  2579. llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
  2580. llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
  2581. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
  2582. llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
  2583. // Get the mask of active threads in the warp.
  2584. llvm::Value *Mask = CGF.EmitRuntimeCall(
  2585. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
  2586. // Fetch team-local id of the thread.
  2587. llvm::Value *ThreadID = getNVPTXThreadID(CGF);
  2588. // Get the width of the team.
  2589. llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
  2590. // Initialize the counter variable for the loop.
  2591. QualType Int32Ty =
  2592. CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
  2593. Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
  2594. LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
  2595. CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
  2596. /*isInit=*/true);
  2597. // Block checks if loop counter exceeds upper bound.
  2598. CGF.EmitBlock(LoopBB);
  2599. llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
  2600. llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
  2601. CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
  2602. // Block tests which single thread should execute region, and which threads
  2603. // should go straight to synchronisation point.
  2604. CGF.EmitBlock(TestBB);
  2605. CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
  2606. llvm::Value *CmpThreadToCounter =
  2607. CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
  2608. CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
  2609. // Block emits the body of the critical region.
  2610. CGF.EmitBlock(BodyBB);
  2611. // Output the critical statement.
  2612. CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
  2613. Hint);
  2614. // After the body surrounded by the critical region, the single executing
  2615. // thread will jump to the synchronisation point.
  2616. // Block waits for all threads in current team to finish then increments the
  2617. // counter variable and returns to the loop.
  2618. CGF.EmitBlock(SyncBB);
  2619. // Reconverge active threads in the warp.
  2620. (void)CGF.EmitRuntimeCall(
  2621. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
  2622. llvm::Value *IncCounterVal =
  2623. CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
  2624. CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
  2625. CGF.EmitBranch(LoopBB);
  2626. // Block that is reached when all threads in the team complete the region.
  2627. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  2628. }
  2629. /// Cast value to the specified type.
  2630. static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
  2631. QualType ValTy, QualType CastTy,
  2632. SourceLocation Loc) {
  2633. assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
  2634. "Cast type must sized.");
  2635. assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
  2636. "Val type must sized.");
  2637. llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
  2638. if (ValTy == CastTy)
  2639. return Val;
  2640. if (CGF.getContext().getTypeSizeInChars(ValTy) ==
  2641. CGF.getContext().getTypeSizeInChars(CastTy))
  2642. return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
  2643. if (CastTy->isIntegerType() && ValTy->isIntegerType())
  2644. return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
  2645. CastTy->hasSignedIntegerRepresentation());
  2646. Address CastItem = CGF.CreateMemTemp(CastTy);
  2647. Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2648. CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
  2649. CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
  2650. return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
  2651. }
  2652. /// This function creates calls to one of two shuffle functions to copy
  2653. /// variables between lanes in a warp.
  2654. static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
  2655. llvm::Value *Elem,
  2656. QualType ElemType,
  2657. llvm::Value *Offset,
  2658. SourceLocation Loc) {
  2659. CodeGenModule &CGM = CGF.CGM;
  2660. CGBuilderTy &Bld = CGF.Builder;
  2661. CGOpenMPRuntimeNVPTX &RT =
  2662. *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
  2663. CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
  2664. assert(Size.getQuantity() <= 8 &&
  2665. "Unsupported bitwidth in shuffle instruction.");
  2666. OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
  2667. ? OMPRTL_NVPTX__kmpc_shuffle_int32
  2668. : OMPRTL_NVPTX__kmpc_shuffle_int64;
  2669. // Cast all types to 32- or 64-bit values before calling shuffle routines.
  2670. QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
  2671. Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
  2672. llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
  2673. llvm::Value *WarpSize =
  2674. Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
  2675. llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
  2676. RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
  2677. return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
  2678. }
  2679. static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
  2680. Address DestAddr, QualType ElemType,
  2681. llvm::Value *Offset, SourceLocation Loc) {
  2682. CGBuilderTy &Bld = CGF.Builder;
  2683. CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
  2684. // Create the loop over the big sized data.
  2685. // ptr = (void*)Elem;
  2686. // ptrEnd = (void*) Elem + 1;
  2687. // Step = 8;
  2688. // while (ptr + Step < ptrEnd)
  2689. // shuffle((int64_t)*ptr);
  2690. // Step = 4;
  2691. // while (ptr + Step < ptrEnd)
  2692. // shuffle((int32_t)*ptr);
  2693. // ...
  2694. Address ElemPtr = DestAddr;
  2695. Address Ptr = SrcAddr;
  2696. Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2697. Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
  2698. for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
  2699. if (Size < CharUnits::fromQuantity(IntSize))
  2700. continue;
  2701. QualType IntType = CGF.getContext().getIntTypeForBitwidth(
  2702. CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
  2703. /*Signed=*/1);
  2704. llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
  2705. Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
  2706. ElemPtr =
  2707. Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
  2708. if (Size.getQuantity() / IntSize > 1) {
  2709. llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
  2710. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
  2711. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
  2712. llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
  2713. CGF.EmitBlock(PreCondBB);
  2714. llvm::PHINode *PhiSrc =
  2715. Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
  2716. PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
  2717. llvm::PHINode *PhiDest =
  2718. Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
  2719. PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
  2720. Ptr = Address(PhiSrc, Ptr.getAlignment());
  2721. ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
  2722. llvm::Value *PtrDiff = Bld.CreatePtrDiff(
  2723. PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
  2724. Ptr.getPointer(), CGF.VoidPtrTy));
  2725. Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
  2726. ThenBB, ExitBB);
  2727. CGF.EmitBlock(ThenBB);
  2728. llvm::Value *Res = createRuntimeShuffleFunction(
  2729. CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
  2730. IntType, Offset, Loc);
  2731. CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
  2732. Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
  2733. Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
  2734. PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
  2735. PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
  2736. CGF.EmitBranch(PreCondBB);
  2737. CGF.EmitBlock(ExitBB);
  2738. } else {
  2739. llvm::Value *Res = createRuntimeShuffleFunction(
  2740. CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
  2741. IntType, Offset, Loc);
  2742. CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
  2743. Ptr = Bld.CreateConstGEP(Ptr, 1);
  2744. ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
  2745. }
  2746. Size = Size % IntSize;
  2747. }
  2748. }
  2749. namespace {
  2750. enum CopyAction : unsigned {
  2751. // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
  2752. // the warp using shuffle instructions.
  2753. RemoteLaneToThread,
  2754. // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
  2755. ThreadCopy,
  2756. // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
  2757. ThreadToScratchpad,
  2758. // ScratchpadToThread: Copy from a scratchpad array in global memory
  2759. // containing team-reduced data to a thread's stack.
  2760. ScratchpadToThread,
  2761. };
  2762. } // namespace
  2763. struct CopyOptionsTy {
  2764. llvm::Value *RemoteLaneOffset;
  2765. llvm::Value *ScratchpadIndex;
  2766. llvm::Value *ScratchpadWidth;
  2767. };
  2768. /// Emit instructions to copy a Reduce list, which contains partially
  2769. /// aggregated values, in the specified direction.
  2770. static void emitReductionListCopy(
  2771. CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
  2772. ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
  2773. CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
  2774. CodeGenModule &CGM = CGF.CGM;
  2775. ASTContext &C = CGM.getContext();
  2776. CGBuilderTy &Bld = CGF.Builder;
  2777. llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
  2778. llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
  2779. llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
  2780. // Iterates, element-by-element, through the source Reduce list and
  2781. // make a copy.
  2782. unsigned Idx = 0;
  2783. unsigned Size = Privates.size();
  2784. for (const Expr *Private : Privates) {
  2785. Address SrcElementAddr = Address::invalid();
  2786. Address DestElementAddr = Address::invalid();
  2787. Address DestElementPtrAddr = Address::invalid();
  2788. // Should we shuffle in an element from a remote lane?
  2789. bool ShuffleInElement = false;
  2790. // Set to true to update the pointer in the dest Reduce list to a
  2791. // newly created element.
  2792. bool UpdateDestListPtr = false;
  2793. // Increment the src or dest pointer to the scratchpad, for each
  2794. // new element.
  2795. bool IncrScratchpadSrc = false;
  2796. bool IncrScratchpadDest = false;
  2797. switch (Action) {
  2798. case RemoteLaneToThread: {
  2799. // Step 1.1: Get the address for the src element in the Reduce list.
  2800. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  2801. SrcElementAddr = CGF.EmitLoadOfPointer(
  2802. SrcElementPtrAddr,
  2803. C.getPointerType(Private->getType())->castAs<PointerType>());
  2804. // Step 1.2: Create a temporary to store the element in the destination
  2805. // Reduce list.
  2806. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  2807. DestElementAddr =
  2808. CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
  2809. ShuffleInElement = true;
  2810. UpdateDestListPtr = true;
  2811. break;
  2812. }
  2813. case ThreadCopy: {
  2814. // Step 1.1: Get the address for the src element in the Reduce list.
  2815. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  2816. SrcElementAddr = CGF.EmitLoadOfPointer(
  2817. SrcElementPtrAddr,
  2818. C.getPointerType(Private->getType())->castAs<PointerType>());
  2819. // Step 1.2: Get the address for dest element. The destination
  2820. // element has already been created on the thread's stack.
  2821. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  2822. DestElementAddr = CGF.EmitLoadOfPointer(
  2823. DestElementPtrAddr,
  2824. C.getPointerType(Private->getType())->castAs<PointerType>());
  2825. break;
  2826. }
  2827. case ThreadToScratchpad: {
  2828. // Step 1.1: Get the address for the src element in the Reduce list.
  2829. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  2830. SrcElementAddr = CGF.EmitLoadOfPointer(
  2831. SrcElementPtrAddr,
  2832. C.getPointerType(Private->getType())->castAs<PointerType>());
  2833. // Step 1.2: Get the address for dest element:
  2834. // address = base + index * ElementSizeInChars.
  2835. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  2836. llvm::Value *CurrentOffset =
  2837. Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
  2838. llvm::Value *ScratchPadElemAbsolutePtrVal =
  2839. Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
  2840. ScratchPadElemAbsolutePtrVal =
  2841. Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
  2842. DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
  2843. C.getTypeAlignInChars(Private->getType()));
  2844. IncrScratchpadDest = true;
  2845. break;
  2846. }
  2847. case ScratchpadToThread: {
  2848. // Step 1.1: Get the address for the src element in the scratchpad.
  2849. // address = base + index * ElementSizeInChars.
  2850. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  2851. llvm::Value *CurrentOffset =
  2852. Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
  2853. llvm::Value *ScratchPadElemAbsolutePtrVal =
  2854. Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
  2855. ScratchPadElemAbsolutePtrVal =
  2856. Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
  2857. SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
  2858. C.getTypeAlignInChars(Private->getType()));
  2859. IncrScratchpadSrc = true;
  2860. // Step 1.2: Create a temporary to store the element in the destination
  2861. // Reduce list.
  2862. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  2863. DestElementAddr =
  2864. CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
  2865. UpdateDestListPtr = true;
  2866. break;
  2867. }
  2868. }
  2869. // Regardless of src and dest of copy, we emit the load of src
  2870. // element as this is required in all directions
  2871. SrcElementAddr = Bld.CreateElementBitCast(
  2872. SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
  2873. DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
  2874. SrcElementAddr.getElementType());
  2875. // Now that all active lanes have read the element in the
  2876. // Reduce list, shuffle over the value from the remote lane.
  2877. if (ShuffleInElement) {
  2878. shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
  2879. RemoteLaneOffset, Private->getExprLoc());
  2880. } else {
  2881. switch (CGF.getEvaluationKind(Private->getType())) {
  2882. case TEK_Scalar: {
  2883. llvm::Value *Elem =
  2884. CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
  2885. Private->getType(), Private->getExprLoc());
  2886. // Store the source element value to the dest element address.
  2887. CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
  2888. Private->getType());
  2889. break;
  2890. }
  2891. case TEK_Complex: {
  2892. CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
  2893. CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
  2894. Private->getExprLoc());
  2895. CGF.EmitStoreOfComplex(
  2896. Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
  2897. /*isInit=*/false);
  2898. break;
  2899. }
  2900. case TEK_Aggregate:
  2901. CGF.EmitAggregateCopy(
  2902. CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
  2903. CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
  2904. Private->getType(), AggValueSlot::DoesNotOverlap);
  2905. break;
  2906. }
  2907. }
  2908. // Step 3.1: Modify reference in dest Reduce list as needed.
  2909. // Modifying the reference in Reduce list to point to the newly
  2910. // created element. The element is live in the current function
  2911. // scope and that of functions it invokes (i.e., reduce_function).
  2912. // RemoteReduceData[i] = (void*)&RemoteElem
  2913. if (UpdateDestListPtr) {
  2914. CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
  2915. DestElementAddr.getPointer(), CGF.VoidPtrTy),
  2916. DestElementPtrAddr, /*Volatile=*/false,
  2917. C.VoidPtrTy);
  2918. }
  2919. // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
  2920. // address of the next element in scratchpad memory, unless we're currently
  2921. // processing the last one. Memory alignment is also taken care of here.
  2922. if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
  2923. llvm::Value *ScratchpadBasePtr =
  2924. IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
  2925. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  2926. ScratchpadBasePtr = Bld.CreateNUWAdd(
  2927. ScratchpadBasePtr,
  2928. Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
  2929. // Take care of global memory alignment for performance
  2930. ScratchpadBasePtr = Bld.CreateNUWSub(
  2931. ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
  2932. ScratchpadBasePtr = Bld.CreateUDiv(
  2933. ScratchpadBasePtr,
  2934. llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
  2935. ScratchpadBasePtr = Bld.CreateNUWAdd(
  2936. ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
  2937. ScratchpadBasePtr = Bld.CreateNUWMul(
  2938. ScratchpadBasePtr,
  2939. llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
  2940. if (IncrScratchpadDest)
  2941. DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
  2942. else /* IncrScratchpadSrc = true */
  2943. SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
  2944. }
  2945. ++Idx;
  2946. }
  2947. }
  2948. /// This function emits a helper that gathers Reduce lists from the first
  2949. /// lane of every active warp to lanes in the first warp.
  2950. ///
  2951. /// void inter_warp_copy_func(void* reduce_data, num_warps)
  2952. /// shared smem[warp_size];
  2953. /// For all data entries D in reduce_data:
  2954. /// sync
  2955. /// If (I am the first lane in each warp)
  2956. /// Copy my local D to smem[warp_id]
  2957. /// sync
  2958. /// if (I am the first warp)
  2959. /// Copy smem[thread_id] to my local D
  2960. static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
  2961. ArrayRef<const Expr *> Privates,
  2962. QualType ReductionArrayTy,
  2963. SourceLocation Loc) {
  2964. ASTContext &C = CGM.getContext();
  2965. llvm::Module &M = CGM.getModule();
  2966. // ReduceList: thread local Reduce list.
  2967. // At the stage of the computation when this function is called, partially
  2968. // aggregated values reside in the first lane of every active warp.
  2969. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2970. C.VoidPtrTy, ImplicitParamDecl::Other);
  2971. // NumWarps: number of warps active in the parallel region. This could
  2972. // be smaller than 32 (max warps in a CTA) for partial block reduction.
  2973. ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2974. C.getIntTypeForBitwidth(32, /* Signed */ true),
  2975. ImplicitParamDecl::Other);
  2976. FunctionArgList Args;
  2977. Args.push_back(&ReduceListArg);
  2978. Args.push_back(&NumWarpsArg);
  2979. const CGFunctionInfo &CGFI =
  2980. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2981. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  2982. llvm::GlobalValue::InternalLinkage,
  2983. "_omp_reduction_inter_warp_copy_func", &M);
  2984. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2985. Fn->setDoesNotRecurse();
  2986. CodeGenFunction CGF(CGM);
  2987. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2988. CGBuilderTy &Bld = CGF.Builder;
  2989. // This array is used as a medium to transfer, one reduce element at a time,
  2990. // the data from the first lane of every warp to lanes in the first warp
  2991. // in order to perform the final step of a reduction in a parallel region
  2992. // (reduction across warps). The array is placed in NVPTX __shared__ memory
  2993. // for reduced latency, as well as to have a distinct copy for concurrently
  2994. // executing target regions. The array is declared with common linkage so
  2995. // as to be shared across compilation units.
  2996. StringRef TransferMediumName =
  2997. "__openmp_nvptx_data_transfer_temporary_storage";
  2998. llvm::GlobalVariable *TransferMedium =
  2999. M.getGlobalVariable(TransferMediumName);
  3000. if (!TransferMedium) {
  3001. auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
  3002. unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
  3003. TransferMedium = new llvm::GlobalVariable(
  3004. M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
  3005. llvm::Constant::getNullValue(Ty), TransferMediumName,
  3006. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  3007. SharedAddressSpace);
  3008. CGM.addCompilerUsedGlobal(TransferMedium);
  3009. }
  3010. // Get the CUDA thread id of the current OpenMP thread on the GPU.
  3011. llvm::Value *ThreadID = getNVPTXThreadID(CGF);
  3012. // nvptx_lane_id = nvptx_id % warpsize
  3013. llvm::Value *LaneID = getNVPTXLaneID(CGF);
  3014. // nvptx_warp_id = nvptx_id / warpsize
  3015. llvm::Value *WarpID = getNVPTXWarpID(CGF);
  3016. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3017. Address LocalReduceList(
  3018. Bld.CreatePointerBitCastOrAddrSpaceCast(
  3019. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  3020. C.VoidPtrTy, Loc),
  3021. CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
  3022. CGF.getPointerAlign());
  3023. unsigned Idx = 0;
  3024. for (const Expr *Private : Privates) {
  3025. //
  3026. // Warp master copies reduce element to transfer medium in __shared__
  3027. // memory.
  3028. //
  3029. unsigned RealTySize =
  3030. C.getTypeSizeInChars(Private->getType())
  3031. .alignTo(C.getTypeAlignInChars(Private->getType()))
  3032. .getQuantity();
  3033. for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
  3034. unsigned NumIters = RealTySize / TySize;
  3035. if (NumIters == 0)
  3036. continue;
  3037. QualType CType = C.getIntTypeForBitwidth(
  3038. C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
  3039. llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
  3040. CharUnits Align = CharUnits::fromQuantity(TySize);
  3041. llvm::Value *Cnt = nullptr;
  3042. Address CntAddr = Address::invalid();
  3043. llvm::BasicBlock *PrecondBB = nullptr;
  3044. llvm::BasicBlock *ExitBB = nullptr;
  3045. if (NumIters > 1) {
  3046. CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
  3047. CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
  3048. /*Volatile=*/false, C.IntTy);
  3049. PrecondBB = CGF.createBasicBlock("precond");
  3050. ExitBB = CGF.createBasicBlock("exit");
  3051. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
  3052. // There is no need to emit line number for unconditional branch.
  3053. (void)ApplyDebugLocation::CreateEmpty(CGF);
  3054. CGF.EmitBlock(PrecondBB);
  3055. Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
  3056. llvm::Value *Cmp =
  3057. Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
  3058. Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
  3059. CGF.EmitBlock(BodyBB);
  3060. }
  3061. // kmpc_barrier.
  3062. CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
  3063. /*EmitChecks=*/false,
  3064. /*ForceSimpleCall=*/true);
  3065. llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
  3066. llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
  3067. llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
  3068. // if (lane_id == 0)
  3069. llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
  3070. Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
  3071. CGF.EmitBlock(ThenBB);
  3072. // Reduce element = LocalReduceList[i]
  3073. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  3074. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  3075. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  3076. // elemptr = ((CopyType*)(elemptrptr)) + I
  3077. Address ElemPtr = Address(ElemPtrPtr, Align);
  3078. ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
  3079. if (NumIters > 1) {
  3080. ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
  3081. ElemPtr.getAlignment());
  3082. }
  3083. // Get pointer to location in transfer medium.
  3084. // MediumPtr = &medium[warp_id]
  3085. llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
  3086. TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
  3087. Address MediumPtr(MediumPtrVal, Align);
  3088. // Casting to actual data type.
  3089. // MediumPtr = (CopyType*)MediumPtrAddr;
  3090. MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
  3091. // elem = *elemptr
  3092. //*MediumPtr = elem
  3093. llvm::Value *Elem =
  3094. CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
  3095. // Store the source element value to the dest element address.
  3096. CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
  3097. Bld.CreateBr(MergeBB);
  3098. CGF.EmitBlock(ElseBB);
  3099. Bld.CreateBr(MergeBB);
  3100. CGF.EmitBlock(MergeBB);
  3101. // kmpc_barrier.
  3102. CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
  3103. /*EmitChecks=*/false,
  3104. /*ForceSimpleCall=*/true);
  3105. //
  3106. // Warp 0 copies reduce element from transfer medium.
  3107. //
  3108. llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
  3109. llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
  3110. llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
  3111. Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
  3112. llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
  3113. AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
  3114. // Up to 32 threads in warp 0 are active.
  3115. llvm::Value *IsActiveThread =
  3116. Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
  3117. Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
  3118. CGF.EmitBlock(W0ThenBB);
  3119. // SrcMediumPtr = &medium[tid]
  3120. llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
  3121. TransferMedium,
  3122. {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
  3123. Address SrcMediumPtr(SrcMediumPtrVal, Align);
  3124. // SrcMediumVal = *SrcMediumPtr;
  3125. SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
  3126. // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
  3127. Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  3128. llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
  3129. TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
  3130. Address TargetElemPtr = Address(TargetElemPtrVal, Align);
  3131. TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
  3132. if (NumIters > 1) {
  3133. TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
  3134. TargetElemPtr.getAlignment());
  3135. }
  3136. // *TargetElemPtr = SrcMediumVal;
  3137. llvm::Value *SrcMediumValue =
  3138. CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
  3139. CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
  3140. CType);
  3141. Bld.CreateBr(W0MergeBB);
  3142. CGF.EmitBlock(W0ElseBB);
  3143. Bld.CreateBr(W0MergeBB);
  3144. CGF.EmitBlock(W0MergeBB);
  3145. if (NumIters > 1) {
  3146. Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
  3147. CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
  3148. CGF.EmitBranch(PrecondBB);
  3149. (void)ApplyDebugLocation::CreateEmpty(CGF);
  3150. CGF.EmitBlock(ExitBB);
  3151. }
  3152. RealTySize %= TySize;
  3153. }
  3154. ++Idx;
  3155. }
  3156. CGF.FinishFunction();
  3157. return Fn;
  3158. }
  3159. /// Emit a helper that reduces data across two OpenMP threads (lanes)
  3160. /// in the same warp. It uses shuffle instructions to copy over data from
  3161. /// a remote lane's stack. The reduction algorithm performed is specified
  3162. /// by the fourth parameter.
  3163. ///
  3164. /// Algorithm Versions.
  3165. /// Full Warp Reduce (argument value 0):
  3166. /// This algorithm assumes that all 32 lanes are active and gathers
  3167. /// data from these 32 lanes, producing a single resultant value.
  3168. /// Contiguous Partial Warp Reduce (argument value 1):
  3169. /// This algorithm assumes that only a *contiguous* subset of lanes
  3170. /// are active. This happens for the last warp in a parallel region
  3171. /// when the user specified num_threads is not an integer multiple of
  3172. /// 32. This contiguous subset always starts with the zeroth lane.
  3173. /// Partial Warp Reduce (argument value 2):
  3174. /// This algorithm gathers data from any number of lanes at any position.
  3175. /// All reduced values are stored in the lowest possible lane. The set
  3176. /// of problems every algorithm addresses is a super set of those
  3177. /// addressable by algorithms with a lower version number. Overhead
  3178. /// increases as algorithm version increases.
  3179. ///
  3180. /// Terminology
  3181. /// Reduce element:
  3182. /// Reduce element refers to the individual data field with primitive
  3183. /// data types to be combined and reduced across threads.
  3184. /// Reduce list:
  3185. /// Reduce list refers to a collection of local, thread-private
  3186. /// reduce elements.
  3187. /// Remote Reduce list:
  3188. /// Remote Reduce list refers to a collection of remote (relative to
  3189. /// the current thread) reduce elements.
  3190. ///
  3191. /// We distinguish between three states of threads that are important to
  3192. /// the implementation of this function.
  3193. /// Alive threads:
  3194. /// Threads in a warp executing the SIMT instruction, as distinguished from
  3195. /// threads that are inactive due to divergent control flow.
  3196. /// Active threads:
  3197. /// The minimal set of threads that has to be alive upon entry to this
  3198. /// function. The computation is correct iff active threads are alive.
  3199. /// Some threads are alive but they are not active because they do not
  3200. /// contribute to the computation in any useful manner. Turning them off
  3201. /// may introduce control flow overheads without any tangible benefits.
  3202. /// Effective threads:
  3203. /// In order to comply with the argument requirements of the shuffle
  3204. /// function, we must keep all lanes holding data alive. But at most
  3205. /// half of them perform value aggregation; we refer to this half of
  3206. /// threads as effective. The other half is simply handing off their
  3207. /// data.
  3208. ///
  3209. /// Procedure
  3210. /// Value shuffle:
  3211. /// In this step active threads transfer data from higher lane positions
  3212. /// in the warp to lower lane positions, creating Remote Reduce list.
  3213. /// Value aggregation:
  3214. /// In this step, effective threads combine their thread local Reduce list
  3215. /// with Remote Reduce list and store the result in the thread local
  3216. /// Reduce list.
  3217. /// Value copy:
  3218. /// In this step, we deal with the assumption made by algorithm 2
  3219. /// (i.e. contiguity assumption). When we have an odd number of lanes
  3220. /// active, say 2k+1, only k threads will be effective and therefore k
  3221. /// new values will be produced. However, the Reduce list owned by the
  3222. /// (2k+1)th thread is ignored in the value aggregation. Therefore
  3223. /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
  3224. /// that the contiguity assumption still holds.
  3225. static llvm::Function *emitShuffleAndReduceFunction(
  3226. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  3227. QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
  3228. ASTContext &C = CGM.getContext();
  3229. // Thread local Reduce list used to host the values of data to be reduced.
  3230. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3231. C.VoidPtrTy, ImplicitParamDecl::Other);
  3232. // Current lane id; could be logical.
  3233. ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
  3234. ImplicitParamDecl::Other);
  3235. // Offset of the remote source lane relative to the current lane.
  3236. ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3237. C.ShortTy, ImplicitParamDecl::Other);
  3238. // Algorithm version. This is expected to be known at compile time.
  3239. ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3240. C.ShortTy, ImplicitParamDecl::Other);
  3241. FunctionArgList Args;
  3242. Args.push_back(&ReduceListArg);
  3243. Args.push_back(&LaneIDArg);
  3244. Args.push_back(&RemoteLaneOffsetArg);
  3245. Args.push_back(&AlgoVerArg);
  3246. const CGFunctionInfo &CGFI =
  3247. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3248. auto *Fn = llvm::Function::Create(
  3249. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  3250. "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
  3251. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3252. Fn->setDoesNotRecurse();
  3253. if (CGM.getLangOpts().Optimize) {
  3254. Fn->removeFnAttr(llvm::Attribute::NoInline);
  3255. Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
  3256. Fn->addFnAttr(llvm::Attribute::AlwaysInline);
  3257. }
  3258. CodeGenFunction CGF(CGM);
  3259. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3260. CGBuilderTy &Bld = CGF.Builder;
  3261. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3262. Address LocalReduceList(
  3263. Bld.CreatePointerBitCastOrAddrSpaceCast(
  3264. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  3265. C.VoidPtrTy, SourceLocation()),
  3266. CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
  3267. CGF.getPointerAlign());
  3268. Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
  3269. llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
  3270. AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  3271. Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
  3272. llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
  3273. AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  3274. Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
  3275. llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
  3276. AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  3277. // Create a local thread-private variable to host the Reduce list
  3278. // from a remote lane.
  3279. Address RemoteReduceList =
  3280. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
  3281. // This loop iterates through the list of reduce elements and copies,
  3282. // element by element, from a remote lane in the warp to RemoteReduceList,
  3283. // hosted on the thread's stack.
  3284. emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
  3285. LocalReduceList, RemoteReduceList,
  3286. {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
  3287. /*ScratchpadIndex=*/nullptr,
  3288. /*ScratchpadWidth=*/nullptr});
  3289. // The actions to be performed on the Remote Reduce list is dependent
  3290. // on the algorithm version.
  3291. //
  3292. // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
  3293. // LaneId % 2 == 0 && Offset > 0):
  3294. // do the reduction value aggregation
  3295. //
  3296. // The thread local variable Reduce list is mutated in place to host the
  3297. // reduced data, which is the aggregated value produced from local and
  3298. // remote lanes.
  3299. //
  3300. // Note that AlgoVer is expected to be a constant integer known at compile
  3301. // time.
  3302. // When AlgoVer==0, the first conjunction evaluates to true, making
  3303. // the entire predicate true during compile time.
  3304. // When AlgoVer==1, the second conjunction has only the second part to be
  3305. // evaluated during runtime. Other conjunctions evaluates to false
  3306. // during compile time.
  3307. // When AlgoVer==2, the third conjunction has only the second part to be
  3308. // evaluated during runtime. Other conjunctions evaluates to false
  3309. // during compile time.
  3310. llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
  3311. llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
  3312. llvm::Value *CondAlgo1 = Bld.CreateAnd(
  3313. Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
  3314. llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
  3315. llvm::Value *CondAlgo2 = Bld.CreateAnd(
  3316. Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
  3317. CondAlgo2 = Bld.CreateAnd(
  3318. CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
  3319. llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
  3320. CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
  3321. llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
  3322. llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
  3323. llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
  3324. Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
  3325. CGF.EmitBlock(ThenBB);
  3326. // reduce_function(LocalReduceList, RemoteReduceList)
  3327. llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3328. LocalReduceList.getPointer(), CGF.VoidPtrTy);
  3329. llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3330. RemoteReduceList.getPointer(), CGF.VoidPtrTy);
  3331. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  3332. CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
  3333. Bld.CreateBr(MergeBB);
  3334. CGF.EmitBlock(ElseBB);
  3335. Bld.CreateBr(MergeBB);
  3336. CGF.EmitBlock(MergeBB);
  3337. // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
  3338. // Reduce list.
  3339. Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
  3340. llvm::Value *CondCopy = Bld.CreateAnd(
  3341. Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
  3342. llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
  3343. llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
  3344. llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
  3345. Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
  3346. CGF.EmitBlock(CpyThenBB);
  3347. emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
  3348. RemoteReduceList, LocalReduceList);
  3349. Bld.CreateBr(CpyMergeBB);
  3350. CGF.EmitBlock(CpyElseBB);
  3351. Bld.CreateBr(CpyMergeBB);
  3352. CGF.EmitBlock(CpyMergeBB);
  3353. CGF.FinishFunction();
  3354. return Fn;
  3355. }
  3356. /// This function emits a helper that copies all the reduction variables from
  3357. /// the team into the provided global buffer for the reduction variables.
  3358. ///
  3359. /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
  3360. /// For all data entries D in reduce_data:
  3361. /// Copy local D to buffer.D[Idx]
  3362. static llvm::Value *emitListToGlobalCopyFunction(
  3363. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  3364. QualType ReductionArrayTy, SourceLocation Loc,
  3365. const RecordDecl *TeamReductionRec,
  3366. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  3367. &VarFieldMap) {
  3368. ASTContext &C = CGM.getContext();
  3369. // Buffer: global reduction buffer.
  3370. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3371. C.VoidPtrTy, ImplicitParamDecl::Other);
  3372. // Idx: index of the buffer.
  3373. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  3374. ImplicitParamDecl::Other);
  3375. // ReduceList: thread local Reduce list.
  3376. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3377. C.VoidPtrTy, ImplicitParamDecl::Other);
  3378. FunctionArgList Args;
  3379. Args.push_back(&BufferArg);
  3380. Args.push_back(&IdxArg);
  3381. Args.push_back(&ReduceListArg);
  3382. const CGFunctionInfo &CGFI =
  3383. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3384. auto *Fn = llvm::Function::Create(
  3385. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  3386. "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
  3387. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3388. Fn->setDoesNotRecurse();
  3389. CodeGenFunction CGF(CGM);
  3390. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3391. CGBuilderTy &Bld = CGF.Builder;
  3392. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3393. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  3394. Address LocalReduceList(
  3395. Bld.CreatePointerBitCastOrAddrSpaceCast(
  3396. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  3397. C.VoidPtrTy, Loc),
  3398. CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
  3399. CGF.getPointerAlign());
  3400. QualType StaticTy = C.getRecordType(TeamReductionRec);
  3401. llvm::Type *LLVMReductionsBufferTy =
  3402. CGM.getTypes().ConvertTypeForMem(StaticTy);
  3403. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3404. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  3405. LLVMReductionsBufferTy->getPointerTo());
  3406. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  3407. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  3408. /*Volatile=*/false, C.IntTy,
  3409. Loc)};
  3410. unsigned Idx = 0;
  3411. for (const Expr *Private : Privates) {
  3412. // Reduce element = LocalReduceList[i]
  3413. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  3414. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  3415. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  3416. // elemptr = ((CopyType*)(elemptrptr)) + I
  3417. ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3418. ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
  3419. Address ElemPtr =
  3420. Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
  3421. const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
  3422. // Global = Buffer.VD[Idx];
  3423. const FieldDecl *FD = VarFieldMap.lookup(VD);
  3424. LValue GlobLVal = CGF.EmitLValueForField(
  3425. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  3426. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
  3427. GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
  3428. switch (CGF.getEvaluationKind(Private->getType())) {
  3429. case TEK_Scalar: {
  3430. llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
  3431. Private->getType(), Loc);
  3432. CGF.EmitStoreOfScalar(V, GlobLVal);
  3433. break;
  3434. }
  3435. case TEK_Complex: {
  3436. CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
  3437. CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
  3438. CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
  3439. break;
  3440. }
  3441. case TEK_Aggregate:
  3442. CGF.EmitAggregateCopy(GlobLVal,
  3443. CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  3444. Private->getType(), AggValueSlot::DoesNotOverlap);
  3445. break;
  3446. }
  3447. ++Idx;
  3448. }
  3449. CGF.FinishFunction();
  3450. return Fn;
  3451. }
  3452. /// This function emits a helper that reduces all the reduction variables from
  3453. /// the team into the provided global buffer for the reduction variables.
  3454. ///
  3455. /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
  3456. /// void *GlobPtrs[];
  3457. /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
  3458. /// ...
  3459. /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
  3460. /// reduce_function(GlobPtrs, reduce_data);
  3461. static llvm::Value *emitListToGlobalReduceFunction(
  3462. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  3463. QualType ReductionArrayTy, SourceLocation Loc,
  3464. const RecordDecl *TeamReductionRec,
  3465. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  3466. &VarFieldMap,
  3467. llvm::Function *ReduceFn) {
  3468. ASTContext &C = CGM.getContext();
  3469. // Buffer: global reduction buffer.
  3470. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3471. C.VoidPtrTy, ImplicitParamDecl::Other);
  3472. // Idx: index of the buffer.
  3473. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  3474. ImplicitParamDecl::Other);
  3475. // ReduceList: thread local Reduce list.
  3476. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3477. C.VoidPtrTy, ImplicitParamDecl::Other);
  3478. FunctionArgList Args;
  3479. Args.push_back(&BufferArg);
  3480. Args.push_back(&IdxArg);
  3481. Args.push_back(&ReduceListArg);
  3482. const CGFunctionInfo &CGFI =
  3483. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3484. auto *Fn = llvm::Function::Create(
  3485. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  3486. "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
  3487. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3488. Fn->setDoesNotRecurse();
  3489. CodeGenFunction CGF(CGM);
  3490. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3491. CGBuilderTy &Bld = CGF.Builder;
  3492. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  3493. QualType StaticTy = C.getRecordType(TeamReductionRec);
  3494. llvm::Type *LLVMReductionsBufferTy =
  3495. CGM.getTypes().ConvertTypeForMem(StaticTy);
  3496. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3497. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  3498. LLVMReductionsBufferTy->getPointerTo());
  3499. // 1. Build a list of reduction variables.
  3500. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  3501. Address ReductionList =
  3502. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  3503. auto IPriv = Privates.begin();
  3504. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  3505. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  3506. /*Volatile=*/false, C.IntTy,
  3507. Loc)};
  3508. unsigned Idx = 0;
  3509. for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
  3510. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  3511. // Global = Buffer.VD[Idx];
  3512. const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
  3513. const FieldDecl *FD = VarFieldMap.lookup(VD);
  3514. LValue GlobLVal = CGF.EmitLValueForField(
  3515. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  3516. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
  3517. llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
  3518. CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
  3519. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  3520. // Store array size.
  3521. ++Idx;
  3522. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  3523. llvm::Value *Size = CGF.Builder.CreateIntCast(
  3524. CGF.getVLASize(
  3525. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  3526. .NumElts,
  3527. CGF.SizeTy, /*isSigned=*/false);
  3528. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  3529. Elem);
  3530. }
  3531. }
  3532. // Call reduce_function(GlobalReduceList, ReduceList)
  3533. llvm::Value *GlobalReduceList =
  3534. CGF.EmitCastToVoidPtr(ReductionList.getPointer());
  3535. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3536. llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
  3537. AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
  3538. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  3539. CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
  3540. CGF.FinishFunction();
  3541. return Fn;
  3542. }
  3543. /// This function emits a helper that copies all the reduction variables from
  3544. /// the team into the provided global buffer for the reduction variables.
  3545. ///
  3546. /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
  3547. /// For all data entries D in reduce_data:
  3548. /// Copy buffer.D[Idx] to local D;
  3549. static llvm::Value *emitGlobalToListCopyFunction(
  3550. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  3551. QualType ReductionArrayTy, SourceLocation Loc,
  3552. const RecordDecl *TeamReductionRec,
  3553. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  3554. &VarFieldMap) {
  3555. ASTContext &C = CGM.getContext();
  3556. // Buffer: global reduction buffer.
  3557. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3558. C.VoidPtrTy, ImplicitParamDecl::Other);
  3559. // Idx: index of the buffer.
  3560. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  3561. ImplicitParamDecl::Other);
  3562. // ReduceList: thread local Reduce list.
  3563. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3564. C.VoidPtrTy, ImplicitParamDecl::Other);
  3565. FunctionArgList Args;
  3566. Args.push_back(&BufferArg);
  3567. Args.push_back(&IdxArg);
  3568. Args.push_back(&ReduceListArg);
  3569. const CGFunctionInfo &CGFI =
  3570. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3571. auto *Fn = llvm::Function::Create(
  3572. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  3573. "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
  3574. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3575. Fn->setDoesNotRecurse();
  3576. CodeGenFunction CGF(CGM);
  3577. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3578. CGBuilderTy &Bld = CGF.Builder;
  3579. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3580. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  3581. Address LocalReduceList(
  3582. Bld.CreatePointerBitCastOrAddrSpaceCast(
  3583. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  3584. C.VoidPtrTy, Loc),
  3585. CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
  3586. CGF.getPointerAlign());
  3587. QualType StaticTy = C.getRecordType(TeamReductionRec);
  3588. llvm::Type *LLVMReductionsBufferTy =
  3589. CGM.getTypes().ConvertTypeForMem(StaticTy);
  3590. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3591. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  3592. LLVMReductionsBufferTy->getPointerTo());
  3593. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  3594. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  3595. /*Volatile=*/false, C.IntTy,
  3596. Loc)};
  3597. unsigned Idx = 0;
  3598. for (const Expr *Private : Privates) {
  3599. // Reduce element = LocalReduceList[i]
  3600. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  3601. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  3602. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  3603. // elemptr = ((CopyType*)(elemptrptr)) + I
  3604. ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3605. ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
  3606. Address ElemPtr =
  3607. Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
  3608. const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
  3609. // Global = Buffer.VD[Idx];
  3610. const FieldDecl *FD = VarFieldMap.lookup(VD);
  3611. LValue GlobLVal = CGF.EmitLValueForField(
  3612. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  3613. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
  3614. GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
  3615. switch (CGF.getEvaluationKind(Private->getType())) {
  3616. case TEK_Scalar: {
  3617. llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
  3618. CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
  3619. break;
  3620. }
  3621. case TEK_Complex: {
  3622. CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
  3623. CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  3624. /*isInit=*/false);
  3625. break;
  3626. }
  3627. case TEK_Aggregate:
  3628. CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  3629. GlobLVal, Private->getType(),
  3630. AggValueSlot::DoesNotOverlap);
  3631. break;
  3632. }
  3633. ++Idx;
  3634. }
  3635. CGF.FinishFunction();
  3636. return Fn;
  3637. }
  3638. /// This function emits a helper that reduces all the reduction variables from
  3639. /// the team into the provided global buffer for the reduction variables.
  3640. ///
  3641. /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
  3642. /// void *GlobPtrs[];
  3643. /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
  3644. /// ...
  3645. /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
  3646. /// reduce_function(reduce_data, GlobPtrs);
  3647. static llvm::Value *emitGlobalToListReduceFunction(
  3648. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  3649. QualType ReductionArrayTy, SourceLocation Loc,
  3650. const RecordDecl *TeamReductionRec,
  3651. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  3652. &VarFieldMap,
  3653. llvm::Function *ReduceFn) {
  3654. ASTContext &C = CGM.getContext();
  3655. // Buffer: global reduction buffer.
  3656. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3657. C.VoidPtrTy, ImplicitParamDecl::Other);
  3658. // Idx: index of the buffer.
  3659. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  3660. ImplicitParamDecl::Other);
  3661. // ReduceList: thread local Reduce list.
  3662. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  3663. C.VoidPtrTy, ImplicitParamDecl::Other);
  3664. FunctionArgList Args;
  3665. Args.push_back(&BufferArg);
  3666. Args.push_back(&IdxArg);
  3667. Args.push_back(&ReduceListArg);
  3668. const CGFunctionInfo &CGFI =
  3669. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3670. auto *Fn = llvm::Function::Create(
  3671. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  3672. "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
  3673. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3674. Fn->setDoesNotRecurse();
  3675. CodeGenFunction CGF(CGM);
  3676. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3677. CGBuilderTy &Bld = CGF.Builder;
  3678. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  3679. QualType StaticTy = C.getRecordType(TeamReductionRec);
  3680. llvm::Type *LLVMReductionsBufferTy =
  3681. CGM.getTypes().ConvertTypeForMem(StaticTy);
  3682. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3683. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  3684. LLVMReductionsBufferTy->getPointerTo());
  3685. // 1. Build a list of reduction variables.
  3686. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  3687. Address ReductionList =
  3688. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  3689. auto IPriv = Privates.begin();
  3690. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  3691. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  3692. /*Volatile=*/false, C.IntTy,
  3693. Loc)};
  3694. unsigned Idx = 0;
  3695. for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
  3696. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  3697. // Global = Buffer.VD[Idx];
  3698. const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
  3699. const FieldDecl *FD = VarFieldMap.lookup(VD);
  3700. LValue GlobLVal = CGF.EmitLValueForField(
  3701. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  3702. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
  3703. llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
  3704. CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
  3705. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  3706. // Store array size.
  3707. ++Idx;
  3708. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  3709. llvm::Value *Size = CGF.Builder.CreateIntCast(
  3710. CGF.getVLASize(
  3711. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  3712. .NumElts,
  3713. CGF.SizeTy, /*isSigned=*/false);
  3714. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  3715. Elem);
  3716. }
  3717. }
  3718. // Call reduce_function(ReduceList, GlobalReduceList)
  3719. llvm::Value *GlobalReduceList =
  3720. CGF.EmitCastToVoidPtr(ReductionList.getPointer());
  3721. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  3722. llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
  3723. AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
  3724. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  3725. CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
  3726. CGF.FinishFunction();
  3727. return Fn;
  3728. }
  3729. ///
  3730. /// Design of OpenMP reductions on the GPU
  3731. ///
  3732. /// Consider a typical OpenMP program with one or more reduction
  3733. /// clauses:
  3734. ///
  3735. /// float foo;
  3736. /// double bar;
  3737. /// #pragma omp target teams distribute parallel for \
  3738. /// reduction(+:foo) reduction(*:bar)
  3739. /// for (int i = 0; i < N; i++) {
  3740. /// foo += A[i]; bar *= B[i];
  3741. /// }
  3742. ///
  3743. /// where 'foo' and 'bar' are reduced across all OpenMP threads in
  3744. /// all teams. In our OpenMP implementation on the NVPTX device an
  3745. /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
  3746. /// within a team are mapped to CUDA threads within a threadblock.
  3747. /// Our goal is to efficiently aggregate values across all OpenMP
  3748. /// threads such that:
  3749. ///
  3750. /// - the compiler and runtime are logically concise, and
  3751. /// - the reduction is performed efficiently in a hierarchical
  3752. /// manner as follows: within OpenMP threads in the same warp,
  3753. /// across warps in a threadblock, and finally across teams on
  3754. /// the NVPTX device.
  3755. ///
  3756. /// Introduction to Decoupling
  3757. ///
  3758. /// We would like to decouple the compiler and the runtime so that the
  3759. /// latter is ignorant of the reduction variables (number, data types)
  3760. /// and the reduction operators. This allows a simpler interface
  3761. /// and implementation while still attaining good performance.
  3762. ///
  3763. /// Pseudocode for the aforementioned OpenMP program generated by the
  3764. /// compiler is as follows:
  3765. ///
  3766. /// 1. Create private copies of reduction variables on each OpenMP
  3767. /// thread: 'foo_private', 'bar_private'
  3768. /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
  3769. /// to it and writes the result in 'foo_private' and 'bar_private'
  3770. /// respectively.
  3771. /// 3. Call the OpenMP runtime on the GPU to reduce within a team
  3772. /// and store the result on the team master:
  3773. ///
  3774. /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
  3775. /// reduceData, shuffleReduceFn, interWarpCpyFn)
  3776. ///
  3777. /// where:
  3778. /// struct ReduceData {
  3779. /// double *foo;
  3780. /// double *bar;
  3781. /// } reduceData
  3782. /// reduceData.foo = &foo_private
  3783. /// reduceData.bar = &bar_private
  3784. ///
  3785. /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
  3786. /// auxiliary functions generated by the compiler that operate on
  3787. /// variables of type 'ReduceData'. They aid the runtime perform
  3788. /// algorithmic steps in a data agnostic manner.
  3789. ///
  3790. /// 'shuffleReduceFn' is a pointer to a function that reduces data
  3791. /// of type 'ReduceData' across two OpenMP threads (lanes) in the
  3792. /// same warp. It takes the following arguments as input:
  3793. ///
  3794. /// a. variable of type 'ReduceData' on the calling lane,
  3795. /// b. its lane_id,
  3796. /// c. an offset relative to the current lane_id to generate a
  3797. /// remote_lane_id. The remote lane contains the second
  3798. /// variable of type 'ReduceData' that is to be reduced.
  3799. /// d. an algorithm version parameter determining which reduction
  3800. /// algorithm to use.
  3801. ///
  3802. /// 'shuffleReduceFn' retrieves data from the remote lane using
  3803. /// efficient GPU shuffle intrinsics and reduces, using the
  3804. /// algorithm specified by the 4th parameter, the two operands
  3805. /// element-wise. The result is written to the first operand.
  3806. ///
  3807. /// Different reduction algorithms are implemented in different
  3808. /// runtime functions, all calling 'shuffleReduceFn' to perform
  3809. /// the essential reduction step. Therefore, based on the 4th
  3810. /// parameter, this function behaves slightly differently to
  3811. /// cooperate with the runtime to ensure correctness under
  3812. /// different circumstances.
  3813. ///
  3814. /// 'InterWarpCpyFn' is a pointer to a function that transfers
  3815. /// reduced variables across warps. It tunnels, through CUDA
  3816. /// shared memory, the thread-private data of type 'ReduceData'
  3817. /// from lane 0 of each warp to a lane in the first warp.
  3818. /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
  3819. /// The last team writes the global reduced value to memory.
  3820. ///
  3821. /// ret = __kmpc_nvptx_teams_reduce_nowait(...,
  3822. /// reduceData, shuffleReduceFn, interWarpCpyFn,
  3823. /// scratchpadCopyFn, loadAndReduceFn)
  3824. ///
  3825. /// 'scratchpadCopyFn' is a helper that stores reduced
  3826. /// data from the team master to a scratchpad array in
  3827. /// global memory.
  3828. ///
  3829. /// 'loadAndReduceFn' is a helper that loads data from
  3830. /// the scratchpad array and reduces it with the input
  3831. /// operand.
  3832. ///
  3833. /// These compiler generated functions hide address
  3834. /// calculation and alignment information from the runtime.
  3835. /// 5. if ret == 1:
  3836. /// The team master of the last team stores the reduced
  3837. /// result to the globals in memory.
  3838. /// foo += reduceData.foo; bar *= reduceData.bar
  3839. ///
  3840. ///
  3841. /// Warp Reduction Algorithms
  3842. ///
  3843. /// On the warp level, we have three algorithms implemented in the
  3844. /// OpenMP runtime depending on the number of active lanes:
  3845. ///
  3846. /// Full Warp Reduction
  3847. ///
  3848. /// The reduce algorithm within a warp where all lanes are active
  3849. /// is implemented in the runtime as follows:
  3850. ///
  3851. /// full_warp_reduce(void *reduce_data,
  3852. /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
  3853. /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
  3854. /// ShuffleReduceFn(reduce_data, 0, offset, 0);
  3855. /// }
  3856. ///
  3857. /// The algorithm completes in log(2, WARPSIZE) steps.
  3858. ///
  3859. /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
  3860. /// not used therefore we save instructions by not retrieving lane_id
  3861. /// from the corresponding special registers. The 4th parameter, which
  3862. /// represents the version of the algorithm being used, is set to 0 to
  3863. /// signify full warp reduction.
  3864. ///
  3865. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  3866. ///
  3867. /// #reduce_elem refers to an element in the local lane's data structure
  3868. /// #remote_elem is retrieved from a remote lane
  3869. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  3870. /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
  3871. ///
  3872. /// Contiguous Partial Warp Reduction
  3873. ///
  3874. /// This reduce algorithm is used within a warp where only the first
  3875. /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
  3876. /// number of OpenMP threads in a parallel region is not a multiple of
  3877. /// WARPSIZE. The algorithm is implemented in the runtime as follows:
  3878. ///
  3879. /// void
  3880. /// contiguous_partial_reduce(void *reduce_data,
  3881. /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
  3882. /// int size, int lane_id) {
  3883. /// int curr_size;
  3884. /// int offset;
  3885. /// curr_size = size;
  3886. /// mask = curr_size/2;
  3887. /// while (offset>0) {
  3888. /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
  3889. /// curr_size = (curr_size+1)/2;
  3890. /// offset = curr_size/2;
  3891. /// }
  3892. /// }
  3893. ///
  3894. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  3895. ///
  3896. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  3897. /// if (lane_id < offset)
  3898. /// reduce_elem = reduce_elem REDUCE_OP remote_elem
  3899. /// else
  3900. /// reduce_elem = remote_elem
  3901. ///
  3902. /// This algorithm assumes that the data to be reduced are located in a
  3903. /// contiguous subset of lanes starting from the first. When there is
  3904. /// an odd number of active lanes, the data in the last lane is not
  3905. /// aggregated with any other lane's dat but is instead copied over.
  3906. ///
  3907. /// Dispersed Partial Warp Reduction
  3908. ///
  3909. /// This algorithm is used within a warp when any discontiguous subset of
  3910. /// lanes are active. It is used to implement the reduction operation
  3911. /// across lanes in an OpenMP simd region or in a nested parallel region.
  3912. ///
  3913. /// void
  3914. /// dispersed_partial_reduce(void *reduce_data,
  3915. /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
  3916. /// int size, remote_id;
  3917. /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
  3918. /// do {
  3919. /// remote_id = next_active_lane_id_right_after_me();
  3920. /// # the above function returns 0 of no active lane
  3921. /// # is present right after the current lane.
  3922. /// size = number_of_active_lanes_in_this_warp();
  3923. /// logical_lane_id /= 2;
  3924. /// ShuffleReduceFn(reduce_data, logical_lane_id,
  3925. /// remote_id-1-threadIdx.x, 2);
  3926. /// } while (logical_lane_id % 2 == 0 && size > 1);
  3927. /// }
  3928. ///
  3929. /// There is no assumption made about the initial state of the reduction.
  3930. /// Any number of lanes (>=1) could be active at any position. The reduction
  3931. /// result is returned in the first active lane.
  3932. ///
  3933. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  3934. ///
  3935. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  3936. /// if (lane_id % 2 == 0 && offset > 0)
  3937. /// reduce_elem = reduce_elem REDUCE_OP remote_elem
  3938. /// else
  3939. /// reduce_elem = remote_elem
  3940. ///
  3941. ///
  3942. /// Intra-Team Reduction
  3943. ///
  3944. /// This function, as implemented in the runtime call
  3945. /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
  3946. /// threads in a team. It first reduces within a warp using the
  3947. /// aforementioned algorithms. We then proceed to gather all such
  3948. /// reduced values at the first warp.
  3949. ///
  3950. /// The runtime makes use of the function 'InterWarpCpyFn', which copies
  3951. /// data from each of the "warp master" (zeroth lane of each warp, where
  3952. /// warp-reduced data is held) to the zeroth warp. This step reduces (in
  3953. /// a mathematical sense) the problem of reduction across warp masters in
  3954. /// a block to the problem of warp reduction.
  3955. ///
  3956. ///
  3957. /// Inter-Team Reduction
  3958. ///
  3959. /// Once a team has reduced its data to a single value, it is stored in
  3960. /// a global scratchpad array. Since each team has a distinct slot, this
  3961. /// can be done without locking.
  3962. ///
  3963. /// The last team to write to the scratchpad array proceeds to reduce the
  3964. /// scratchpad array. One or more workers in the last team use the helper
  3965. /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
  3966. /// the k'th worker reduces every k'th element.
  3967. ///
  3968. /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
  3969. /// reduce across workers and compute a globally reduced value.
  3970. ///
  3971. void CGOpenMPRuntimeNVPTX::emitReduction(
  3972. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
  3973. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  3974. ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
  3975. if (!CGF.HaveInsertPoint())
  3976. return;
  3977. bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
  3978. #ifndef NDEBUG
  3979. bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
  3980. #endif
  3981. if (Options.SimpleReduction) {
  3982. assert(!TeamsReduction && !ParallelReduction &&
  3983. "Invalid reduction selection in emitReduction.");
  3984. CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
  3985. ReductionOps, Options);
  3986. return;
  3987. }
  3988. assert((TeamsReduction || ParallelReduction) &&
  3989. "Invalid reduction selection in emitReduction.");
  3990. // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
  3991. // RedList, shuffle_reduce_func, interwarp_copy_func);
  3992. // or
  3993. // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
  3994. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  3995. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3996. llvm::Value *Res;
  3997. ASTContext &C = CGM.getContext();
  3998. // 1. Build a list of reduction variables.
  3999. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  4000. auto Size = RHSExprs.size();
  4001. for (const Expr *E : Privates) {
  4002. if (E->getType()->isVariablyModifiedType())
  4003. // Reserve place for array size.
  4004. ++Size;
  4005. }
  4006. llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
  4007. QualType ReductionArrayTy =
  4008. C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
  4009. /*IndexTypeQuals=*/0);
  4010. Address ReductionList =
  4011. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  4012. auto IPriv = Privates.begin();
  4013. unsigned Idx = 0;
  4014. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
  4015. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  4016. CGF.Builder.CreateStore(
  4017. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4018. CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
  4019. Elem);
  4020. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  4021. // Store array size.
  4022. ++Idx;
  4023. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  4024. llvm::Value *Size = CGF.Builder.CreateIntCast(
  4025. CGF.getVLASize(
  4026. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  4027. .NumElts,
  4028. CGF.SizeTy, /*isSigned=*/false);
  4029. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  4030. Elem);
  4031. }
  4032. }
  4033. llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4034. ReductionList.getPointer(), CGF.VoidPtrTy);
  4035. llvm::Function *ReductionFn = emitReductionFunction(
  4036. Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
  4037. LHSExprs, RHSExprs, ReductionOps);
  4038. llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
  4039. llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
  4040. CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
  4041. llvm::Value *InterWarpCopyFn =
  4042. emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
  4043. if (ParallelReduction) {
  4044. llvm::Value *Args[] = {RTLoc,
  4045. ThreadId,
  4046. CGF.Builder.getInt32(RHSExprs.size()),
  4047. ReductionArrayTySize,
  4048. RL,
  4049. ShuffleAndReduceFn,
  4050. InterWarpCopyFn};
  4051. Res = CGF.EmitRuntimeCall(
  4052. createNVPTXRuntimeFunction(
  4053. OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
  4054. Args);
  4055. } else {
  4056. assert(TeamsReduction && "expected teams reduction.");
  4057. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
  4058. llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
  4059. int Cnt = 0;
  4060. for (const Expr *DRE : Privates) {
  4061. PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
  4062. ++Cnt;
  4063. }
  4064. const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
  4065. CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
  4066. C.getLangOpts().OpenMPCUDAReductionBufNum);
  4067. TeamsReductions.push_back(TeamReductionRec);
  4068. if (!KernelTeamsReductionPtr) {
  4069. KernelTeamsReductionPtr = new llvm::GlobalVariable(
  4070. CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
  4071. llvm::GlobalValue::InternalLinkage, nullptr,
  4072. "_openmp_teams_reductions_buffer_$_$ptr");
  4073. }
  4074. llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
  4075. Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
  4076. /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
  4077. llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
  4078. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
  4079. llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
  4080. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
  4081. ReductionFn);
  4082. llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
  4083. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
  4084. llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
  4085. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
  4086. ReductionFn);
  4087. llvm::Value *Args[] = {
  4088. RTLoc,
  4089. ThreadId,
  4090. GlobalBufferPtr,
  4091. CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
  4092. RL,
  4093. ShuffleAndReduceFn,
  4094. InterWarpCopyFn,
  4095. GlobalToBufferCpyFn,
  4096. GlobalToBufferRedFn,
  4097. BufferToGlobalCpyFn,
  4098. BufferToGlobalRedFn};
  4099. Res = CGF.EmitRuntimeCall(
  4100. createNVPTXRuntimeFunction(
  4101. OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
  4102. Args);
  4103. }
  4104. // 5. Build if (res == 1)
  4105. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
  4106. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
  4107. llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
  4108. Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
  4109. CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
  4110. // 6. Build then branch: where we have reduced values in the master
  4111. // thread in each team.
  4112. // __kmpc_end_reduce{_nowait}(<gtid>);
  4113. // break;
  4114. CGF.EmitBlock(ThenBB);
  4115. // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
  4116. auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
  4117. this](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4118. auto IPriv = Privates.begin();
  4119. auto ILHS = LHSExprs.begin();
  4120. auto IRHS = RHSExprs.begin();
  4121. for (const Expr *E : ReductionOps) {
  4122. emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  4123. cast<DeclRefExpr>(*IRHS));
  4124. ++IPriv;
  4125. ++ILHS;
  4126. ++IRHS;
  4127. }
  4128. };
  4129. llvm::Value *EndArgs[] = {ThreadId};
  4130. RegionCodeGenTy RCG(CodeGen);
  4131. NVPTXActionTy Action(
  4132. nullptr, llvm::None,
  4133. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
  4134. EndArgs);
  4135. RCG.setAction(Action);
  4136. RCG(CGF);
  4137. // There is no need to emit line number for unconditional branch.
  4138. (void)ApplyDebugLocation::CreateEmpty(CGF);
  4139. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  4140. }
  4141. const VarDecl *
  4142. CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
  4143. const VarDecl *NativeParam) const {
  4144. if (!NativeParam->getType()->isReferenceType())
  4145. return NativeParam;
  4146. QualType ArgType = NativeParam->getType();
  4147. QualifierCollector QC;
  4148. const Type *NonQualTy = QC.strip(ArgType);
  4149. QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
  4150. if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
  4151. if (Attr->getCaptureKind() == OMPC_map) {
  4152. PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
  4153. LangAS::opencl_global);
  4154. } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
  4155. PointeeTy.isConstant(CGM.getContext())) {
  4156. PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
  4157. LangAS::opencl_generic);
  4158. }
  4159. }
  4160. ArgType = CGM.getContext().getPointerType(PointeeTy);
  4161. QC.addRestrict();
  4162. enum { NVPTX_local_addr = 5 };
  4163. QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
  4164. ArgType = QC.apply(CGM.getContext(), ArgType);
  4165. if (isa<ImplicitParamDecl>(NativeParam))
  4166. return ImplicitParamDecl::Create(
  4167. CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
  4168. NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
  4169. return ParmVarDecl::Create(
  4170. CGM.getContext(),
  4171. const_cast<DeclContext *>(NativeParam->getDeclContext()),
  4172. NativeParam->getBeginLoc(), NativeParam->getLocation(),
  4173. NativeParam->getIdentifier(), ArgType,
  4174. /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
  4175. }
  4176. Address
  4177. CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
  4178. const VarDecl *NativeParam,
  4179. const VarDecl *TargetParam) const {
  4180. assert(NativeParam != TargetParam &&
  4181. NativeParam->getType()->isReferenceType() &&
  4182. "Native arg must not be the same as target arg.");
  4183. Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
  4184. QualType NativeParamType = NativeParam->getType();
  4185. QualifierCollector QC;
  4186. const Type *NonQualTy = QC.strip(NativeParamType);
  4187. QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
  4188. unsigned NativePointeeAddrSpace =
  4189. CGF.getContext().getTargetAddressSpace(NativePointeeTy);
  4190. QualType TargetTy = TargetParam->getType();
  4191. llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
  4192. LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
  4193. // First cast to generic.
  4194. TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4195. TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
  4196. /*AddrSpace=*/0));
  4197. // Cast from generic to native address space.
  4198. TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4199. TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
  4200. NativePointeeAddrSpace));
  4201. Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
  4202. CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
  4203. NativeParamType);
  4204. return NativeParamAddr;
  4205. }
  4206. void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
  4207. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  4208. ArrayRef<llvm::Value *> Args) const {
  4209. SmallVector<llvm::Value *, 4> TargetArgs;
  4210. TargetArgs.reserve(Args.size());
  4211. auto *FnType = OutlinedFn.getFunctionType();
  4212. for (unsigned I = 0, E = Args.size(); I < E; ++I) {
  4213. if (FnType->isVarArg() && FnType->getNumParams() <= I) {
  4214. TargetArgs.append(std::next(Args.begin(), I), Args.end());
  4215. break;
  4216. }
  4217. llvm::Type *TargetType = FnType->getParamType(I);
  4218. llvm::Value *NativeArg = Args[I];
  4219. if (!TargetType->isPointerTy()) {
  4220. TargetArgs.emplace_back(NativeArg);
  4221. continue;
  4222. }
  4223. llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4224. NativeArg,
  4225. NativeArg->getType()->getPointerElementType()->getPointerTo());
  4226. TargetArgs.emplace_back(
  4227. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
  4228. }
  4229. CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
  4230. }
  4231. /// Emit function which wraps the outline parallel region
  4232. /// and controls the arguments which are passed to this function.
  4233. /// The wrapper ensures that the outlined function is called
  4234. /// with the correct arguments when data is shared.
  4235. llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
  4236. llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
  4237. ASTContext &Ctx = CGM.getContext();
  4238. const auto &CS = *D.getCapturedStmt(OMPD_parallel);
  4239. // Create a function that takes as argument the source thread.
  4240. FunctionArgList WrapperArgs;
  4241. QualType Int16QTy =
  4242. Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
  4243. QualType Int32QTy =
  4244. Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
  4245. ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
  4246. /*Id=*/nullptr, Int16QTy,
  4247. ImplicitParamDecl::Other);
  4248. ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
  4249. /*Id=*/nullptr, Int32QTy,
  4250. ImplicitParamDecl::Other);
  4251. WrapperArgs.emplace_back(&ParallelLevelArg);
  4252. WrapperArgs.emplace_back(&WrapperArg);
  4253. const CGFunctionInfo &CGFI =
  4254. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
  4255. auto *Fn = llvm::Function::Create(
  4256. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  4257. Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
  4258. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  4259. Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
  4260. Fn->setDoesNotRecurse();
  4261. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  4262. CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
  4263. D.getBeginLoc(), D.getBeginLoc());
  4264. const auto *RD = CS.getCapturedRecordDecl();
  4265. auto CurField = RD->field_begin();
  4266. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  4267. /*Name=*/".zero.addr");
  4268. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  4269. // Get the array of arguments.
  4270. SmallVector<llvm::Value *, 8> Args;
  4271. Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
  4272. Args.emplace_back(ZeroAddr.getPointer());
  4273. CGBuilderTy &Bld = CGF.Builder;
  4274. auto CI = CS.capture_begin();
  4275. // Use global memory for data sharing.
  4276. // Handle passing of global args to workers.
  4277. Address GlobalArgs =
  4278. CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
  4279. llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
  4280. llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
  4281. CGF.EmitRuntimeCall(
  4282. createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
  4283. DataSharingArgs);
  4284. // Retrieve the shared variables from the list of references returned
  4285. // by the runtime. Pass the variables to the outlined function.
  4286. Address SharedArgListAddress = Address::invalid();
  4287. if (CS.capture_size() > 0 ||
  4288. isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
  4289. SharedArgListAddress = CGF.EmitLoadOfPointer(
  4290. GlobalArgs, CGF.getContext()
  4291. .getPointerType(CGF.getContext().getPointerType(
  4292. CGF.getContext().VoidPtrTy))
  4293. .castAs<PointerType>());
  4294. }
  4295. unsigned Idx = 0;
  4296. if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
  4297. Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
  4298. Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  4299. Src, CGF.SizeTy->getPointerTo());
  4300. llvm::Value *LB = CGF.EmitLoadOfScalar(
  4301. TypedAddress,
  4302. /*Volatile=*/false,
  4303. CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
  4304. cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
  4305. Args.emplace_back(LB);
  4306. ++Idx;
  4307. Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
  4308. TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  4309. Src, CGF.SizeTy->getPointerTo());
  4310. llvm::Value *UB = CGF.EmitLoadOfScalar(
  4311. TypedAddress,
  4312. /*Volatile=*/false,
  4313. CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
  4314. cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
  4315. Args.emplace_back(UB);
  4316. ++Idx;
  4317. }
  4318. if (CS.capture_size() > 0) {
  4319. ASTContext &CGFContext = CGF.getContext();
  4320. for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
  4321. QualType ElemTy = CurField->getType();
  4322. Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
  4323. Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  4324. Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
  4325. llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
  4326. /*Volatile=*/false,
  4327. CGFContext.getPointerType(ElemTy),
  4328. CI->getLocation());
  4329. if (CI->capturesVariableByCopy() &&
  4330. !CI->getCapturedVar()->getType()->isAnyPointerType()) {
  4331. Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
  4332. CI->getLocation());
  4333. }
  4334. Args.emplace_back(Arg);
  4335. }
  4336. }
  4337. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
  4338. CGF.FinishFunction();
  4339. return Fn;
  4340. }
  4341. void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
  4342. const Decl *D) {
  4343. if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
  4344. return;
  4345. assert(D && "Expected function or captured|block decl.");
  4346. assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
  4347. "Function is registered already.");
  4348. assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
  4349. "Team is set but not processed.");
  4350. const Stmt *Body = nullptr;
  4351. bool NeedToDelayGlobalization = false;
  4352. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  4353. Body = FD->getBody();
  4354. } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  4355. Body = BD->getBody();
  4356. } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
  4357. Body = CD->getBody();
  4358. NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
  4359. if (NeedToDelayGlobalization &&
  4360. getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
  4361. return;
  4362. }
  4363. if (!Body)
  4364. return;
  4365. CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
  4366. VarChecker.Visit(Body);
  4367. const RecordDecl *GlobalizedVarsRecord =
  4368. VarChecker.getGlobalizedRecord(IsInTTDRegion);
  4369. TeamAndReductions.first = nullptr;
  4370. TeamAndReductions.second.clear();
  4371. ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
  4372. VarChecker.getEscapedVariableLengthDecls();
  4373. if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
  4374. return;
  4375. auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
  4376. I->getSecond().MappedParams =
  4377. std::make_unique<CodeGenFunction::OMPMapVars>();
  4378. I->getSecond().GlobalRecord = GlobalizedVarsRecord;
  4379. I->getSecond().EscapedParameters.insert(
  4380. VarChecker.getEscapedParameters().begin(),
  4381. VarChecker.getEscapedParameters().end());
  4382. I->getSecond().EscapedVariableLengthDecls.append(
  4383. EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
  4384. DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
  4385. for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
  4386. assert(VD->isCanonicalDecl() && "Expected canonical declaration");
  4387. const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
  4388. Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
  4389. }
  4390. if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
  4391. CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
  4392. VarChecker.Visit(Body);
  4393. I->getSecond().SecondaryGlobalRecord =
  4394. VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
  4395. I->getSecond().SecondaryLocalVarData.emplace();
  4396. DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
  4397. for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
  4398. assert(VD->isCanonicalDecl() && "Expected canonical declaration");
  4399. const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
  4400. Data.insert(
  4401. std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
  4402. }
  4403. }
  4404. if (!NeedToDelayGlobalization) {
  4405. emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
  4406. struct GlobalizationScope final : EHScopeStack::Cleanup {
  4407. GlobalizationScope() = default;
  4408. void Emit(CodeGenFunction &CGF, Flags flags) override {
  4409. static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
  4410. .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
  4411. }
  4412. };
  4413. CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
  4414. }
  4415. }
  4416. Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
  4417. const VarDecl *VD) {
  4418. if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
  4419. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  4420. switch (A->getAllocatorType()) {
  4421. // Use the default allocator here as by default local vars are
  4422. // threadlocal.
  4423. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  4424. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  4425. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  4426. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  4427. // Follow the user decision - use default allocation.
  4428. return Address::invalid();
  4429. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  4430. // TODO: implement aupport for user-defined allocators.
  4431. return Address::invalid();
  4432. case OMPAllocateDeclAttr::OMPConstMemAlloc: {
  4433. llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
  4434. auto *GV = new llvm::GlobalVariable(
  4435. CGM.getModule(), VarTy, /*isConstant=*/false,
  4436. llvm::GlobalValue::InternalLinkage,
  4437. llvm::Constant::getNullValue(VarTy), VD->getName(),
  4438. /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
  4439. CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
  4440. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  4441. GV->setAlignment(Align.getAsAlign());
  4442. return Address(GV, Align);
  4443. }
  4444. case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
  4445. llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
  4446. auto *GV = new llvm::GlobalVariable(
  4447. CGM.getModule(), VarTy, /*isConstant=*/false,
  4448. llvm::GlobalValue::InternalLinkage,
  4449. llvm::Constant::getNullValue(VarTy), VD->getName(),
  4450. /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
  4451. CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
  4452. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  4453. GV->setAlignment(Align.getAsAlign());
  4454. return Address(GV, Align);
  4455. }
  4456. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  4457. case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
  4458. llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
  4459. auto *GV = new llvm::GlobalVariable(
  4460. CGM.getModule(), VarTy, /*isConstant=*/false,
  4461. llvm::GlobalValue::InternalLinkage,
  4462. llvm::Constant::getNullValue(VarTy), VD->getName());
  4463. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  4464. GV->setAlignment(Align.getAsAlign());
  4465. return Address(GV, Align);
  4466. }
  4467. }
  4468. }
  4469. if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
  4470. return Address::invalid();
  4471. VD = VD->getCanonicalDecl();
  4472. auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  4473. if (I == FunctionGlobalizedDecls.end())
  4474. return Address::invalid();
  4475. auto VDI = I->getSecond().LocalVarData.find(VD);
  4476. if (VDI != I->getSecond().LocalVarData.end())
  4477. return VDI->second.PrivateAddr;
  4478. if (VD->hasAttrs()) {
  4479. for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
  4480. E(VD->attr_end());
  4481. IT != E; ++IT) {
  4482. auto VDI = I->getSecond().LocalVarData.find(
  4483. cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
  4484. ->getCanonicalDecl());
  4485. if (VDI != I->getSecond().LocalVarData.end())
  4486. return VDI->second.PrivateAddr;
  4487. }
  4488. }
  4489. return Address::invalid();
  4490. }
  4491. void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
  4492. FunctionGlobalizedDecls.erase(CGF.CurFn);
  4493. CGOpenMPRuntime::functionFinished(CGF);
  4494. }
  4495. void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
  4496. CodeGenFunction &CGF, const OMPLoopDirective &S,
  4497. OpenMPDistScheduleClauseKind &ScheduleKind,
  4498. llvm::Value *&Chunk) const {
  4499. if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
  4500. ScheduleKind = OMPC_DIST_SCHEDULE_static;
  4501. Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
  4502. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  4503. S.getIterationVariable()->getType(), S.getBeginLoc());
  4504. return;
  4505. }
  4506. CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
  4507. CGF, S, ScheduleKind, Chunk);
  4508. }
  4509. void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
  4510. CodeGenFunction &CGF, const OMPLoopDirective &S,
  4511. OpenMPScheduleClauseKind &ScheduleKind,
  4512. const Expr *&ChunkExpr) const {
  4513. ScheduleKind = OMPC_SCHEDULE_static;
  4514. // Chunk size is 1 in this case.
  4515. llvm::APInt ChunkSize(32, 1);
  4516. ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
  4517. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  4518. SourceLocation());
  4519. }
  4520. void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
  4521. CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
  4522. assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
  4523. " Expected target-based directive.");
  4524. const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
  4525. for (const CapturedStmt::Capture &C : CS->captures()) {
  4526. // Capture variables captured by reference in lambdas for target-based
  4527. // directives.
  4528. if (!C.capturesVariable())
  4529. continue;
  4530. const VarDecl *VD = C.getCapturedVar();
  4531. const auto *RD = VD->getType()
  4532. .getCanonicalType()
  4533. .getNonReferenceType()
  4534. ->getAsCXXRecordDecl();
  4535. if (!RD || !RD->isLambda())
  4536. continue;
  4537. Address VDAddr = CGF.GetAddrOfLocalVar(VD);
  4538. LValue VDLVal;
  4539. if (VD->getType().getCanonicalType()->isReferenceType())
  4540. VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
  4541. else
  4542. VDLVal = CGF.MakeAddrLValue(
  4543. VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
  4544. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  4545. FieldDecl *ThisCapture = nullptr;
  4546. RD->getCaptureFields(Captures, ThisCapture);
  4547. if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
  4548. LValue ThisLVal =
  4549. CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
  4550. llvm::Value *CXXThis = CGF.LoadCXXThis();
  4551. CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
  4552. }
  4553. for (const LambdaCapture &LC : RD->captures()) {
  4554. if (LC.getCaptureKind() != LCK_ByRef)
  4555. continue;
  4556. const VarDecl *VD = LC.getCapturedVar();
  4557. if (!CS->capturesVariable(VD))
  4558. continue;
  4559. auto It = Captures.find(VD);
  4560. assert(It != Captures.end() && "Found lambda capture without field.");
  4561. LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
  4562. Address VDAddr = CGF.GetAddrOfLocalVar(VD);
  4563. if (VD->getType().getCanonicalType()->isReferenceType())
  4564. VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
  4565. VD->getType().getCanonicalType())
  4566. .getAddress();
  4567. CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
  4568. }
  4569. }
  4570. }
  4571. unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
  4572. return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
  4573. }
  4574. bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
  4575. LangAS &AS) {
  4576. if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
  4577. return false;
  4578. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  4579. switch(A->getAllocatorType()) {
  4580. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  4581. // Not supported, fallback to the default mem space.
  4582. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  4583. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  4584. case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
  4585. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  4586. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  4587. AS = LangAS::Default;
  4588. return true;
  4589. case OMPAllocateDeclAttr::OMPConstMemAlloc:
  4590. AS = LangAS::cuda_constant;
  4591. return true;
  4592. case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
  4593. AS = LangAS::cuda_shared;
  4594. return true;
  4595. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  4596. llvm_unreachable("Expected predefined allocator for the variables with the "
  4597. "static storage.");
  4598. }
  4599. return false;
  4600. }
  4601. // Get current CudaArch and ignore any unknown values
  4602. static CudaArch getCudaArch(CodeGenModule &CGM) {
  4603. if (!CGM.getTarget().hasFeature("ptx"))
  4604. return CudaArch::UNKNOWN;
  4605. llvm::StringMap<bool> Features;
  4606. CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
  4607. CGM.getTarget().getTargetOpts().CPU,
  4608. CGM.getTarget().getTargetOpts().Features);
  4609. for (const auto &Feature : Features) {
  4610. if (Feature.getValue()) {
  4611. CudaArch Arch = StringToCudaArch(Feature.getKey());
  4612. if (Arch != CudaArch::UNKNOWN)
  4613. return Arch;
  4614. }
  4615. }
  4616. return CudaArch::UNKNOWN;
  4617. }
  4618. /// Check to see if target architecture supports unified addressing which is
  4619. /// a restriction for OpenMP requires clause "unified_shared_memory".
  4620. void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
  4621. const OMPRequiresDecl *D) {
  4622. for (const OMPClause *Clause : D->clauselists()) {
  4623. if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
  4624. switch (getCudaArch(CGM)) {
  4625. case CudaArch::SM_20:
  4626. case CudaArch::SM_21:
  4627. case CudaArch::SM_30:
  4628. case CudaArch::SM_32:
  4629. case CudaArch::SM_35:
  4630. case CudaArch::SM_37:
  4631. case CudaArch::SM_50:
  4632. case CudaArch::SM_52:
  4633. case CudaArch::SM_53:
  4634. case CudaArch::SM_60:
  4635. case CudaArch::SM_61:
  4636. case CudaArch::SM_62:
  4637. CGM.Error(Clause->getBeginLoc(),
  4638. "Target architecture does not support unified addressing");
  4639. return;
  4640. case CudaArch::SM_70:
  4641. case CudaArch::SM_72:
  4642. case CudaArch::SM_75:
  4643. case CudaArch::GFX600:
  4644. case CudaArch::GFX601:
  4645. case CudaArch::GFX700:
  4646. case CudaArch::GFX701:
  4647. case CudaArch::GFX702:
  4648. case CudaArch::GFX703:
  4649. case CudaArch::GFX704:
  4650. case CudaArch::GFX801:
  4651. case CudaArch::GFX802:
  4652. case CudaArch::GFX803:
  4653. case CudaArch::GFX810:
  4654. case CudaArch::GFX900:
  4655. case CudaArch::GFX902:
  4656. case CudaArch::GFX904:
  4657. case CudaArch::GFX906:
  4658. case CudaArch::GFX908:
  4659. case CudaArch::GFX909:
  4660. case CudaArch::GFX1010:
  4661. case CudaArch::GFX1011:
  4662. case CudaArch::GFX1012:
  4663. case CudaArch::UNKNOWN:
  4664. break;
  4665. case CudaArch::LAST:
  4666. llvm_unreachable("Unexpected Cuda arch.");
  4667. }
  4668. }
  4669. }
  4670. CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
  4671. }
  4672. /// Get number of SMs and number of blocks per SM.
  4673. static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
  4674. std::pair<unsigned, unsigned> Data;
  4675. if (CGM.getLangOpts().OpenMPCUDANumSMs)
  4676. Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
  4677. if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
  4678. Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
  4679. if (Data.first && Data.second)
  4680. return Data;
  4681. switch (getCudaArch(CGM)) {
  4682. case CudaArch::SM_20:
  4683. case CudaArch::SM_21:
  4684. case CudaArch::SM_30:
  4685. case CudaArch::SM_32:
  4686. case CudaArch::SM_35:
  4687. case CudaArch::SM_37:
  4688. case CudaArch::SM_50:
  4689. case CudaArch::SM_52:
  4690. case CudaArch::SM_53:
  4691. return {16, 16};
  4692. case CudaArch::SM_60:
  4693. case CudaArch::SM_61:
  4694. case CudaArch::SM_62:
  4695. return {56, 32};
  4696. case CudaArch::SM_70:
  4697. case CudaArch::SM_72:
  4698. case CudaArch::SM_75:
  4699. return {84, 32};
  4700. case CudaArch::GFX600:
  4701. case CudaArch::GFX601:
  4702. case CudaArch::GFX700:
  4703. case CudaArch::GFX701:
  4704. case CudaArch::GFX702:
  4705. case CudaArch::GFX703:
  4706. case CudaArch::GFX704:
  4707. case CudaArch::GFX801:
  4708. case CudaArch::GFX802:
  4709. case CudaArch::GFX803:
  4710. case CudaArch::GFX810:
  4711. case CudaArch::GFX900:
  4712. case CudaArch::GFX902:
  4713. case CudaArch::GFX904:
  4714. case CudaArch::GFX906:
  4715. case CudaArch::GFX908:
  4716. case CudaArch::GFX909:
  4717. case CudaArch::GFX1010:
  4718. case CudaArch::GFX1011:
  4719. case CudaArch::GFX1012:
  4720. case CudaArch::UNKNOWN:
  4721. break;
  4722. case CudaArch::LAST:
  4723. llvm_unreachable("Unexpected Cuda arch.");
  4724. }
  4725. llvm_unreachable("Unexpected NVPTX target without ptx feature.");
  4726. }
  4727. void CGOpenMPRuntimeNVPTX::clear() {
  4728. if (!GlobalizedRecords.empty()) {
  4729. ASTContext &C = CGM.getContext();
  4730. llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
  4731. llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
  4732. RecordDecl *StaticRD = C.buildImplicitRecord(
  4733. "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
  4734. StaticRD->startDefinition();
  4735. RecordDecl *SharedStaticRD = C.buildImplicitRecord(
  4736. "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
  4737. SharedStaticRD->startDefinition();
  4738. for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
  4739. if (Records.Records.empty())
  4740. continue;
  4741. unsigned Size = 0;
  4742. unsigned RecAlignment = 0;
  4743. for (const RecordDecl *RD : Records.Records) {
  4744. QualType RDTy = C.getRecordType(RD);
  4745. unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
  4746. RecAlignment = std::max(RecAlignment, Alignment);
  4747. unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
  4748. Size =
  4749. llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
  4750. }
  4751. Size = llvm::alignTo(Size, RecAlignment);
  4752. llvm::APInt ArySize(/*numBits=*/64, Size);
  4753. QualType SubTy = C.getConstantArrayType(
  4754. C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
  4755. const bool UseSharedMemory = Size <= SharedMemorySize;
  4756. auto *Field =
  4757. FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
  4758. SourceLocation(), SourceLocation(), nullptr, SubTy,
  4759. C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
  4760. /*BW=*/nullptr, /*Mutable=*/false,
  4761. /*InitStyle=*/ICIS_NoInit);
  4762. Field->setAccess(AS_public);
  4763. if (UseSharedMemory) {
  4764. SharedStaticRD->addDecl(Field);
  4765. SharedRecs.push_back(&Records);
  4766. } else {
  4767. StaticRD->addDecl(Field);
  4768. GlobalRecs.push_back(&Records);
  4769. }
  4770. Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
  4771. Records.UseSharedMemory->setInitializer(
  4772. llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
  4773. }
  4774. // Allocate SharedMemorySize buffer for the shared memory.
  4775. // FIXME: nvlink does not handle weak linkage correctly (object with the
  4776. // different size are reported as erroneous).
  4777. // Restore this code as sson as nvlink is fixed.
  4778. if (!SharedStaticRD->field_empty()) {
  4779. llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
  4780. QualType SubTy = C.getConstantArrayType(
  4781. C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
  4782. auto *Field = FieldDecl::Create(
  4783. C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
  4784. C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
  4785. /*BW=*/nullptr, /*Mutable=*/false,
  4786. /*InitStyle=*/ICIS_NoInit);
  4787. Field->setAccess(AS_public);
  4788. SharedStaticRD->addDecl(Field);
  4789. }
  4790. SharedStaticRD->completeDefinition();
  4791. if (!SharedStaticRD->field_empty()) {
  4792. QualType StaticTy = C.getRecordType(SharedStaticRD);
  4793. llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
  4794. auto *GV = new llvm::GlobalVariable(
  4795. CGM.getModule(), LLVMStaticTy,
  4796. /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
  4797. llvm::Constant::getNullValue(LLVMStaticTy),
  4798. "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
  4799. llvm::GlobalValue::NotThreadLocal,
  4800. C.getTargetAddressSpace(LangAS::cuda_shared));
  4801. auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  4802. GV, CGM.VoidPtrTy);
  4803. for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
  4804. Rec->Buffer->replaceAllUsesWith(Replacement);
  4805. Rec->Buffer->eraseFromParent();
  4806. }
  4807. }
  4808. StaticRD->completeDefinition();
  4809. if (!StaticRD->field_empty()) {
  4810. QualType StaticTy = C.getRecordType(StaticRD);
  4811. std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
  4812. llvm::APInt Size1(32, SMsBlockPerSM.second);
  4813. QualType Arr1Ty =
  4814. C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
  4815. /*IndexTypeQuals=*/0);
  4816. llvm::APInt Size2(32, SMsBlockPerSM.first);
  4817. QualType Arr2Ty =
  4818. C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
  4819. /*IndexTypeQuals=*/0);
  4820. llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
  4821. // FIXME: nvlink does not handle weak linkage correctly (object with the
  4822. // different size are reported as erroneous).
  4823. // Restore CommonLinkage as soon as nvlink is fixed.
  4824. auto *GV = new llvm::GlobalVariable(
  4825. CGM.getModule(), LLVMArr2Ty,
  4826. /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
  4827. llvm::Constant::getNullValue(LLVMArr2Ty),
  4828. "_openmp_static_glob_rd_$_");
  4829. auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  4830. GV, CGM.VoidPtrTy);
  4831. for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
  4832. Rec->Buffer->replaceAllUsesWith(Replacement);
  4833. Rec->Buffer->eraseFromParent();
  4834. }
  4835. }
  4836. }
  4837. if (!TeamsReductions.empty()) {
  4838. ASTContext &C = CGM.getContext();
  4839. RecordDecl *StaticRD = C.buildImplicitRecord(
  4840. "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
  4841. StaticRD->startDefinition();
  4842. for (const RecordDecl *TeamReductionRec : TeamsReductions) {
  4843. QualType RecTy = C.getRecordType(TeamReductionRec);
  4844. auto *Field = FieldDecl::Create(
  4845. C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
  4846. C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
  4847. /*BW=*/nullptr, /*Mutable=*/false,
  4848. /*InitStyle=*/ICIS_NoInit);
  4849. Field->setAccess(AS_public);
  4850. StaticRD->addDecl(Field);
  4851. }
  4852. StaticRD->completeDefinition();
  4853. QualType StaticTy = C.getRecordType(StaticRD);
  4854. llvm::Type *LLVMReductionsBufferTy =
  4855. CGM.getTypes().ConvertTypeForMem(StaticTy);
  4856. // FIXME: nvlink does not handle weak linkage correctly (object with the
  4857. // different size are reported as erroneous).
  4858. // Restore CommonLinkage as soon as nvlink is fixed.
  4859. auto *GV = new llvm::GlobalVariable(
  4860. CGM.getModule(), LLVMReductionsBufferTy,
  4861. /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
  4862. llvm::Constant::getNullValue(LLVMReductionsBufferTy),
  4863. "_openmp_teams_reductions_buffer_$_");
  4864. KernelTeamsReductionPtr->setInitializer(
  4865. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
  4866. CGM.VoidPtrTy));
  4867. }
  4868. CGOpenMPRuntime::clear();
  4869. }