CGOpenMPRuntimeNVPTX.cpp 213 KB

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