CGStmtOpenMP.cpp 330 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874
  1. //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
  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 contains code to emit OpenMP nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCleanup.h"
  13. #include "CGOpenMPRuntime.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "TargetInfo.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/OpenMPClause.h"
  21. #include "clang/AST/Stmt.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Basic/PrettyStackTrace.h"
  26. #include "llvm/ADT/SmallSet.h"
  27. #include "llvm/BinaryFormat/Dwarf.h"
  28. #include "llvm/Frontend/OpenMP/OMPConstants.h"
  29. #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DebugInfoMetadata.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/IR/Metadata.h"
  35. #include "llvm/Support/AtomicOrdering.h"
  36. #include <optional>
  37. using namespace clang;
  38. using namespace CodeGen;
  39. using namespace llvm::omp;
  40. static const VarDecl *getBaseDecl(const Expr *Ref);
  41. namespace {
  42. /// Lexical scope for OpenMP executable constructs, that handles correct codegen
  43. /// for captured expressions.
  44. class OMPLexicalScope : public CodeGenFunction::LexicalScope {
  45. void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  46. for (const auto *C : S.clauses()) {
  47. if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
  48. if (const auto *PreInit =
  49. cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
  50. for (const auto *I : PreInit->decls()) {
  51. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  52. CGF.EmitVarDecl(cast<VarDecl>(*I));
  53. } else {
  54. CodeGenFunction::AutoVarEmission Emission =
  55. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  56. CGF.EmitAutoVarCleanups(Emission);
  57. }
  58. }
  59. }
  60. }
  61. }
  62. }
  63. CodeGenFunction::OMPPrivateScope InlinedShareds;
  64. static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
  65. return CGF.LambdaCaptureFields.lookup(VD) ||
  66. (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
  67. (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
  68. cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
  69. }
  70. public:
  71. OMPLexicalScope(
  72. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  73. const std::optional<OpenMPDirectiveKind> CapturedRegion = std::nullopt,
  74. const bool EmitPreInitStmt = true)
  75. : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
  76. InlinedShareds(CGF) {
  77. if (EmitPreInitStmt)
  78. emitPreInitStmt(CGF, S);
  79. if (!CapturedRegion)
  80. return;
  81. assert(S.hasAssociatedStmt() &&
  82. "Expected associated statement for inlined directive.");
  83. const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
  84. for (const auto &C : CS->captures()) {
  85. if (C.capturesVariable() || C.capturesVariableByCopy()) {
  86. auto *VD = C.getCapturedVar();
  87. assert(VD == VD->getCanonicalDecl() &&
  88. "Canonical decl must be captured.");
  89. DeclRefExpr DRE(
  90. CGF.getContext(), const_cast<VarDecl *>(VD),
  91. isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
  92. InlinedShareds.isGlobalVarCaptured(VD)),
  93. VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
  94. InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF));
  95. }
  96. }
  97. (void)InlinedShareds.Privatize();
  98. }
  99. };
  100. /// Lexical scope for OpenMP parallel construct, that handles correct codegen
  101. /// for captured expressions.
  102. class OMPParallelScope final : public OMPLexicalScope {
  103. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  104. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  105. return !(isOpenMPTargetExecutionDirective(Kind) ||
  106. isOpenMPLoopBoundSharingDirective(Kind)) &&
  107. isOpenMPParallelDirective(Kind);
  108. }
  109. public:
  110. OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  111. : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
  112. EmitPreInitStmt(S)) {}
  113. };
  114. /// Lexical scope for OpenMP teams construct, that handles correct codegen
  115. /// for captured expressions.
  116. class OMPTeamsScope final : public OMPLexicalScope {
  117. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  118. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  119. return !isOpenMPTargetExecutionDirective(Kind) &&
  120. isOpenMPTeamsDirective(Kind);
  121. }
  122. public:
  123. OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  124. : OMPLexicalScope(CGF, S, /*CapturedRegion=*/std::nullopt,
  125. EmitPreInitStmt(S)) {}
  126. };
  127. /// Private scope for OpenMP loop-based directives, that supports capturing
  128. /// of used expression from loop statement.
  129. class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
  130. void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) {
  131. const DeclStmt *PreInits;
  132. CodeGenFunction::OMPMapVars PreCondVars;
  133. if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
  134. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  135. for (const auto *E : LD->counters()) {
  136. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  137. EmittedAsPrivate.insert(VD->getCanonicalDecl());
  138. (void)PreCondVars.setVarAddr(
  139. CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
  140. }
  141. // Mark private vars as undefs.
  142. for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) {
  143. for (const Expr *IRef : C->varlists()) {
  144. const auto *OrigVD =
  145. cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
  146. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  147. QualType OrigVDTy = OrigVD->getType().getNonReferenceType();
  148. (void)PreCondVars.setVarAddr(
  149. CGF, OrigVD,
  150. Address(llvm::UndefValue::get(CGF.ConvertTypeForMem(
  151. CGF.getContext().getPointerType(OrigVDTy))),
  152. CGF.ConvertTypeForMem(OrigVDTy),
  153. CGF.getContext().getDeclAlign(OrigVD)));
  154. }
  155. }
  156. }
  157. (void)PreCondVars.apply(CGF);
  158. // Emit init, __range and __end variables for C++ range loops.
  159. (void)OMPLoopBasedDirective::doForAllLoops(
  160. LD->getInnermostCapturedStmt()->getCapturedStmt(),
  161. /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(),
  162. [&CGF](unsigned Cnt, const Stmt *CurStmt) {
  163. if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) {
  164. if (const Stmt *Init = CXXFor->getInit())
  165. CGF.EmitStmt(Init);
  166. CGF.EmitStmt(CXXFor->getRangeStmt());
  167. CGF.EmitStmt(CXXFor->getEndStmt());
  168. }
  169. return false;
  170. });
  171. PreInits = cast_or_null<DeclStmt>(LD->getPreInits());
  172. } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) {
  173. PreInits = cast_or_null<DeclStmt>(Tile->getPreInits());
  174. } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) {
  175. PreInits = cast_or_null<DeclStmt>(Unroll->getPreInits());
  176. } else {
  177. llvm_unreachable("Unknown loop-based directive kind.");
  178. }
  179. if (PreInits) {
  180. for (const auto *I : PreInits->decls())
  181. CGF.EmitVarDecl(cast<VarDecl>(*I));
  182. }
  183. PreCondVars.restore(CGF);
  184. }
  185. public:
  186. OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S)
  187. : CodeGenFunction::RunCleanupsScope(CGF) {
  188. emitPreInitStmt(CGF, S);
  189. }
  190. };
  191. class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
  192. CodeGenFunction::OMPPrivateScope InlinedShareds;
  193. static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
  194. return CGF.LambdaCaptureFields.lookup(VD) ||
  195. (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
  196. (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
  197. cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
  198. }
  199. public:
  200. OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  201. : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
  202. InlinedShareds(CGF) {
  203. for (const auto *C : S.clauses()) {
  204. if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
  205. if (const auto *PreInit =
  206. cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
  207. for (const auto *I : PreInit->decls()) {
  208. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  209. CGF.EmitVarDecl(cast<VarDecl>(*I));
  210. } else {
  211. CodeGenFunction::AutoVarEmission Emission =
  212. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  213. CGF.EmitAutoVarCleanups(Emission);
  214. }
  215. }
  216. }
  217. } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
  218. for (const Expr *E : UDP->varlists()) {
  219. const Decl *D = cast<DeclRefExpr>(E)->getDecl();
  220. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
  221. CGF.EmitVarDecl(*OED);
  222. }
  223. } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) {
  224. for (const Expr *E : UDP->varlists()) {
  225. const Decl *D = getBaseDecl(E);
  226. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
  227. CGF.EmitVarDecl(*OED);
  228. }
  229. }
  230. }
  231. if (!isOpenMPSimdDirective(S.getDirectiveKind()))
  232. CGF.EmitOMPPrivateClause(S, InlinedShareds);
  233. if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
  234. if (const Expr *E = TG->getReductionRef())
  235. CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
  236. }
  237. // Temp copy arrays for inscan reductions should not be emitted as they are
  238. // not used in simd only mode.
  239. llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps;
  240. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  241. if (C->getModifier() != OMPC_REDUCTION_inscan)
  242. continue;
  243. for (const Expr *E : C->copy_array_temps())
  244. CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl());
  245. }
  246. const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
  247. while (CS) {
  248. for (auto &C : CS->captures()) {
  249. if (C.capturesVariable() || C.capturesVariableByCopy()) {
  250. auto *VD = C.getCapturedVar();
  251. if (CopyArrayTemps.contains(VD))
  252. continue;
  253. assert(VD == VD->getCanonicalDecl() &&
  254. "Canonical decl must be captured.");
  255. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
  256. isCapturedVar(CGF, VD) ||
  257. (CGF.CapturedStmtInfo &&
  258. InlinedShareds.isGlobalVarCaptured(VD)),
  259. VD->getType().getNonReferenceType(), VK_LValue,
  260. C.getLocation());
  261. InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF));
  262. }
  263. }
  264. CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
  265. }
  266. (void)InlinedShareds.Privatize();
  267. }
  268. };
  269. } // namespace
  270. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  271. const OMPExecutableDirective &S,
  272. const RegionCodeGenTy &CodeGen);
  273. LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
  274. if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
  275. if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
  276. OrigVD = OrigVD->getCanonicalDecl();
  277. bool IsCaptured =
  278. LambdaCaptureFields.lookup(OrigVD) ||
  279. (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
  280. (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
  281. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
  282. OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
  283. return EmitLValue(&DRE);
  284. }
  285. }
  286. return EmitLValue(E);
  287. }
  288. llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
  289. ASTContext &C = getContext();
  290. llvm::Value *Size = nullptr;
  291. auto SizeInChars = C.getTypeSizeInChars(Ty);
  292. if (SizeInChars.isZero()) {
  293. // getTypeSizeInChars() returns 0 for a VLA.
  294. while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
  295. VlaSizePair VlaSize = getVLASize(VAT);
  296. Ty = VlaSize.Type;
  297. Size =
  298. Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) : VlaSize.NumElts;
  299. }
  300. SizeInChars = C.getTypeSizeInChars(Ty);
  301. if (SizeInChars.isZero())
  302. return llvm::ConstantInt::get(SizeTy, /*V=*/0);
  303. return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
  304. }
  305. return CGM.getSize(SizeInChars);
  306. }
  307. void CodeGenFunction::GenerateOpenMPCapturedVars(
  308. const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
  309. const RecordDecl *RD = S.getCapturedRecordDecl();
  310. auto CurField = RD->field_begin();
  311. auto CurCap = S.captures().begin();
  312. for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
  313. E = S.capture_init_end();
  314. I != E; ++I, ++CurField, ++CurCap) {
  315. if (CurField->hasCapturedVLAType()) {
  316. const VariableArrayType *VAT = CurField->getCapturedVLAType();
  317. llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
  318. CapturedVars.push_back(Val);
  319. } else if (CurCap->capturesThis()) {
  320. CapturedVars.push_back(CXXThisValue);
  321. } else if (CurCap->capturesVariableByCopy()) {
  322. llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
  323. // If the field is not a pointer, we need to save the actual value
  324. // and load it as a void pointer.
  325. if (!CurField->getType()->isAnyPointerType()) {
  326. ASTContext &Ctx = getContext();
  327. Address DstAddr = CreateMemTemp(
  328. Ctx.getUIntPtrType(),
  329. Twine(CurCap->getCapturedVar()->getName(), ".casted"));
  330. LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
  331. llvm::Value *SrcAddrVal = EmitScalarConversion(
  332. DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
  333. Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
  334. LValue SrcLV =
  335. MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
  336. // Store the value using the source type pointer.
  337. EmitStoreThroughLValue(RValue::get(CV), SrcLV);
  338. // Load the value using the destination type pointer.
  339. CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
  340. }
  341. CapturedVars.push_back(CV);
  342. } else {
  343. assert(CurCap->capturesVariable() && "Expected capture by reference.");
  344. CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
  345. }
  346. }
  347. }
  348. static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
  349. QualType DstType, StringRef Name,
  350. LValue AddrLV) {
  351. ASTContext &Ctx = CGF.getContext();
  352. llvm::Value *CastedPtr = CGF.EmitScalarConversion(
  353. AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
  354. Ctx.getPointerType(DstType), Loc);
  355. Address TmpAddr =
  356. CGF.MakeNaturalAlignAddrLValue(CastedPtr, DstType).getAddress(CGF);
  357. return TmpAddr;
  358. }
  359. static QualType getCanonicalParamType(ASTContext &C, QualType T) {
  360. if (T->isLValueReferenceType())
  361. return C.getLValueReferenceType(
  362. getCanonicalParamType(C, T.getNonReferenceType()),
  363. /*SpelledAsLValue=*/false);
  364. if (T->isPointerType())
  365. return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
  366. if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
  367. if (const auto *VLA = dyn_cast<VariableArrayType>(A))
  368. return getCanonicalParamType(C, VLA->getElementType());
  369. if (!A->isVariablyModifiedType())
  370. return C.getCanonicalType(T);
  371. }
  372. return C.getCanonicalParamType(T);
  373. }
  374. namespace {
  375. /// Contains required data for proper outlined function codegen.
  376. struct FunctionOptions {
  377. /// Captured statement for which the function is generated.
  378. const CapturedStmt *S = nullptr;
  379. /// true if cast to/from UIntPtr is required for variables captured by
  380. /// value.
  381. const bool UIntPtrCastRequired = true;
  382. /// true if only casted arguments must be registered as local args or VLA
  383. /// sizes.
  384. const bool RegisterCastedArgsOnly = false;
  385. /// Name of the generated function.
  386. const StringRef FunctionName;
  387. /// Location of the non-debug version of the outlined function.
  388. SourceLocation Loc;
  389. explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
  390. bool RegisterCastedArgsOnly, StringRef FunctionName,
  391. SourceLocation Loc)
  392. : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
  393. RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
  394. FunctionName(FunctionName), Loc(Loc) {}
  395. };
  396. } // namespace
  397. static llvm::Function *emitOutlinedFunctionPrologue(
  398. CodeGenFunction &CGF, FunctionArgList &Args,
  399. llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
  400. &LocalAddrs,
  401. llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
  402. &VLASizes,
  403. llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
  404. const CapturedDecl *CD = FO.S->getCapturedDecl();
  405. const RecordDecl *RD = FO.S->getCapturedRecordDecl();
  406. assert(CD->hasBody() && "missing CapturedDecl body");
  407. CXXThisValue = nullptr;
  408. // Build the argument list.
  409. CodeGenModule &CGM = CGF.CGM;
  410. ASTContext &Ctx = CGM.getContext();
  411. FunctionArgList TargetArgs;
  412. Args.append(CD->param_begin(),
  413. std::next(CD->param_begin(), CD->getContextParamPosition()));
  414. TargetArgs.append(
  415. CD->param_begin(),
  416. std::next(CD->param_begin(), CD->getContextParamPosition()));
  417. auto I = FO.S->captures().begin();
  418. FunctionDecl *DebugFunctionDecl = nullptr;
  419. if (!FO.UIntPtrCastRequired) {
  420. FunctionProtoType::ExtProtoInfo EPI;
  421. QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, std::nullopt, EPI);
  422. DebugFunctionDecl = FunctionDecl::Create(
  423. Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
  424. SourceLocation(), DeclarationName(), FunctionTy,
  425. Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
  426. /*UsesFPIntrin=*/false, /*isInlineSpecified=*/false,
  427. /*hasWrittenPrototype=*/false);
  428. }
  429. for (const FieldDecl *FD : RD->fields()) {
  430. QualType ArgType = FD->getType();
  431. IdentifierInfo *II = nullptr;
  432. VarDecl *CapVar = nullptr;
  433. // If this is a capture by copy and the type is not a pointer, the outlined
  434. // function argument type should be uintptr and the value properly casted to
  435. // uintptr. This is necessary given that the runtime library is only able to
  436. // deal with pointers. We can pass in the same way the VLA type sizes to the
  437. // outlined function.
  438. if (FO.UIntPtrCastRequired &&
  439. ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
  440. I->capturesVariableArrayType()))
  441. ArgType = Ctx.getUIntPtrType();
  442. if (I->capturesVariable() || I->capturesVariableByCopy()) {
  443. CapVar = I->getCapturedVar();
  444. II = CapVar->getIdentifier();
  445. } else if (I->capturesThis()) {
  446. II = &Ctx.Idents.get("this");
  447. } else {
  448. assert(I->capturesVariableArrayType());
  449. II = &Ctx.Idents.get("vla");
  450. }
  451. if (ArgType->isVariablyModifiedType())
  452. ArgType = getCanonicalParamType(Ctx, ArgType);
  453. VarDecl *Arg;
  454. if (CapVar && (CapVar->getTLSKind() != clang::VarDecl::TLS_None)) {
  455. Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
  456. II, ArgType,
  457. ImplicitParamDecl::ThreadPrivateVar);
  458. } else if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
  459. Arg = ParmVarDecl::Create(
  460. Ctx, DebugFunctionDecl,
  461. CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
  462. CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
  463. /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
  464. } else {
  465. Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
  466. II, ArgType, ImplicitParamDecl::Other);
  467. }
  468. Args.emplace_back(Arg);
  469. // Do not cast arguments if we emit function with non-original types.
  470. TargetArgs.emplace_back(
  471. FO.UIntPtrCastRequired
  472. ? Arg
  473. : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
  474. ++I;
  475. }
  476. Args.append(std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
  477. CD->param_end());
  478. TargetArgs.append(
  479. std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
  480. CD->param_end());
  481. // Create the function declaration.
  482. const CGFunctionInfo &FuncInfo =
  483. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
  484. llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
  485. auto *F =
  486. llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
  487. FO.FunctionName, &CGM.getModule());
  488. CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
  489. if (CD->isNothrow())
  490. F->setDoesNotThrow();
  491. F->setDoesNotRecurse();
  492. // Always inline the outlined function if optimizations are enabled.
  493. if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
  494. F->removeFnAttr(llvm::Attribute::NoInline);
  495. F->addFnAttr(llvm::Attribute::AlwaysInline);
  496. }
  497. // Generate the function.
  498. CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
  499. FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
  500. FO.UIntPtrCastRequired ? FO.Loc
  501. : CD->getBody()->getBeginLoc());
  502. unsigned Cnt = CD->getContextParamPosition();
  503. I = FO.S->captures().begin();
  504. for (const FieldDecl *FD : RD->fields()) {
  505. // Do not map arguments if we emit function with non-original types.
  506. Address LocalAddr(Address::invalid());
  507. if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
  508. LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
  509. TargetArgs[Cnt]);
  510. } else {
  511. LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
  512. }
  513. // If we are capturing a pointer by copy we don't need to do anything, just
  514. // use the value that we get from the arguments.
  515. if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
  516. const VarDecl *CurVD = I->getCapturedVar();
  517. if (!FO.RegisterCastedArgsOnly)
  518. LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
  519. ++Cnt;
  520. ++I;
  521. continue;
  522. }
  523. LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
  524. AlignmentSource::Decl);
  525. if (FD->hasCapturedVLAType()) {
  526. if (FO.UIntPtrCastRequired) {
  527. ArgLVal = CGF.MakeAddrLValue(
  528. castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
  529. Args[Cnt]->getName(), ArgLVal),
  530. FD->getType(), AlignmentSource::Decl);
  531. }
  532. llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
  533. const VariableArrayType *VAT = FD->getCapturedVLAType();
  534. VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
  535. } else if (I->capturesVariable()) {
  536. const VarDecl *Var = I->getCapturedVar();
  537. QualType VarTy = Var->getType();
  538. Address ArgAddr = ArgLVal.getAddress(CGF);
  539. if (ArgLVal.getType()->isLValueReferenceType()) {
  540. ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
  541. } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
  542. assert(ArgLVal.getType()->isPointerType());
  543. ArgAddr = CGF.EmitLoadOfPointer(
  544. ArgAddr, ArgLVal.getType()->castAs<PointerType>());
  545. }
  546. if (!FO.RegisterCastedArgsOnly) {
  547. LocalAddrs.insert(
  548. {Args[Cnt], {Var, ArgAddr.withAlignment(Ctx.getDeclAlign(Var))}});
  549. }
  550. } else if (I->capturesVariableByCopy()) {
  551. assert(!FD->getType()->isAnyPointerType() &&
  552. "Not expecting a captured pointer.");
  553. const VarDecl *Var = I->getCapturedVar();
  554. LocalAddrs.insert({Args[Cnt],
  555. {Var, FO.UIntPtrCastRequired
  556. ? castValueFromUintptr(
  557. CGF, I->getLocation(), FD->getType(),
  558. Args[Cnt]->getName(), ArgLVal)
  559. : ArgLVal.getAddress(CGF)}});
  560. } else {
  561. // If 'this' is captured, load it into CXXThisValue.
  562. assert(I->capturesThis());
  563. CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
  564. LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
  565. }
  566. ++Cnt;
  567. ++I;
  568. }
  569. return F;
  570. }
  571. llvm::Function *
  572. CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
  573. SourceLocation Loc) {
  574. assert(
  575. CapturedStmtInfo &&
  576. "CapturedStmtInfo should be set when generating the captured function");
  577. const CapturedDecl *CD = S.getCapturedDecl();
  578. // Build the argument list.
  579. bool NeedWrapperFunction =
  580. getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
  581. FunctionArgList Args;
  582. llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
  583. llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
  584. SmallString<256> Buffer;
  585. llvm::raw_svector_ostream Out(Buffer);
  586. Out << CapturedStmtInfo->getHelperName();
  587. if (NeedWrapperFunction)
  588. Out << "_debug__";
  589. FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
  590. Out.str(), Loc);
  591. llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
  592. VLASizes, CXXThisValue, FO);
  593. CodeGenFunction::OMPPrivateScope LocalScope(*this);
  594. for (const auto &LocalAddrPair : LocalAddrs) {
  595. if (LocalAddrPair.second.first) {
  596. LocalScope.addPrivate(LocalAddrPair.second.first,
  597. LocalAddrPair.second.second);
  598. }
  599. }
  600. (void)LocalScope.Privatize();
  601. for (const auto &VLASizePair : VLASizes)
  602. VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
  603. PGO.assignRegionCounters(GlobalDecl(CD), F);
  604. CapturedStmtInfo->EmitBody(*this, CD->getBody());
  605. (void)LocalScope.ForceCleanup();
  606. FinishFunction(CD->getBodyRBrace());
  607. if (!NeedWrapperFunction)
  608. return F;
  609. FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
  610. /*RegisterCastedArgsOnly=*/true,
  611. CapturedStmtInfo->getHelperName(), Loc);
  612. CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
  613. WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
  614. Args.clear();
  615. LocalAddrs.clear();
  616. VLASizes.clear();
  617. llvm::Function *WrapperF =
  618. emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
  619. WrapperCGF.CXXThisValue, WrapperFO);
  620. llvm::SmallVector<llvm::Value *, 4> CallArgs;
  621. auto *PI = F->arg_begin();
  622. for (const auto *Arg : Args) {
  623. llvm::Value *CallArg;
  624. auto I = LocalAddrs.find(Arg);
  625. if (I != LocalAddrs.end()) {
  626. LValue LV = WrapperCGF.MakeAddrLValue(
  627. I->second.second,
  628. I->second.first ? I->second.first->getType() : Arg->getType(),
  629. AlignmentSource::Decl);
  630. if (LV.getType()->isAnyComplexType())
  631. LV.setAddress(WrapperCGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  632. LV.getAddress(WrapperCGF),
  633. PI->getType()->getPointerTo(
  634. LV.getAddress(WrapperCGF).getAddressSpace()),
  635. PI->getType()));
  636. CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
  637. } else {
  638. auto EI = VLASizes.find(Arg);
  639. if (EI != VLASizes.end()) {
  640. CallArg = EI->second.second;
  641. } else {
  642. LValue LV =
  643. WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
  644. Arg->getType(), AlignmentSource::Decl);
  645. CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
  646. }
  647. }
  648. CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
  649. ++PI;
  650. }
  651. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
  652. WrapperCGF.FinishFunction();
  653. return WrapperF;
  654. }
  655. //===----------------------------------------------------------------------===//
  656. // OpenMP Directive Emission
  657. //===----------------------------------------------------------------------===//
  658. void CodeGenFunction::EmitOMPAggregateAssign(
  659. Address DestAddr, Address SrcAddr, QualType OriginalType,
  660. const llvm::function_ref<void(Address, Address)> CopyGen) {
  661. // Perform element-by-element initialization.
  662. QualType ElementTy;
  663. // Drill down to the base element type on both arrays.
  664. const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
  665. llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
  666. SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  667. llvm::Value *SrcBegin = SrcAddr.getPointer();
  668. llvm::Value *DestBegin = DestAddr.getPointer();
  669. // Cast from pointer to array type to pointer to single element.
  670. llvm::Value *DestEnd = Builder.CreateInBoundsGEP(DestAddr.getElementType(),
  671. DestBegin, NumElements);
  672. // The basic structure here is a while-do loop.
  673. llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
  674. llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
  675. llvm::Value *IsEmpty =
  676. Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
  677. Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  678. // Enter the loop body, making that address the current address.
  679. llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
  680. EmitBlock(BodyBB);
  681. CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
  682. llvm::PHINode *SrcElementPHI =
  683. Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  684. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  685. Address SrcElementCurrent =
  686. Address(SrcElementPHI, SrcAddr.getElementType(),
  687. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  688. llvm::PHINode *DestElementPHI = Builder.CreatePHI(
  689. DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  690. DestElementPHI->addIncoming(DestBegin, EntryBB);
  691. Address DestElementCurrent =
  692. Address(DestElementPHI, DestAddr.getElementType(),
  693. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  694. // Emit copy.
  695. CopyGen(DestElementCurrent, SrcElementCurrent);
  696. // Shift the address forward by one element.
  697. llvm::Value *DestElementNext =
  698. Builder.CreateConstGEP1_32(DestAddr.getElementType(), DestElementPHI,
  699. /*Idx0=*/1, "omp.arraycpy.dest.element");
  700. llvm::Value *SrcElementNext =
  701. Builder.CreateConstGEP1_32(SrcAddr.getElementType(), SrcElementPHI,
  702. /*Idx0=*/1, "omp.arraycpy.src.element");
  703. // Check whether we've reached the end.
  704. llvm::Value *Done =
  705. Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  706. Builder.CreateCondBr(Done, DoneBB, BodyBB);
  707. DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
  708. SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
  709. // Done.
  710. EmitBlock(DoneBB, /*IsFinished=*/true);
  711. }
  712. void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
  713. Address SrcAddr, const VarDecl *DestVD,
  714. const VarDecl *SrcVD, const Expr *Copy) {
  715. if (OriginalType->isArrayType()) {
  716. const auto *BO = dyn_cast<BinaryOperator>(Copy);
  717. if (BO && BO->getOpcode() == BO_Assign) {
  718. // Perform simple memcpy for simple copying.
  719. LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
  720. LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
  721. EmitAggregateAssign(Dest, Src, OriginalType);
  722. } else {
  723. // For arrays with complex element types perform element by element
  724. // copying.
  725. EmitOMPAggregateAssign(
  726. DestAddr, SrcAddr, OriginalType,
  727. [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
  728. // Working with the single array element, so have to remap
  729. // destination and source variables to corresponding array
  730. // elements.
  731. CodeGenFunction::OMPPrivateScope Remap(*this);
  732. Remap.addPrivate(DestVD, DestElement);
  733. Remap.addPrivate(SrcVD, SrcElement);
  734. (void)Remap.Privatize();
  735. EmitIgnoredExpr(Copy);
  736. });
  737. }
  738. } else {
  739. // Remap pseudo source variable to private copy.
  740. CodeGenFunction::OMPPrivateScope Remap(*this);
  741. Remap.addPrivate(SrcVD, SrcAddr);
  742. Remap.addPrivate(DestVD, DestAddr);
  743. (void)Remap.Privatize();
  744. // Emit copying of the whole variable.
  745. EmitIgnoredExpr(Copy);
  746. }
  747. }
  748. bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  749. OMPPrivateScope &PrivateScope) {
  750. if (!HaveInsertPoint())
  751. return false;
  752. bool DeviceConstTarget =
  753. getLangOpts().OpenMPIsDevice &&
  754. isOpenMPTargetExecutionDirective(D.getDirectiveKind());
  755. bool FirstprivateIsLastprivate = false;
  756. llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
  757. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  758. for (const auto *D : C->varlists())
  759. Lastprivates.try_emplace(
  760. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
  761. C->getKind());
  762. }
  763. llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
  764. llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  765. getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
  766. // Force emission of the firstprivate copy if the directive does not emit
  767. // outlined function, like omp for, omp simd, omp distribute etc.
  768. bool MustEmitFirstprivateCopy =
  769. CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
  770. for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
  771. const auto *IRef = C->varlist_begin();
  772. const auto *InitsRef = C->inits().begin();
  773. for (const Expr *IInit : C->private_copies()) {
  774. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  775. bool ThisFirstprivateIsLastprivate =
  776. Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
  777. const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
  778. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  779. if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
  780. !FD->getType()->isReferenceType() &&
  781. (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
  782. EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
  783. ++IRef;
  784. ++InitsRef;
  785. continue;
  786. }
  787. // Do not emit copy for firstprivate constant variables in target regions,
  788. // captured by reference.
  789. if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
  790. FD && FD->getType()->isReferenceType() &&
  791. (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
  792. EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
  793. ++IRef;
  794. ++InitsRef;
  795. continue;
  796. }
  797. FirstprivateIsLastprivate =
  798. FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
  799. if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
  800. const auto *VDInit =
  801. cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
  802. bool IsRegistered;
  803. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
  804. /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
  805. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  806. LValue OriginalLVal;
  807. if (!FD) {
  808. // Check if the firstprivate variable is just a constant value.
  809. ConstantEmission CE = tryEmitAsConstant(&DRE);
  810. if (CE && !CE.isReference()) {
  811. // Constant value, no need to create a copy.
  812. ++IRef;
  813. ++InitsRef;
  814. continue;
  815. }
  816. if (CE && CE.isReference()) {
  817. OriginalLVal = CE.getReferenceLValue(*this, &DRE);
  818. } else {
  819. assert(!CE && "Expected non-constant firstprivate.");
  820. OriginalLVal = EmitLValue(&DRE);
  821. }
  822. } else {
  823. OriginalLVal = EmitLValue(&DRE);
  824. }
  825. QualType Type = VD->getType();
  826. if (Type->isArrayType()) {
  827. // Emit VarDecl with copy init for arrays.
  828. // Get the address of the original variable captured in current
  829. // captured region.
  830. AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
  831. const Expr *Init = VD->getInit();
  832. if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
  833. // Perform simple memcpy.
  834. LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(), Type);
  835. EmitAggregateAssign(Dest, OriginalLVal, Type);
  836. } else {
  837. EmitOMPAggregateAssign(
  838. Emission.getAllocatedAddress(), OriginalLVal.getAddress(*this),
  839. Type,
  840. [this, VDInit, Init](Address DestElement, Address SrcElement) {
  841. // Clean up any temporaries needed by the
  842. // initialization.
  843. RunCleanupsScope InitScope(*this);
  844. // Emit initialization for single element.
  845. setAddrOfLocalVar(VDInit, SrcElement);
  846. EmitAnyExprToMem(Init, DestElement,
  847. Init->getType().getQualifiers(),
  848. /*IsInitializer*/ false);
  849. LocalDeclMap.erase(VDInit);
  850. });
  851. }
  852. EmitAutoVarCleanups(Emission);
  853. IsRegistered =
  854. PrivateScope.addPrivate(OrigVD, Emission.getAllocatedAddress());
  855. } else {
  856. Address OriginalAddr = OriginalLVal.getAddress(*this);
  857. // Emit private VarDecl with copy init.
  858. // Remap temp VDInit variable to the address of the original
  859. // variable (for proper handling of captured global variables).
  860. setAddrOfLocalVar(VDInit, OriginalAddr);
  861. EmitDecl(*VD);
  862. LocalDeclMap.erase(VDInit);
  863. Address VDAddr = GetAddrOfLocalVar(VD);
  864. if (ThisFirstprivateIsLastprivate &&
  865. Lastprivates[OrigVD->getCanonicalDecl()] ==
  866. OMPC_LASTPRIVATE_conditional) {
  867. // Create/init special variable for lastprivate conditionals.
  868. llvm::Value *V =
  869. EmitLoadOfScalar(MakeAddrLValue(VDAddr, (*IRef)->getType(),
  870. AlignmentSource::Decl),
  871. (*IRef)->getExprLoc());
  872. VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
  873. *this, OrigVD);
  874. EmitStoreOfScalar(V, MakeAddrLValue(VDAddr, (*IRef)->getType(),
  875. AlignmentSource::Decl));
  876. LocalDeclMap.erase(VD);
  877. setAddrOfLocalVar(VD, VDAddr);
  878. }
  879. IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
  880. }
  881. assert(IsRegistered &&
  882. "firstprivate var already registered as private");
  883. // Silence the warning about unused variable.
  884. (void)IsRegistered;
  885. }
  886. ++IRef;
  887. ++InitsRef;
  888. }
  889. }
  890. return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
  891. }
  892. void CodeGenFunction::EmitOMPPrivateClause(
  893. const OMPExecutableDirective &D,
  894. CodeGenFunction::OMPPrivateScope &PrivateScope) {
  895. if (!HaveInsertPoint())
  896. return;
  897. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  898. for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
  899. auto IRef = C->varlist_begin();
  900. for (const Expr *IInit : C->private_copies()) {
  901. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  902. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  903. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  904. EmitDecl(*VD);
  905. // Emit private VarDecl with copy init.
  906. bool IsRegistered =
  907. PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(VD));
  908. assert(IsRegistered && "private var already registered as private");
  909. // Silence the warning about unused variable.
  910. (void)IsRegistered;
  911. }
  912. ++IRef;
  913. }
  914. }
  915. }
  916. bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
  917. if (!HaveInsertPoint())
  918. return false;
  919. // threadprivate_var1 = master_threadprivate_var1;
  920. // operator=(threadprivate_var2, master_threadprivate_var2);
  921. // ...
  922. // __kmpc_barrier(&loc, global_tid);
  923. llvm::DenseSet<const VarDecl *> CopiedVars;
  924. llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
  925. for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
  926. auto IRef = C->varlist_begin();
  927. auto ISrcRef = C->source_exprs().begin();
  928. auto IDestRef = C->destination_exprs().begin();
  929. for (const Expr *AssignOp : C->assignment_ops()) {
  930. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  931. QualType Type = VD->getType();
  932. if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
  933. // Get the address of the master variable. If we are emitting code with
  934. // TLS support, the address is passed from the master as field in the
  935. // captured declaration.
  936. Address MasterAddr = Address::invalid();
  937. if (getLangOpts().OpenMPUseTLS &&
  938. getContext().getTargetInfo().isTLSSupported()) {
  939. assert(CapturedStmtInfo->lookup(VD) &&
  940. "Copyin threadprivates should have been captured!");
  941. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
  942. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  943. MasterAddr = EmitLValue(&DRE).getAddress(*this);
  944. LocalDeclMap.erase(VD);
  945. } else {
  946. MasterAddr =
  947. Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
  948. : CGM.GetAddrOfGlobal(VD),
  949. CGM.getTypes().ConvertTypeForMem(VD->getType()),
  950. getContext().getDeclAlign(VD));
  951. }
  952. // Get the address of the threadprivate variable.
  953. Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
  954. if (CopiedVars.size() == 1) {
  955. // At first check if current thread is a master thread. If it is, no
  956. // need to copy data.
  957. CopyBegin = createBasicBlock("copyin.not.master");
  958. CopyEnd = createBasicBlock("copyin.not.master.end");
  959. // TODO: Avoid ptrtoint conversion.
  960. auto *MasterAddrInt =
  961. Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy);
  962. auto *PrivateAddrInt =
  963. Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy);
  964. Builder.CreateCondBr(
  965. Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin,
  966. CopyEnd);
  967. EmitBlock(CopyBegin);
  968. }
  969. const auto *SrcVD =
  970. cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  971. const auto *DestVD =
  972. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  973. EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
  974. }
  975. ++IRef;
  976. ++ISrcRef;
  977. ++IDestRef;
  978. }
  979. }
  980. if (CopyEnd) {
  981. // Exit out of copying procedure for non-master thread.
  982. EmitBlock(CopyEnd, /*IsFinished=*/true);
  983. return true;
  984. }
  985. return false;
  986. }
  987. bool CodeGenFunction::EmitOMPLastprivateClauseInit(
  988. const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
  989. if (!HaveInsertPoint())
  990. return false;
  991. bool HasAtLeastOneLastprivate = false;
  992. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  993. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  994. const auto *LoopDirective = cast<OMPLoopDirective>(&D);
  995. for (const Expr *C : LoopDirective->counters()) {
  996. SIMDLCVs.insert(
  997. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  998. }
  999. }
  1000. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  1001. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  1002. HasAtLeastOneLastprivate = true;
  1003. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
  1004. !getLangOpts().OpenMPSimd)
  1005. break;
  1006. const auto *IRef = C->varlist_begin();
  1007. const auto *IDestRef = C->destination_exprs().begin();
  1008. for (const Expr *IInit : C->private_copies()) {
  1009. // Keep the address of the original variable for future update at the end
  1010. // of the loop.
  1011. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  1012. // Taskloops do not require additional initialization, it is done in
  1013. // runtime support library.
  1014. if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
  1015. const auto *DestVD =
  1016. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  1017. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
  1018. /*RefersToEnclosingVariableOrCapture=*/
  1019. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1020. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  1021. PrivateScope.addPrivate(DestVD, EmitLValue(&DRE).getAddress(*this));
  1022. // Check if the variable is also a firstprivate: in this case IInit is
  1023. // not generated. Initialization of this variable will happen in codegen
  1024. // for 'firstprivate' clause.
  1025. if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
  1026. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  1027. Address VDAddr = Address::invalid();
  1028. if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
  1029. VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
  1030. *this, OrigVD);
  1031. setAddrOfLocalVar(VD, VDAddr);
  1032. } else {
  1033. // Emit private VarDecl with copy init.
  1034. EmitDecl(*VD);
  1035. VDAddr = GetAddrOfLocalVar(VD);
  1036. }
  1037. bool IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr);
  1038. assert(IsRegistered &&
  1039. "lastprivate var already registered as private");
  1040. (void)IsRegistered;
  1041. }
  1042. }
  1043. ++IRef;
  1044. ++IDestRef;
  1045. }
  1046. }
  1047. return HasAtLeastOneLastprivate;
  1048. }
  1049. void CodeGenFunction::EmitOMPLastprivateClauseFinal(
  1050. const OMPExecutableDirective &D, bool NoFinals,
  1051. llvm::Value *IsLastIterCond) {
  1052. if (!HaveInsertPoint())
  1053. return;
  1054. // Emit following code:
  1055. // if (<IsLastIterCond>) {
  1056. // orig_var1 = private_orig_var1;
  1057. // ...
  1058. // orig_varn = private_orig_varn;
  1059. // }
  1060. llvm::BasicBlock *ThenBB = nullptr;
  1061. llvm::BasicBlock *DoneBB = nullptr;
  1062. if (IsLastIterCond) {
  1063. // Emit implicit barrier if at least one lastprivate conditional is found
  1064. // and this is not a simd mode.
  1065. if (!getLangOpts().OpenMPSimd &&
  1066. llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
  1067. [](const OMPLastprivateClause *C) {
  1068. return C->getKind() == OMPC_LASTPRIVATE_conditional;
  1069. })) {
  1070. CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
  1071. OMPD_unknown,
  1072. /*EmitChecks=*/false,
  1073. /*ForceSimpleCall=*/true);
  1074. }
  1075. ThenBB = createBasicBlock(".omp.lastprivate.then");
  1076. DoneBB = createBasicBlock(".omp.lastprivate.done");
  1077. Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
  1078. EmitBlock(ThenBB);
  1079. }
  1080. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  1081. llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
  1082. if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
  1083. auto IC = LoopDirective->counters().begin();
  1084. for (const Expr *F : LoopDirective->finals()) {
  1085. const auto *D =
  1086. cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
  1087. if (NoFinals)
  1088. AlreadyEmittedVars.insert(D);
  1089. else
  1090. LoopCountersAndUpdates[D] = F;
  1091. ++IC;
  1092. }
  1093. }
  1094. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  1095. auto IRef = C->varlist_begin();
  1096. auto ISrcRef = C->source_exprs().begin();
  1097. auto IDestRef = C->destination_exprs().begin();
  1098. for (const Expr *AssignOp : C->assignment_ops()) {
  1099. const auto *PrivateVD =
  1100. cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  1101. QualType Type = PrivateVD->getType();
  1102. const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
  1103. if (AlreadyEmittedVars.insert(CanonicalVD).second) {
  1104. // If lastprivate variable is a loop control variable for loop-based
  1105. // directive, update its value before copyin back to original
  1106. // variable.
  1107. if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
  1108. EmitIgnoredExpr(FinalExpr);
  1109. const auto *SrcVD =
  1110. cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  1111. const auto *DestVD =
  1112. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  1113. // Get the address of the private variable.
  1114. Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
  1115. if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
  1116. PrivateAddr = Address(
  1117. Builder.CreateLoad(PrivateAddr),
  1118. CGM.getTypes().ConvertTypeForMem(RefTy->getPointeeType()),
  1119. CGM.getNaturalTypeAlignment(RefTy->getPointeeType()));
  1120. // Store the last value to the private copy in the last iteration.
  1121. if (C->getKind() == OMPC_LASTPRIVATE_conditional)
  1122. CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
  1123. *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
  1124. (*IRef)->getExprLoc());
  1125. // Get the address of the original variable.
  1126. Address OriginalAddr = GetAddrOfLocalVar(DestVD);
  1127. EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
  1128. }
  1129. ++IRef;
  1130. ++ISrcRef;
  1131. ++IDestRef;
  1132. }
  1133. if (const Expr *PostUpdate = C->getPostUpdateExpr())
  1134. EmitIgnoredExpr(PostUpdate);
  1135. }
  1136. if (IsLastIterCond)
  1137. EmitBlock(DoneBB, /*IsFinished=*/true);
  1138. }
  1139. void CodeGenFunction::EmitOMPReductionClauseInit(
  1140. const OMPExecutableDirective &D,
  1141. CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) {
  1142. if (!HaveInsertPoint())
  1143. return;
  1144. SmallVector<const Expr *, 4> Shareds;
  1145. SmallVector<const Expr *, 4> Privates;
  1146. SmallVector<const Expr *, 4> ReductionOps;
  1147. SmallVector<const Expr *, 4> LHSs;
  1148. SmallVector<const Expr *, 4> RHSs;
  1149. OMPTaskDataTy Data;
  1150. SmallVector<const Expr *, 4> TaskLHSs;
  1151. SmallVector<const Expr *, 4> TaskRHSs;
  1152. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1153. if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan))
  1154. continue;
  1155. Shareds.append(C->varlist_begin(), C->varlist_end());
  1156. Privates.append(C->privates().begin(), C->privates().end());
  1157. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  1158. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  1159. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  1160. if (C->getModifier() == OMPC_REDUCTION_task) {
  1161. Data.ReductionVars.append(C->privates().begin(), C->privates().end());
  1162. Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
  1163. Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
  1164. Data.ReductionOps.append(C->reduction_ops().begin(),
  1165. C->reduction_ops().end());
  1166. TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  1167. TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  1168. }
  1169. }
  1170. ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
  1171. unsigned Count = 0;
  1172. auto *ILHS = LHSs.begin();
  1173. auto *IRHS = RHSs.begin();
  1174. auto *IPriv = Privates.begin();
  1175. for (const Expr *IRef : Shareds) {
  1176. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
  1177. // Emit private VarDecl with reduction init.
  1178. RedCG.emitSharedOrigLValue(*this, Count);
  1179. RedCG.emitAggregateType(*this, Count);
  1180. AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
  1181. RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
  1182. RedCG.getSharedLValue(Count).getAddress(*this),
  1183. [&Emission](CodeGenFunction &CGF) {
  1184. CGF.EmitAutoVarInit(Emission);
  1185. return true;
  1186. });
  1187. EmitAutoVarCleanups(Emission);
  1188. Address BaseAddr = RedCG.adjustPrivateAddress(
  1189. *this, Count, Emission.getAllocatedAddress());
  1190. bool IsRegistered =
  1191. PrivateScope.addPrivate(RedCG.getBaseDecl(Count), BaseAddr);
  1192. assert(IsRegistered && "private var already registered as private");
  1193. // Silence the warning about unused variable.
  1194. (void)IsRegistered;
  1195. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  1196. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  1197. QualType Type = PrivateVD->getType();
  1198. bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
  1199. if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
  1200. // Store the address of the original variable associated with the LHS
  1201. // implicit variable.
  1202. PrivateScope.addPrivate(LHSVD,
  1203. RedCG.getSharedLValue(Count).getAddress(*this));
  1204. PrivateScope.addPrivate(RHSVD, GetAddrOfLocalVar(PrivateVD));
  1205. } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
  1206. isa<ArraySubscriptExpr>(IRef)) {
  1207. // Store the address of the original variable associated with the LHS
  1208. // implicit variable.
  1209. PrivateScope.addPrivate(LHSVD,
  1210. RedCG.getSharedLValue(Count).getAddress(*this));
  1211. PrivateScope.addPrivate(RHSVD, Builder.CreateElementBitCast(
  1212. GetAddrOfLocalVar(PrivateVD),
  1213. ConvertTypeForMem(RHSVD->getType()),
  1214. "rhs.begin"));
  1215. } else {
  1216. QualType Type = PrivateVD->getType();
  1217. bool IsArray = getContext().getAsArrayType(Type) != nullptr;
  1218. Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
  1219. // Store the address of the original variable associated with the LHS
  1220. // implicit variable.
  1221. if (IsArray) {
  1222. OriginalAddr = Builder.CreateElementBitCast(
  1223. OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
  1224. }
  1225. PrivateScope.addPrivate(LHSVD, OriginalAddr);
  1226. PrivateScope.addPrivate(
  1227. RHSVD, IsArray ? Builder.CreateElementBitCast(
  1228. GetAddrOfLocalVar(PrivateVD),
  1229. ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
  1230. : GetAddrOfLocalVar(PrivateVD));
  1231. }
  1232. ++ILHS;
  1233. ++IRHS;
  1234. ++IPriv;
  1235. ++Count;
  1236. }
  1237. if (!Data.ReductionVars.empty()) {
  1238. Data.IsReductionWithTaskMod = true;
  1239. Data.IsWorksharingReduction =
  1240. isOpenMPWorksharingDirective(D.getDirectiveKind());
  1241. llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit(
  1242. *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data);
  1243. const Expr *TaskRedRef = nullptr;
  1244. switch (D.getDirectiveKind()) {
  1245. case OMPD_parallel:
  1246. TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr();
  1247. break;
  1248. case OMPD_for:
  1249. TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr();
  1250. break;
  1251. case OMPD_sections:
  1252. TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr();
  1253. break;
  1254. case OMPD_parallel_for:
  1255. TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr();
  1256. break;
  1257. case OMPD_parallel_master:
  1258. TaskRedRef =
  1259. cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr();
  1260. break;
  1261. case OMPD_parallel_sections:
  1262. TaskRedRef =
  1263. cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr();
  1264. break;
  1265. case OMPD_target_parallel:
  1266. TaskRedRef =
  1267. cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr();
  1268. break;
  1269. case OMPD_target_parallel_for:
  1270. TaskRedRef =
  1271. cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr();
  1272. break;
  1273. case OMPD_distribute_parallel_for:
  1274. TaskRedRef =
  1275. cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr();
  1276. break;
  1277. case OMPD_teams_distribute_parallel_for:
  1278. TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D)
  1279. .getTaskReductionRefExpr();
  1280. break;
  1281. case OMPD_target_teams_distribute_parallel_for:
  1282. TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D)
  1283. .getTaskReductionRefExpr();
  1284. break;
  1285. case OMPD_simd:
  1286. case OMPD_for_simd:
  1287. case OMPD_section:
  1288. case OMPD_single:
  1289. case OMPD_master:
  1290. case OMPD_critical:
  1291. case OMPD_parallel_for_simd:
  1292. case OMPD_task:
  1293. case OMPD_taskyield:
  1294. case OMPD_error:
  1295. case OMPD_barrier:
  1296. case OMPD_taskwait:
  1297. case OMPD_taskgroup:
  1298. case OMPD_flush:
  1299. case OMPD_depobj:
  1300. case OMPD_scan:
  1301. case OMPD_ordered:
  1302. case OMPD_atomic:
  1303. case OMPD_teams:
  1304. case OMPD_target:
  1305. case OMPD_cancellation_point:
  1306. case OMPD_cancel:
  1307. case OMPD_target_data:
  1308. case OMPD_target_enter_data:
  1309. case OMPD_target_exit_data:
  1310. case OMPD_taskloop:
  1311. case OMPD_taskloop_simd:
  1312. case OMPD_master_taskloop:
  1313. case OMPD_master_taskloop_simd:
  1314. case OMPD_parallel_master_taskloop:
  1315. case OMPD_parallel_master_taskloop_simd:
  1316. case OMPD_distribute:
  1317. case OMPD_target_update:
  1318. case OMPD_distribute_parallel_for_simd:
  1319. case OMPD_distribute_simd:
  1320. case OMPD_target_parallel_for_simd:
  1321. case OMPD_target_simd:
  1322. case OMPD_teams_distribute:
  1323. case OMPD_teams_distribute_simd:
  1324. case OMPD_teams_distribute_parallel_for_simd:
  1325. case OMPD_target_teams:
  1326. case OMPD_target_teams_distribute:
  1327. case OMPD_target_teams_distribute_parallel_for_simd:
  1328. case OMPD_target_teams_distribute_simd:
  1329. case OMPD_declare_target:
  1330. case OMPD_end_declare_target:
  1331. case OMPD_threadprivate:
  1332. case OMPD_allocate:
  1333. case OMPD_declare_reduction:
  1334. case OMPD_declare_mapper:
  1335. case OMPD_declare_simd:
  1336. case OMPD_requires:
  1337. case OMPD_declare_variant:
  1338. case OMPD_begin_declare_variant:
  1339. case OMPD_end_declare_variant:
  1340. case OMPD_unknown:
  1341. default:
  1342. llvm_unreachable("Enexpected directive with task reductions.");
  1343. }
  1344. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl());
  1345. EmitVarDecl(*VD);
  1346. EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD),
  1347. /*Volatile=*/false, TaskRedRef->getType());
  1348. }
  1349. }
  1350. void CodeGenFunction::EmitOMPReductionClauseFinal(
  1351. const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
  1352. if (!HaveInsertPoint())
  1353. return;
  1354. llvm::SmallVector<const Expr *, 8> Privates;
  1355. llvm::SmallVector<const Expr *, 8> LHSExprs;
  1356. llvm::SmallVector<const Expr *, 8> RHSExprs;
  1357. llvm::SmallVector<const Expr *, 8> ReductionOps;
  1358. bool HasAtLeastOneReduction = false;
  1359. bool IsReductionWithTaskMod = false;
  1360. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1361. // Do not emit for inscan reductions.
  1362. if (C->getModifier() == OMPC_REDUCTION_inscan)
  1363. continue;
  1364. HasAtLeastOneReduction = true;
  1365. Privates.append(C->privates().begin(), C->privates().end());
  1366. LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  1367. RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  1368. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  1369. IsReductionWithTaskMod =
  1370. IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task;
  1371. }
  1372. if (HasAtLeastOneReduction) {
  1373. if (IsReductionWithTaskMod) {
  1374. CGM.getOpenMPRuntime().emitTaskReductionFini(
  1375. *this, D.getBeginLoc(),
  1376. isOpenMPWorksharingDirective(D.getDirectiveKind()));
  1377. }
  1378. bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
  1379. isOpenMPParallelDirective(D.getDirectiveKind()) ||
  1380. ReductionKind == OMPD_simd;
  1381. bool SimpleReduction = ReductionKind == OMPD_simd;
  1382. // Emit nowait reduction if nowait clause is present or directive is a
  1383. // parallel directive (it always has implicit barrier).
  1384. CGM.getOpenMPRuntime().emitReduction(
  1385. *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
  1386. {WithNowait, SimpleReduction, ReductionKind});
  1387. }
  1388. }
  1389. static void emitPostUpdateForReductionClause(
  1390. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  1391. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  1392. if (!CGF.HaveInsertPoint())
  1393. return;
  1394. llvm::BasicBlock *DoneBB = nullptr;
  1395. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1396. if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
  1397. if (!DoneBB) {
  1398. if (llvm::Value *Cond = CondGen(CGF)) {
  1399. // If the first post-update expression is found, emit conditional
  1400. // block if it was requested.
  1401. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
  1402. DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
  1403. CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1404. CGF.EmitBlock(ThenBB);
  1405. }
  1406. }
  1407. CGF.EmitIgnoredExpr(PostUpdate);
  1408. }
  1409. }
  1410. if (DoneBB)
  1411. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  1412. }
  1413. namespace {
  1414. /// Codegen lambda for appending distribute lower and upper bounds to outlined
  1415. /// parallel function. This is necessary for combined constructs such as
  1416. /// 'distribute parallel for'
  1417. typedef llvm::function_ref<void(CodeGenFunction &,
  1418. const OMPExecutableDirective &,
  1419. llvm::SmallVectorImpl<llvm::Value *> &)>
  1420. CodeGenBoundParametersTy;
  1421. } // anonymous namespace
  1422. static void
  1423. checkForLastprivateConditionalUpdate(CodeGenFunction &CGF,
  1424. const OMPExecutableDirective &S) {
  1425. if (CGF.getLangOpts().OpenMP < 50)
  1426. return;
  1427. llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
  1428. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  1429. for (const Expr *Ref : C->varlists()) {
  1430. if (!Ref->getType()->isScalarType())
  1431. continue;
  1432. const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
  1433. if (!DRE)
  1434. continue;
  1435. PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
  1436. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
  1437. }
  1438. }
  1439. for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
  1440. for (const Expr *Ref : C->varlists()) {
  1441. if (!Ref->getType()->isScalarType())
  1442. continue;
  1443. const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
  1444. if (!DRE)
  1445. continue;
  1446. PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
  1447. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
  1448. }
  1449. }
  1450. for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
  1451. for (const Expr *Ref : C->varlists()) {
  1452. if (!Ref->getType()->isScalarType())
  1453. continue;
  1454. const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
  1455. if (!DRE)
  1456. continue;
  1457. PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
  1458. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
  1459. }
  1460. }
  1461. // Privates should ne analyzed since they are not captured at all.
  1462. // Task reductions may be skipped - tasks are ignored.
  1463. // Firstprivates do not return value but may be passed by reference - no need
  1464. // to check for updated lastprivate conditional.
  1465. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  1466. for (const Expr *Ref : C->varlists()) {
  1467. if (!Ref->getType()->isScalarType())
  1468. continue;
  1469. const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
  1470. if (!DRE)
  1471. continue;
  1472. PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
  1473. }
  1474. }
  1475. CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional(
  1476. CGF, S, PrivateDecls);
  1477. }
  1478. static void emitCommonOMPParallelDirective(
  1479. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  1480. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1481. const CodeGenBoundParametersTy &CodeGenBoundParameters) {
  1482. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  1483. llvm::Value *NumThreads = nullptr;
  1484. llvm::Function *OutlinedFn =
  1485. CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
  1486. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  1487. if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
  1488. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  1489. NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
  1490. /*IgnoreResultAssign=*/true);
  1491. CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
  1492. CGF, NumThreads, NumThreadsClause->getBeginLoc());
  1493. }
  1494. if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
  1495. CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
  1496. CGF.CGM.getOpenMPRuntime().emitProcBindClause(
  1497. CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
  1498. }
  1499. const Expr *IfCond = nullptr;
  1500. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  1501. if (C->getNameModifier() == OMPD_unknown ||
  1502. C->getNameModifier() == OMPD_parallel) {
  1503. IfCond = C->getCondition();
  1504. break;
  1505. }
  1506. }
  1507. OMPParallelScope Scope(CGF, S);
  1508. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  1509. // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
  1510. // lower and upper bounds with the pragma 'for' chunking mechanism.
  1511. // The following lambda takes care of appending the lower and upper bound
  1512. // parameters when necessary
  1513. CodeGenBoundParameters(CGF, S, CapturedVars);
  1514. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  1515. CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
  1516. CapturedVars, IfCond, NumThreads);
  1517. }
  1518. static bool isAllocatableDecl(const VarDecl *VD) {
  1519. const VarDecl *CVD = VD->getCanonicalDecl();
  1520. if (!CVD->hasAttr<OMPAllocateDeclAttr>())
  1521. return false;
  1522. const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
  1523. // Use the default allocation.
  1524. return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc ||
  1525. AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) &&
  1526. !AA->getAllocator());
  1527. }
  1528. static void emitEmptyBoundParameters(CodeGenFunction &,
  1529. const OMPExecutableDirective &,
  1530. llvm::SmallVectorImpl<llvm::Value *> &) {}
  1531. static void emitOMPCopyinClause(CodeGenFunction &CGF,
  1532. const OMPExecutableDirective &S) {
  1533. bool Copyins = CGF.EmitOMPCopyinClause(S);
  1534. if (Copyins) {
  1535. // Emit implicit barrier to synchronize threads and avoid data races on
  1536. // propagation master's thread values of threadprivate variables to local
  1537. // instances of that variables of all other implicit threads.
  1538. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  1539. CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  1540. /*ForceSimpleCall=*/true);
  1541. }
  1542. }
  1543. Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
  1544. CodeGenFunction &CGF, const VarDecl *VD) {
  1545. CodeGenModule &CGM = CGF.CGM;
  1546. auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  1547. if (!VD)
  1548. return Address::invalid();
  1549. const VarDecl *CVD = VD->getCanonicalDecl();
  1550. if (!isAllocatableDecl(CVD))
  1551. return Address::invalid();
  1552. llvm::Value *Size;
  1553. CharUnits Align = CGM.getContext().getDeclAlign(CVD);
  1554. if (CVD->getType()->isVariablyModifiedType()) {
  1555. Size = CGF.getTypeSize(CVD->getType());
  1556. // Align the size: ((size + align - 1) / align) * align
  1557. Size = CGF.Builder.CreateNUWAdd(
  1558. Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
  1559. Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
  1560. Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
  1561. } else {
  1562. CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
  1563. Size = CGM.getSize(Sz.alignTo(Align));
  1564. }
  1565. const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
  1566. assert(AA->getAllocator() &&
  1567. "Expected allocator expression for non-default allocator.");
  1568. llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
  1569. // According to the standard, the original allocator type is a enum (integer).
  1570. // Convert to pointer type, if required.
  1571. if (Allocator->getType()->isIntegerTy())
  1572. Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
  1573. else if (Allocator->getType()->isPointerTy())
  1574. Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
  1575. CGM.VoidPtrTy);
  1576. llvm::Value *Addr = OMPBuilder.createOMPAlloc(
  1577. CGF.Builder, Size, Allocator,
  1578. getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", "."));
  1579. llvm::CallInst *FreeCI =
  1580. OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator);
  1581. CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI);
  1582. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1583. Addr,
  1584. CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
  1585. getNameWithSeparators({CVD->getName(), ".addr"}, ".", "."));
  1586. return Address(Addr, CGF.ConvertTypeForMem(CVD->getType()), Align);
  1587. }
  1588. Address CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
  1589. CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr,
  1590. SourceLocation Loc) {
  1591. CodeGenModule &CGM = CGF.CGM;
  1592. if (CGM.getLangOpts().OpenMPUseTLS &&
  1593. CGM.getContext().getTargetInfo().isTLSSupported())
  1594. return VDAddr;
  1595. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  1596. llvm::Type *VarTy = VDAddr.getElementType();
  1597. llvm::Value *Data =
  1598. CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy);
  1599. llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy));
  1600. std::string Suffix = getNameWithSeparators({"cache", ""});
  1601. llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix);
  1602. llvm::CallInst *ThreadPrivateCacheCall =
  1603. OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName);
  1604. return Address(ThreadPrivateCacheCall, CGM.Int8Ty, VDAddr.getAlignment());
  1605. }
  1606. std::string CodeGenFunction::OMPBuilderCBHelpers::getNameWithSeparators(
  1607. ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) {
  1608. SmallString<128> Buffer;
  1609. llvm::raw_svector_ostream OS(Buffer);
  1610. StringRef Sep = FirstSeparator;
  1611. for (StringRef Part : Parts) {
  1612. OS << Sep << Part;
  1613. Sep = Separator;
  1614. }
  1615. return OS.str().str();
  1616. }
  1617. void CodeGenFunction::OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  1618. CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
  1619. InsertPointTy CodeGenIP, Twine RegionName) {
  1620. CGBuilderTy &Builder = CGF.Builder;
  1621. Builder.restoreIP(CodeGenIP);
  1622. llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
  1623. "." + RegionName + ".after");
  1624. {
  1625. OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
  1626. CGF.EmitStmt(RegionBodyStmt);
  1627. }
  1628. if (Builder.saveIP().isSet())
  1629. Builder.CreateBr(FiniBB);
  1630. }
  1631. void CodeGenFunction::OMPBuilderCBHelpers::EmitOMPOutlinedRegionBody(
  1632. CodeGenFunction &CGF, const Stmt *RegionBodyStmt, InsertPointTy AllocaIP,
  1633. InsertPointTy CodeGenIP, Twine RegionName) {
  1634. CGBuilderTy &Builder = CGF.Builder;
  1635. Builder.restoreIP(CodeGenIP);
  1636. llvm::BasicBlock *FiniBB = splitBBWithSuffix(Builder, /*CreateBranch=*/false,
  1637. "." + RegionName + ".after");
  1638. {
  1639. OMPBuilderCBHelpers::OutlinedRegionBodyRAII IRB(CGF, AllocaIP, *FiniBB);
  1640. CGF.EmitStmt(RegionBodyStmt);
  1641. }
  1642. if (Builder.saveIP().isSet())
  1643. Builder.CreateBr(FiniBB);
  1644. }
  1645. void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
  1646. if (CGM.getLangOpts().OpenMPIRBuilder) {
  1647. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  1648. // Check if we have any if clause associated with the directive.
  1649. llvm::Value *IfCond = nullptr;
  1650. if (const auto *C = S.getSingleClause<OMPIfClause>())
  1651. IfCond = EmitScalarExpr(C->getCondition(),
  1652. /*IgnoreResultAssign=*/true);
  1653. llvm::Value *NumThreads = nullptr;
  1654. if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
  1655. NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
  1656. /*IgnoreResultAssign=*/true);
  1657. ProcBindKind ProcBind = OMP_PROC_BIND_default;
  1658. if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
  1659. ProcBind = ProcBindClause->getProcBindKind();
  1660. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  1661. // The cleanup callback that finalizes all variabels at the given location,
  1662. // thus calls destructors etc.
  1663. auto FiniCB = [this](InsertPointTy IP) {
  1664. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  1665. };
  1666. // Privatization callback that performs appropriate action for
  1667. // shared/private/firstprivate/lastprivate/copyin/... variables.
  1668. //
  1669. // TODO: This defaults to shared right now.
  1670. auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
  1671. llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
  1672. // The next line is appropriate only for variables (Val) with the
  1673. // data-sharing attribute "shared".
  1674. ReplVal = &Val;
  1675. return CodeGenIP;
  1676. };
  1677. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  1678. const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
  1679. auto BodyGenCB = [&, this](InsertPointTy AllocaIP,
  1680. InsertPointTy CodeGenIP) {
  1681. OMPBuilderCBHelpers::EmitOMPOutlinedRegionBody(
  1682. *this, ParallelRegionBodyStmt, AllocaIP, CodeGenIP, "parallel");
  1683. };
  1684. CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
  1685. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
  1686. llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
  1687. AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
  1688. Builder.restoreIP(
  1689. OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB,
  1690. IfCond, NumThreads, ProcBind, S.hasCancel()));
  1691. return;
  1692. }
  1693. // Emit parallel region as a standalone region.
  1694. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  1695. Action.Enter(CGF);
  1696. OMPPrivateScope PrivateScope(CGF);
  1697. emitOMPCopyinClause(CGF, S);
  1698. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  1699. CGF.EmitOMPPrivateClause(S, PrivateScope);
  1700. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  1701. (void)PrivateScope.Privatize();
  1702. CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
  1703. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  1704. };
  1705. {
  1706. auto LPCRegion =
  1707. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  1708. emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
  1709. emitEmptyBoundParameters);
  1710. emitPostUpdateForReductionClause(*this, S,
  1711. [](CodeGenFunction &) { return nullptr; });
  1712. }
  1713. // Check for outer lastprivate conditional update.
  1714. checkForLastprivateConditionalUpdate(*this, S);
  1715. }
  1716. void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) {
  1717. EmitStmt(S.getIfStmt());
  1718. }
  1719. namespace {
  1720. /// RAII to handle scopes for loop transformation directives.
  1721. class OMPTransformDirectiveScopeRAII {
  1722. OMPLoopScope *Scope = nullptr;
  1723. CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr;
  1724. CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr;
  1725. public:
  1726. OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) {
  1727. if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) {
  1728. Scope = new OMPLoopScope(CGF, *Dir);
  1729. CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP);
  1730. CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI);
  1731. }
  1732. }
  1733. ~OMPTransformDirectiveScopeRAII() {
  1734. if (!Scope)
  1735. return;
  1736. delete CapInfoRAII;
  1737. delete CGSI;
  1738. delete Scope;
  1739. }
  1740. };
  1741. } // namespace
  1742. static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
  1743. int MaxLevel, int Level = 0) {
  1744. assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
  1745. const Stmt *SimplifiedS = S->IgnoreContainers();
  1746. if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
  1747. PrettyStackTraceLoc CrashInfo(
  1748. CGF.getContext().getSourceManager(), CS->getLBracLoc(),
  1749. "LLVM IR generation of compound statement ('{}')");
  1750. // Keep track of the current cleanup stack depth, including debug scopes.
  1751. CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
  1752. for (const Stmt *CurStmt : CS->body())
  1753. emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
  1754. return;
  1755. }
  1756. if (SimplifiedS == NextLoop) {
  1757. if (auto *Dir = dyn_cast<OMPLoopTransformationDirective>(SimplifiedS))
  1758. SimplifiedS = Dir->getTransformedStmt();
  1759. if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS))
  1760. SimplifiedS = CanonLoop->getLoopStmt();
  1761. if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
  1762. S = For->getBody();
  1763. } else {
  1764. assert(isa<CXXForRangeStmt>(SimplifiedS) &&
  1765. "Expected canonical for loop or range-based for loop.");
  1766. const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
  1767. CGF.EmitStmt(CXXFor->getLoopVarStmt());
  1768. S = CXXFor->getBody();
  1769. }
  1770. if (Level + 1 < MaxLevel) {
  1771. NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
  1772. S, /*TryImperfectlyNestedLoops=*/true);
  1773. emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
  1774. return;
  1775. }
  1776. }
  1777. CGF.EmitStmt(S);
  1778. }
  1779. void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
  1780. JumpDest LoopExit) {
  1781. RunCleanupsScope BodyScope(*this);
  1782. // Update counters values on current iteration.
  1783. for (const Expr *UE : D.updates())
  1784. EmitIgnoredExpr(UE);
  1785. // Update the linear variables.
  1786. // In distribute directives only loop counters may be marked as linear, no
  1787. // need to generate the code for them.
  1788. if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
  1789. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1790. for (const Expr *UE : C->updates())
  1791. EmitIgnoredExpr(UE);
  1792. }
  1793. }
  1794. // On a continue in the body, jump to the end.
  1795. JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
  1796. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1797. for (const Expr *E : D.finals_conditions()) {
  1798. if (!E)
  1799. continue;
  1800. // Check that loop counter in non-rectangular nest fits into the iteration
  1801. // space.
  1802. llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
  1803. EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
  1804. getProfileCount(D.getBody()));
  1805. EmitBlock(NextBB);
  1806. }
  1807. OMPPrivateScope InscanScope(*this);
  1808. EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true);
  1809. bool IsInscanRegion = InscanScope.Privatize();
  1810. if (IsInscanRegion) {
  1811. // Need to remember the block before and after scan directive
  1812. // to dispatch them correctly depending on the clause used in
  1813. // this directive, inclusive or exclusive. For inclusive scan the natural
  1814. // order of the blocks is used, for exclusive clause the blocks must be
  1815. // executed in reverse order.
  1816. OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb");
  1817. OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb");
  1818. // No need to allocate inscan exit block, in simd mode it is selected in the
  1819. // codegen for the scan directive.
  1820. if (D.getDirectiveKind() != OMPD_simd && !getLangOpts().OpenMPSimd)
  1821. OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb");
  1822. OMPScanDispatch = createBasicBlock("omp.inscan.dispatch");
  1823. EmitBranch(OMPScanDispatch);
  1824. EmitBlock(OMPBeforeScanBlock);
  1825. }
  1826. // Emit loop variables for C++ range loops.
  1827. const Stmt *Body =
  1828. D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
  1829. // Emit loop body.
  1830. emitBody(*this, Body,
  1831. OMPLoopBasedDirective::tryToFindNextInnerLoop(
  1832. Body, /*TryImperfectlyNestedLoops=*/true),
  1833. D.getLoopsNumber());
  1834. // Jump to the dispatcher at the end of the loop body.
  1835. if (IsInscanRegion)
  1836. EmitBranch(OMPScanExitBlock);
  1837. // The end (updates/cleanups).
  1838. EmitBlock(Continue.getBlock());
  1839. BreakContinueStack.pop_back();
  1840. }
  1841. using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>;
  1842. /// Emit a captured statement and return the function as well as its captured
  1843. /// closure context.
  1844. static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF,
  1845. const CapturedStmt *S) {
  1846. LValue CapStruct = ParentCGF.InitCapturedStruct(*S);
  1847. CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true);
  1848. std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI =
  1849. std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S);
  1850. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get());
  1851. llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S);
  1852. return {F, CapStruct.getPointer(ParentCGF)};
  1853. }
  1854. /// Emit a call to a previously captured closure.
  1855. static llvm::CallInst *
  1856. emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap,
  1857. llvm::ArrayRef<llvm::Value *> Args) {
  1858. // Append the closure context to the argument.
  1859. SmallVector<llvm::Value *> EffectiveArgs;
  1860. EffectiveArgs.reserve(Args.size() + 1);
  1861. llvm::append_range(EffectiveArgs, Args);
  1862. EffectiveArgs.push_back(Cap.second);
  1863. return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs);
  1864. }
  1865. llvm::CanonicalLoopInfo *
  1866. CodeGenFunction::EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth) {
  1867. assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented");
  1868. // The caller is processing the loop-associated directive processing the \p
  1869. // Depth loops nested in \p S. Put the previous pending loop-associated
  1870. // directive to the stack. If the current loop-associated directive is a loop
  1871. // transformation directive, it will push its generated loops onto the stack
  1872. // such that together with the loops left here they form the combined loop
  1873. // nest for the parent loop-associated directive.
  1874. int ParentExpectedOMPLoopDepth = ExpectedOMPLoopDepth;
  1875. ExpectedOMPLoopDepth = Depth;
  1876. EmitStmt(S);
  1877. assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops");
  1878. // The last added loop is the outermost one.
  1879. llvm::CanonicalLoopInfo *Result = OMPLoopNestStack.back();
  1880. // Pop the \p Depth loops requested by the call from that stack and restore
  1881. // the previous context.
  1882. OMPLoopNestStack.pop_back_n(Depth);
  1883. ExpectedOMPLoopDepth = ParentExpectedOMPLoopDepth;
  1884. return Result;
  1885. }
  1886. void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) {
  1887. const Stmt *SyntacticalLoop = S->getLoopStmt();
  1888. if (!getLangOpts().OpenMPIRBuilder) {
  1889. // Ignore if OpenMPIRBuilder is not enabled.
  1890. EmitStmt(SyntacticalLoop);
  1891. return;
  1892. }
  1893. LexicalScope ForScope(*this, S->getSourceRange());
  1894. // Emit init statements. The Distance/LoopVar funcs may reference variable
  1895. // declarations they contain.
  1896. const Stmt *BodyStmt;
  1897. if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) {
  1898. if (const Stmt *InitStmt = For->getInit())
  1899. EmitStmt(InitStmt);
  1900. BodyStmt = For->getBody();
  1901. } else if (const auto *RangeFor =
  1902. dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) {
  1903. if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt())
  1904. EmitStmt(RangeStmt);
  1905. if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt())
  1906. EmitStmt(BeginStmt);
  1907. if (const DeclStmt *EndStmt = RangeFor->getEndStmt())
  1908. EmitStmt(EndStmt);
  1909. if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt())
  1910. EmitStmt(LoopVarStmt);
  1911. BodyStmt = RangeFor->getBody();
  1912. } else
  1913. llvm_unreachable("Expected for-stmt or range-based for-stmt");
  1914. // Emit closure for later use. By-value captures will be captured here.
  1915. const CapturedStmt *DistanceFunc = S->getDistanceFunc();
  1916. EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc);
  1917. const CapturedStmt *LoopVarFunc = S->getLoopVarFunc();
  1918. EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc);
  1919. // Call the distance function to get the number of iterations of the loop to
  1920. // come.
  1921. QualType LogicalTy = DistanceFunc->getCapturedDecl()
  1922. ->getParam(0)
  1923. ->getType()
  1924. .getNonReferenceType();
  1925. Address CountAddr = CreateMemTemp(LogicalTy, ".count.addr");
  1926. emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()});
  1927. llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count");
  1928. // Emit the loop structure.
  1929. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  1930. auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP,
  1931. llvm::Value *IndVar) {
  1932. Builder.restoreIP(CodeGenIP);
  1933. // Emit the loop body: Convert the logical iteration number to the loop
  1934. // variable and emit the body.
  1935. const DeclRefExpr *LoopVarRef = S->getLoopVarRef();
  1936. LValue LCVal = EmitLValue(LoopVarRef);
  1937. Address LoopVarAddress = LCVal.getAddress(*this);
  1938. emitCapturedStmtCall(*this, LoopVarClosure,
  1939. {LoopVarAddress.getPointer(), IndVar});
  1940. RunCleanupsScope BodyScope(*this);
  1941. EmitStmt(BodyStmt);
  1942. };
  1943. llvm::CanonicalLoopInfo *CL =
  1944. OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal);
  1945. // Finish up the loop.
  1946. Builder.restoreIP(CL->getAfterIP());
  1947. ForScope.ForceCleanup();
  1948. // Remember the CanonicalLoopInfo for parent AST nodes consuming it.
  1949. OMPLoopNestStack.push_back(CL);
  1950. }
  1951. void CodeGenFunction::EmitOMPInnerLoop(
  1952. const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond,
  1953. const Expr *IncExpr,
  1954. const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
  1955. const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
  1956. auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
  1957. // Start the loop with a block that tests the condition.
  1958. auto CondBlock = createBasicBlock("omp.inner.for.cond");
  1959. EmitBlock(CondBlock);
  1960. const SourceRange R = S.getSourceRange();
  1961. // If attributes are attached, push to the basic block with them.
  1962. const auto &OMPED = cast<OMPExecutableDirective>(S);
  1963. const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt();
  1964. const Stmt *SS = ICS->getCapturedStmt();
  1965. const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS);
  1966. OMPLoopNestStack.clear();
  1967. if (AS)
  1968. LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(),
  1969. AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()),
  1970. SourceLocToDebugLoc(R.getEnd()));
  1971. else
  1972. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  1973. SourceLocToDebugLoc(R.getEnd()));
  1974. // If there are any cleanups between here and the loop-exit scope,
  1975. // create a block to stage a loop exit along.
  1976. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  1977. if (RequiresCleanup)
  1978. ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
  1979. llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
  1980. // Emit condition.
  1981. EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
  1982. if (ExitBlock != LoopExit.getBlock()) {
  1983. EmitBlock(ExitBlock);
  1984. EmitBranchThroughCleanup(LoopExit);
  1985. }
  1986. EmitBlock(LoopBody);
  1987. incrementProfileCounter(&S);
  1988. // Create a block for the increment.
  1989. JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
  1990. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1991. BodyGen(*this);
  1992. // Emit "IV = IV + 1" and a back-edge to the condition block.
  1993. EmitBlock(Continue.getBlock());
  1994. EmitIgnoredExpr(IncExpr);
  1995. PostIncGen(*this);
  1996. BreakContinueStack.pop_back();
  1997. EmitBranch(CondBlock);
  1998. LoopStack.pop();
  1999. // Emit the fall-through block.
  2000. EmitBlock(LoopExit.getBlock());
  2001. }
  2002. bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
  2003. if (!HaveInsertPoint())
  2004. return false;
  2005. // Emit inits for the linear variables.
  2006. bool HasLinears = false;
  2007. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  2008. for (const Expr *Init : C->inits()) {
  2009. HasLinears = true;
  2010. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
  2011. if (const auto *Ref =
  2012. dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
  2013. AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
  2014. const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
  2015. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
  2016. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  2017. VD->getInit()->getType(), VK_LValue,
  2018. VD->getInit()->getExprLoc());
  2019. EmitExprAsInit(
  2020. &DRE, VD,
  2021. MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
  2022. /*capturedByInit=*/false);
  2023. EmitAutoVarCleanups(Emission);
  2024. } else {
  2025. EmitVarDecl(*VD);
  2026. }
  2027. }
  2028. // Emit the linear steps for the linear clauses.
  2029. // If a step is not constant, it is pre-calculated before the loop.
  2030. if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
  2031. if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
  2032. EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
  2033. // Emit calculation of the linear step.
  2034. EmitIgnoredExpr(CS);
  2035. }
  2036. }
  2037. return HasLinears;
  2038. }
  2039. void CodeGenFunction::EmitOMPLinearClauseFinal(
  2040. const OMPLoopDirective &D,
  2041. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  2042. if (!HaveInsertPoint())
  2043. return;
  2044. llvm::BasicBlock *DoneBB = nullptr;
  2045. // Emit the final values of the linear variables.
  2046. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  2047. auto IC = C->varlist_begin();
  2048. for (const Expr *F : C->finals()) {
  2049. if (!DoneBB) {
  2050. if (llvm::Value *Cond = CondGen(*this)) {
  2051. // If the first post-update expression is found, emit conditional
  2052. // block if it was requested.
  2053. llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
  2054. DoneBB = createBasicBlock(".omp.linear.pu.done");
  2055. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  2056. EmitBlock(ThenBB);
  2057. }
  2058. }
  2059. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
  2060. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
  2061. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  2062. (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
  2063. Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
  2064. CodeGenFunction::OMPPrivateScope VarScope(*this);
  2065. VarScope.addPrivate(OrigVD, OrigAddr);
  2066. (void)VarScope.Privatize();
  2067. EmitIgnoredExpr(F);
  2068. ++IC;
  2069. }
  2070. if (const Expr *PostUpdate = C->getPostUpdateExpr())
  2071. EmitIgnoredExpr(PostUpdate);
  2072. }
  2073. if (DoneBB)
  2074. EmitBlock(DoneBB, /*IsFinished=*/true);
  2075. }
  2076. static void emitAlignedClause(CodeGenFunction &CGF,
  2077. const OMPExecutableDirective &D) {
  2078. if (!CGF.HaveInsertPoint())
  2079. return;
  2080. for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
  2081. llvm::APInt ClauseAlignment(64, 0);
  2082. if (const Expr *AlignmentExpr = Clause->getAlignment()) {
  2083. auto *AlignmentCI =
  2084. cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
  2085. ClauseAlignment = AlignmentCI->getValue();
  2086. }
  2087. for (const Expr *E : Clause->varlists()) {
  2088. llvm::APInt Alignment(ClauseAlignment);
  2089. if (Alignment == 0) {
  2090. // OpenMP [2.8.1, Description]
  2091. // If no optional parameter is specified, implementation-defined default
  2092. // alignments for SIMD instructions on the target platforms are assumed.
  2093. Alignment =
  2094. CGF.getContext()
  2095. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  2096. E->getType()->getPointeeType()))
  2097. .getQuantity();
  2098. }
  2099. assert((Alignment == 0 || Alignment.isPowerOf2()) &&
  2100. "alignment is not power of 2");
  2101. if (Alignment != 0) {
  2102. llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
  2103. CGF.emitAlignmentAssumption(
  2104. PtrValue, E, /*No second loc needed*/ SourceLocation(),
  2105. llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
  2106. }
  2107. }
  2108. }
  2109. }
  2110. void CodeGenFunction::EmitOMPPrivateLoopCounters(
  2111. const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
  2112. if (!HaveInsertPoint())
  2113. return;
  2114. auto I = S.private_counters().begin();
  2115. for (const Expr *E : S.counters()) {
  2116. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2117. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
  2118. // Emit var without initialization.
  2119. AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
  2120. EmitAutoVarCleanups(VarEmission);
  2121. LocalDeclMap.erase(PrivateVD);
  2122. (void)LoopScope.addPrivate(VD, VarEmission.getAllocatedAddress());
  2123. if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
  2124. VD->hasGlobalStorage()) {
  2125. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
  2126. LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
  2127. E->getType(), VK_LValue, E->getExprLoc());
  2128. (void)LoopScope.addPrivate(PrivateVD, EmitLValue(&DRE).getAddress(*this));
  2129. } else {
  2130. (void)LoopScope.addPrivate(PrivateVD, VarEmission.getAllocatedAddress());
  2131. }
  2132. ++I;
  2133. }
  2134. // Privatize extra loop counters used in loops for ordered(n) clauses.
  2135. for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
  2136. if (!C->getNumForLoops())
  2137. continue;
  2138. for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size();
  2139. I < E; ++I) {
  2140. const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
  2141. const auto *VD = cast<VarDecl>(DRE->getDecl());
  2142. // Override only those variables that can be captured to avoid re-emission
  2143. // of the variables declared within the loops.
  2144. if (DRE->refersToEnclosingVariableOrCapture()) {
  2145. (void)LoopScope.addPrivate(
  2146. VD, CreateMemTemp(DRE->getType(), VD->getName()));
  2147. }
  2148. }
  2149. }
  2150. }
  2151. static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
  2152. const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2153. llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
  2154. if (!CGF.HaveInsertPoint())
  2155. return;
  2156. {
  2157. CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
  2158. CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
  2159. (void)PreCondScope.Privatize();
  2160. // Get initial values of real counters.
  2161. for (const Expr *I : S.inits()) {
  2162. CGF.EmitIgnoredExpr(I);
  2163. }
  2164. }
  2165. // Create temp loop control variables with their init values to support
  2166. // non-rectangular loops.
  2167. CodeGenFunction::OMPMapVars PreCondVars;
  2168. for (const Expr *E : S.dependent_counters()) {
  2169. if (!E)
  2170. continue;
  2171. assert(!E->getType().getNonReferenceType()->isRecordType() &&
  2172. "dependent counter must not be an iterator.");
  2173. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2174. Address CounterAddr =
  2175. CGF.CreateMemTemp(VD->getType().getNonReferenceType());
  2176. (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
  2177. }
  2178. (void)PreCondVars.apply(CGF);
  2179. for (const Expr *E : S.dependent_inits()) {
  2180. if (!E)
  2181. continue;
  2182. CGF.EmitIgnoredExpr(E);
  2183. }
  2184. // Check that loop is executed at least one time.
  2185. CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
  2186. PreCondVars.restore(CGF);
  2187. }
  2188. void CodeGenFunction::EmitOMPLinearClause(
  2189. const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
  2190. if (!HaveInsertPoint())
  2191. return;
  2192. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  2193. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  2194. const auto *LoopDirective = cast<OMPLoopDirective>(&D);
  2195. for (const Expr *C : LoopDirective->counters()) {
  2196. SIMDLCVs.insert(
  2197. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  2198. }
  2199. }
  2200. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  2201. auto CurPrivate = C->privates().begin();
  2202. for (const Expr *E : C->varlists()) {
  2203. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2204. const auto *PrivateVD =
  2205. cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
  2206. if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
  2207. // Emit private VarDecl with copy init.
  2208. EmitVarDecl(*PrivateVD);
  2209. bool IsRegistered =
  2210. PrivateScope.addPrivate(VD, GetAddrOfLocalVar(PrivateVD));
  2211. assert(IsRegistered && "linear var already registered as private");
  2212. // Silence the warning about unused variable.
  2213. (void)IsRegistered;
  2214. } else {
  2215. EmitVarDecl(*PrivateVD);
  2216. }
  2217. ++CurPrivate;
  2218. }
  2219. }
  2220. }
  2221. static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
  2222. const OMPExecutableDirective &D) {
  2223. if (!CGF.HaveInsertPoint())
  2224. return;
  2225. if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
  2226. RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
  2227. /*ignoreResult=*/true);
  2228. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  2229. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  2230. // In presence of finite 'safelen', it may be unsafe to mark all
  2231. // the memory instructions parallel, because loop-carried
  2232. // dependences of 'safelen' iterations are possible.
  2233. CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
  2234. } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
  2235. RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
  2236. /*ignoreResult=*/true);
  2237. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  2238. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  2239. // In presence of finite 'safelen', it may be unsafe to mark all
  2240. // the memory instructions parallel, because loop-carried
  2241. // dependences of 'safelen' iterations are possible.
  2242. CGF.LoopStack.setParallel(/*Enable=*/false);
  2243. }
  2244. }
  2245. void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
  2246. // Walk clauses and process safelen/lastprivate.
  2247. LoopStack.setParallel(/*Enable=*/true);
  2248. LoopStack.setVectorizeEnable();
  2249. emitSimdlenSafelenClause(*this, D);
  2250. if (const auto *C = D.getSingleClause<OMPOrderClause>())
  2251. if (C->getKind() == OMPC_ORDER_concurrent)
  2252. LoopStack.setParallel(/*Enable=*/true);
  2253. if ((D.getDirectiveKind() == OMPD_simd ||
  2254. (getLangOpts().OpenMPSimd &&
  2255. isOpenMPSimdDirective(D.getDirectiveKind()))) &&
  2256. llvm::any_of(D.getClausesOfKind<OMPReductionClause>(),
  2257. [](const OMPReductionClause *C) {
  2258. return C->getModifier() == OMPC_REDUCTION_inscan;
  2259. }))
  2260. // Disable parallel access in case of prefix sum.
  2261. LoopStack.setParallel(/*Enable=*/false);
  2262. }
  2263. void CodeGenFunction::EmitOMPSimdFinal(
  2264. const OMPLoopDirective &D,
  2265. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  2266. if (!HaveInsertPoint())
  2267. return;
  2268. llvm::BasicBlock *DoneBB = nullptr;
  2269. auto IC = D.counters().begin();
  2270. auto IPC = D.private_counters().begin();
  2271. for (const Expr *F : D.finals()) {
  2272. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
  2273. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
  2274. const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
  2275. if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
  2276. OrigVD->hasGlobalStorage() || CED) {
  2277. if (!DoneBB) {
  2278. if (llvm::Value *Cond = CondGen(*this)) {
  2279. // If the first post-update expression is found, emit conditional
  2280. // block if it was requested.
  2281. llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
  2282. DoneBB = createBasicBlock(".omp.final.done");
  2283. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  2284. EmitBlock(ThenBB);
  2285. }
  2286. }
  2287. Address OrigAddr = Address::invalid();
  2288. if (CED) {
  2289. OrigAddr =
  2290. EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
  2291. } else {
  2292. DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
  2293. /*RefersToEnclosingVariableOrCapture=*/false,
  2294. (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
  2295. OrigAddr = EmitLValue(&DRE).getAddress(*this);
  2296. }
  2297. OMPPrivateScope VarScope(*this);
  2298. VarScope.addPrivate(OrigVD, OrigAddr);
  2299. (void)VarScope.Privatize();
  2300. EmitIgnoredExpr(F);
  2301. }
  2302. ++IC;
  2303. ++IPC;
  2304. }
  2305. if (DoneBB)
  2306. EmitBlock(DoneBB, /*IsFinished=*/true);
  2307. }
  2308. static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
  2309. const OMPLoopDirective &S,
  2310. CodeGenFunction::JumpDest LoopExit) {
  2311. CGF.EmitOMPLoopBody(S, LoopExit);
  2312. CGF.EmitStopPoint(&S);
  2313. }
  2314. /// Emit a helper variable and return corresponding lvalue.
  2315. static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
  2316. const DeclRefExpr *Helper) {
  2317. auto VDecl = cast<VarDecl>(Helper->getDecl());
  2318. CGF.EmitVarDecl(*VDecl);
  2319. return CGF.EmitLValue(Helper);
  2320. }
  2321. static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
  2322. const RegionCodeGenTy &SimdInitGen,
  2323. const RegionCodeGenTy &BodyCodeGen) {
  2324. auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
  2325. PrePostActionTy &) {
  2326. CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
  2327. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  2328. SimdInitGen(CGF);
  2329. BodyCodeGen(CGF);
  2330. };
  2331. auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
  2332. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  2333. CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
  2334. BodyCodeGen(CGF);
  2335. };
  2336. const Expr *IfCond = nullptr;
  2337. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  2338. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  2339. if (CGF.getLangOpts().OpenMP >= 50 &&
  2340. (C->getNameModifier() == OMPD_unknown ||
  2341. C->getNameModifier() == OMPD_simd)) {
  2342. IfCond = C->getCondition();
  2343. break;
  2344. }
  2345. }
  2346. }
  2347. if (IfCond) {
  2348. CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
  2349. } else {
  2350. RegionCodeGenTy ThenRCG(ThenGen);
  2351. ThenRCG(CGF);
  2352. }
  2353. }
  2354. static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
  2355. PrePostActionTy &Action) {
  2356. Action.Enter(CGF);
  2357. assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
  2358. "Expected simd directive");
  2359. OMPLoopScope PreInitScope(CGF, S);
  2360. // if (PreCond) {
  2361. // for (IV in 0..LastIteration) BODY;
  2362. // <Final counter/linear vars updates>;
  2363. // }
  2364. //
  2365. if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
  2366. isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
  2367. isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
  2368. (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
  2369. (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
  2370. }
  2371. // Emit: if (PreCond) - begin.
  2372. // If the condition constant folds and can be elided, avoid emitting the
  2373. // whole loop.
  2374. bool CondConstant;
  2375. llvm::BasicBlock *ContBlock = nullptr;
  2376. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  2377. if (!CondConstant)
  2378. return;
  2379. } else {
  2380. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
  2381. ContBlock = CGF.createBasicBlock("simd.if.end");
  2382. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  2383. CGF.getProfileCount(&S));
  2384. CGF.EmitBlock(ThenBlock);
  2385. CGF.incrementProfileCounter(&S);
  2386. }
  2387. // Emit the loop iteration variable.
  2388. const Expr *IVExpr = S.getIterationVariable();
  2389. const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  2390. CGF.EmitVarDecl(*IVDecl);
  2391. CGF.EmitIgnoredExpr(S.getInit());
  2392. // Emit the iterations count variable.
  2393. // If it is not a variable, Sema decided to calculate iterations count on
  2394. // each iteration (e.g., it is foldable into a constant).
  2395. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  2396. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  2397. // Emit calculation of the iterations count.
  2398. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  2399. }
  2400. emitAlignedClause(CGF, S);
  2401. (void)CGF.EmitOMPLinearClauseInit(S);
  2402. {
  2403. CodeGenFunction::OMPPrivateScope LoopScope(CGF);
  2404. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  2405. CGF.EmitOMPLinearClause(S, LoopScope);
  2406. CGF.EmitOMPPrivateClause(S, LoopScope);
  2407. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  2408. CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
  2409. CGF, S, CGF.EmitLValue(S.getIterationVariable()));
  2410. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  2411. (void)LoopScope.Privatize();
  2412. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  2413. CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
  2414. emitCommonSimdLoop(
  2415. CGF, S,
  2416. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2417. CGF.EmitOMPSimdInit(S);
  2418. },
  2419. [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
  2420. CGF.EmitOMPInnerLoop(
  2421. S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
  2422. [&S](CodeGenFunction &CGF) {
  2423. emitOMPLoopBodyWithStopPoint(CGF, S,
  2424. CodeGenFunction::JumpDest());
  2425. },
  2426. [](CodeGenFunction &) {});
  2427. });
  2428. CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
  2429. // Emit final copy of the lastprivate variables at the end of loops.
  2430. if (HasLastprivateClause)
  2431. CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
  2432. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
  2433. emitPostUpdateForReductionClause(CGF, S,
  2434. [](CodeGenFunction &) { return nullptr; });
  2435. LoopScope.restoreMap();
  2436. CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
  2437. }
  2438. // Emit: if (PreCond) - end.
  2439. if (ContBlock) {
  2440. CGF.EmitBranch(ContBlock);
  2441. CGF.EmitBlock(ContBlock, true);
  2442. }
  2443. }
  2444. static bool isSupportedByOpenMPIRBuilder(const OMPSimdDirective &S) {
  2445. // Check for unsupported clauses
  2446. for (OMPClause *C : S.clauses()) {
  2447. // Currently only order, simdlen and safelen clauses are supported
  2448. if (!(isa<OMPSimdlenClause>(C) || isa<OMPSafelenClause>(C) ||
  2449. isa<OMPOrderClause>(C) || isa<OMPAlignedClause>(C)))
  2450. return false;
  2451. }
  2452. // Check if we have a statement with the ordered directive.
  2453. // Visit the statement hierarchy to find a compound statement
  2454. // with a ordered directive in it.
  2455. if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(S.getRawStmt())) {
  2456. if (const Stmt *SyntacticalLoop = CanonLoop->getLoopStmt()) {
  2457. for (const Stmt *SubStmt : SyntacticalLoop->children()) {
  2458. if (!SubStmt)
  2459. continue;
  2460. if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(SubStmt)) {
  2461. for (const Stmt *CSSubStmt : CS->children()) {
  2462. if (!CSSubStmt)
  2463. continue;
  2464. if (isa<OMPOrderedDirective>(CSSubStmt)) {
  2465. return false;
  2466. }
  2467. }
  2468. }
  2469. }
  2470. }
  2471. }
  2472. return true;
  2473. }
  2474. static llvm::MapVector<llvm::Value *, llvm::Value *>
  2475. GetAlignedMapping(const OMPSimdDirective &S, CodeGenFunction &CGF) {
  2476. llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars;
  2477. for (const auto *Clause : S.getClausesOfKind<OMPAlignedClause>()) {
  2478. llvm::APInt ClauseAlignment(64, 0);
  2479. if (const Expr *AlignmentExpr = Clause->getAlignment()) {
  2480. auto *AlignmentCI =
  2481. cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
  2482. ClauseAlignment = AlignmentCI->getValue();
  2483. }
  2484. for (const Expr *E : Clause->varlists()) {
  2485. llvm::APInt Alignment(ClauseAlignment);
  2486. if (Alignment == 0) {
  2487. // OpenMP [2.8.1, Description]
  2488. // If no optional parameter is specified, implementation-defined default
  2489. // alignments for SIMD instructions on the target platforms are assumed.
  2490. Alignment =
  2491. CGF.getContext()
  2492. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  2493. E->getType()->getPointeeType()))
  2494. .getQuantity();
  2495. }
  2496. assert((Alignment == 0 || Alignment.isPowerOf2()) &&
  2497. "alignment is not power of 2");
  2498. llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
  2499. AlignedVars[PtrValue] = CGF.Builder.getInt64(Alignment.getSExtValue());
  2500. }
  2501. }
  2502. return AlignedVars;
  2503. }
  2504. void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
  2505. bool UseOMPIRBuilder =
  2506. CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S);
  2507. if (UseOMPIRBuilder) {
  2508. auto &&CodeGenIRBuilder = [this, &S, UseOMPIRBuilder](CodeGenFunction &CGF,
  2509. PrePostActionTy &) {
  2510. // Use the OpenMPIRBuilder if enabled.
  2511. if (UseOMPIRBuilder) {
  2512. llvm::MapVector<llvm::Value *, llvm::Value *> AlignedVars =
  2513. GetAlignedMapping(S, CGF);
  2514. // Emit the associated statement and get its loop representation.
  2515. const Stmt *Inner = S.getRawStmt();
  2516. llvm::CanonicalLoopInfo *CLI =
  2517. EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
  2518. llvm::OpenMPIRBuilder &OMPBuilder =
  2519. CGM.getOpenMPRuntime().getOMPBuilder();
  2520. // Add SIMD specific metadata
  2521. llvm::ConstantInt *Simdlen = nullptr;
  2522. if (const auto *C = S.getSingleClause<OMPSimdlenClause>()) {
  2523. RValue Len =
  2524. this->EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
  2525. /*ignoreResult=*/true);
  2526. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  2527. Simdlen = Val;
  2528. }
  2529. llvm::ConstantInt *Safelen = nullptr;
  2530. if (const auto *C = S.getSingleClause<OMPSafelenClause>()) {
  2531. RValue Len =
  2532. this->EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
  2533. /*ignoreResult=*/true);
  2534. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  2535. Safelen = Val;
  2536. }
  2537. llvm::omp::OrderKind Order = llvm::omp::OrderKind::OMP_ORDER_unknown;
  2538. if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
  2539. if (C->getKind() == OpenMPOrderClauseKind ::OMPC_ORDER_concurrent) {
  2540. Order = llvm::omp::OrderKind::OMP_ORDER_concurrent;
  2541. }
  2542. }
  2543. // Add simd metadata to the collapsed loop. Do not generate
  2544. // another loop for if clause. Support for if clause is done earlier.
  2545. OMPBuilder.applySimd(CLI, AlignedVars,
  2546. /*IfCond*/ nullptr, Order, Simdlen, Safelen);
  2547. return;
  2548. }
  2549. };
  2550. {
  2551. auto LPCRegion =
  2552. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  2553. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2554. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd,
  2555. CodeGenIRBuilder);
  2556. }
  2557. return;
  2558. }
  2559. ParentLoopDirectiveForScanRegion ScanRegion(*this, S);
  2560. OMPFirstScanLoop = true;
  2561. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2562. emitOMPSimdRegion(CGF, S, Action);
  2563. };
  2564. {
  2565. auto LPCRegion =
  2566. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  2567. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2568. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  2569. }
  2570. // Check for outer lastprivate conditional update.
  2571. checkForLastprivateConditionalUpdate(*this, S);
  2572. }
  2573. void CodeGenFunction::EmitOMPTileDirective(const OMPTileDirective &S) {
  2574. // Emit the de-sugared statement.
  2575. OMPTransformDirectiveScopeRAII TileScope(*this, &S);
  2576. EmitStmt(S.getTransformedStmt());
  2577. }
  2578. void CodeGenFunction::EmitOMPUnrollDirective(const OMPUnrollDirective &S) {
  2579. bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder;
  2580. if (UseOMPIRBuilder) {
  2581. auto DL = SourceLocToDebugLoc(S.getBeginLoc());
  2582. const Stmt *Inner = S.getRawStmt();
  2583. // Consume nested loop. Clear the entire remaining loop stack because a
  2584. // fully unrolled loop is non-transformable. For partial unrolling the
  2585. // generated outer loop is pushed back to the stack.
  2586. llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
  2587. OMPLoopNestStack.clear();
  2588. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  2589. bool NeedsUnrolledCLI = ExpectedOMPLoopDepth >= 1;
  2590. llvm::CanonicalLoopInfo *UnrolledCLI = nullptr;
  2591. if (S.hasClausesOfKind<OMPFullClause>()) {
  2592. assert(ExpectedOMPLoopDepth == 0);
  2593. OMPBuilder.unrollLoopFull(DL, CLI);
  2594. } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
  2595. uint64_t Factor = 0;
  2596. if (Expr *FactorExpr = PartialClause->getFactor()) {
  2597. Factor = FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
  2598. assert(Factor >= 1 && "Only positive factors are valid");
  2599. }
  2600. OMPBuilder.unrollLoopPartial(DL, CLI, Factor,
  2601. NeedsUnrolledCLI ? &UnrolledCLI : nullptr);
  2602. } else {
  2603. OMPBuilder.unrollLoopHeuristic(DL, CLI);
  2604. }
  2605. assert((!NeedsUnrolledCLI || UnrolledCLI) &&
  2606. "NeedsUnrolledCLI implies UnrolledCLI to be set");
  2607. if (UnrolledCLI)
  2608. OMPLoopNestStack.push_back(UnrolledCLI);
  2609. return;
  2610. }
  2611. // This function is only called if the unrolled loop is not consumed by any
  2612. // other loop-associated construct. Such a loop-associated construct will have
  2613. // used the transformed AST.
  2614. // Set the unroll metadata for the next emitted loop.
  2615. LoopStack.setUnrollState(LoopAttributes::Enable);
  2616. if (S.hasClausesOfKind<OMPFullClause>()) {
  2617. LoopStack.setUnrollState(LoopAttributes::Full);
  2618. } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
  2619. if (Expr *FactorExpr = PartialClause->getFactor()) {
  2620. uint64_t Factor =
  2621. FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
  2622. assert(Factor >= 1 && "Only positive factors are valid");
  2623. LoopStack.setUnrollCount(Factor);
  2624. }
  2625. }
  2626. EmitStmt(S.getAssociatedStmt());
  2627. }
  2628. void CodeGenFunction::EmitOMPOuterLoop(
  2629. bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
  2630. CodeGenFunction::OMPPrivateScope &LoopScope,
  2631. const CodeGenFunction::OMPLoopArguments &LoopArgs,
  2632. const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
  2633. const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
  2634. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  2635. const Expr *IVExpr = S.getIterationVariable();
  2636. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2637. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2638. JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
  2639. // Start the loop with a block that tests the condition.
  2640. llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
  2641. EmitBlock(CondBlock);
  2642. const SourceRange R = S.getSourceRange();
  2643. OMPLoopNestStack.clear();
  2644. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  2645. SourceLocToDebugLoc(R.getEnd()));
  2646. llvm::Value *BoolCondVal = nullptr;
  2647. if (!DynamicOrOrdered) {
  2648. // UB = min(UB, GlobalUB) or
  2649. // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
  2650. // 'distribute parallel for')
  2651. EmitIgnoredExpr(LoopArgs.EUB);
  2652. // IV = LB
  2653. EmitIgnoredExpr(LoopArgs.Init);
  2654. // IV < UB
  2655. BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
  2656. } else {
  2657. BoolCondVal =
  2658. RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
  2659. LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
  2660. }
  2661. // If there are any cleanups between here and the loop-exit scope,
  2662. // create a block to stage a loop exit along.
  2663. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  2664. if (LoopScope.requiresCleanups())
  2665. ExitBlock = createBasicBlock("omp.dispatch.cleanup");
  2666. llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
  2667. Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
  2668. if (ExitBlock != LoopExit.getBlock()) {
  2669. EmitBlock(ExitBlock);
  2670. EmitBranchThroughCleanup(LoopExit);
  2671. }
  2672. EmitBlock(LoopBody);
  2673. // Emit "IV = LB" (in case of static schedule, we have already calculated new
  2674. // LB for loop condition and emitted it above).
  2675. if (DynamicOrOrdered)
  2676. EmitIgnoredExpr(LoopArgs.Init);
  2677. // Create a block for the increment.
  2678. JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
  2679. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  2680. emitCommonSimdLoop(
  2681. *this, S,
  2682. [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
  2683. // Generate !llvm.loop.parallel metadata for loads and stores for loops
  2684. // with dynamic/guided scheduling and without ordered clause.
  2685. if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
  2686. CGF.LoopStack.setParallel(!IsMonotonic);
  2687. if (const auto *C = S.getSingleClause<OMPOrderClause>())
  2688. if (C->getKind() == OMPC_ORDER_concurrent)
  2689. CGF.LoopStack.setParallel(/*Enable=*/true);
  2690. } else {
  2691. CGF.EmitOMPSimdInit(S);
  2692. }
  2693. },
  2694. [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
  2695. &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
  2696. SourceLocation Loc = S.getBeginLoc();
  2697. // when 'distribute' is not combined with a 'for':
  2698. // while (idx <= UB) { BODY; ++idx; }
  2699. // when 'distribute' is combined with a 'for'
  2700. // (e.g. 'distribute parallel for')
  2701. // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
  2702. CGF.EmitOMPInnerLoop(
  2703. S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
  2704. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  2705. CodeGenLoop(CGF, S, LoopExit);
  2706. },
  2707. [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
  2708. CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
  2709. });
  2710. });
  2711. EmitBlock(Continue.getBlock());
  2712. BreakContinueStack.pop_back();
  2713. if (!DynamicOrOrdered) {
  2714. // Emit "LB = LB + Stride", "UB = UB + Stride".
  2715. EmitIgnoredExpr(LoopArgs.NextLB);
  2716. EmitIgnoredExpr(LoopArgs.NextUB);
  2717. }
  2718. EmitBranch(CondBlock);
  2719. OMPLoopNestStack.clear();
  2720. LoopStack.pop();
  2721. // Emit the fall-through block.
  2722. EmitBlock(LoopExit.getBlock());
  2723. // Tell the runtime we are done.
  2724. auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
  2725. if (!DynamicOrOrdered)
  2726. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  2727. S.getDirectiveKind());
  2728. };
  2729. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  2730. }
  2731. void CodeGenFunction::EmitOMPForOuterLoop(
  2732. const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
  2733. const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
  2734. const OMPLoopArguments &LoopArgs,
  2735. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  2736. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  2737. // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
  2738. const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind.Schedule);
  2739. assert((Ordered || !RT.isStaticNonchunked(ScheduleKind.Schedule,
  2740. LoopArgs.Chunk != nullptr)) &&
  2741. "static non-chunked schedule does not need outer loop");
  2742. // Emit outer loop.
  2743. //
  2744. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  2745. // When schedule(dynamic,chunk_size) is specified, the iterations are
  2746. // distributed to threads in the team in chunks as the threads request them.
  2747. // Each thread executes a chunk of iterations, then requests another chunk,
  2748. // until no chunks remain to be distributed. Each chunk contains chunk_size
  2749. // iterations, except for the last chunk to be distributed, which may have
  2750. // fewer iterations. When no chunk_size is specified, it defaults to 1.
  2751. //
  2752. // When schedule(guided,chunk_size) is specified, the iterations are assigned
  2753. // to threads in the team in chunks as the executing threads request them.
  2754. // Each thread executes a chunk of iterations, then requests another chunk,
  2755. // until no chunks remain to be assigned. For a chunk_size of 1, the size of
  2756. // each chunk is proportional to the number of unassigned iterations divided
  2757. // by the number of threads in the team, decreasing to 1. For a chunk_size
  2758. // with value k (greater than 1), the size of each chunk is determined in the
  2759. // same way, with the restriction that the chunks do not contain fewer than k
  2760. // iterations (except for the last chunk to be assigned, which may have fewer
  2761. // than k iterations).
  2762. //
  2763. // When schedule(auto) is specified, the decision regarding scheduling is
  2764. // delegated to the compiler and/or runtime system. The programmer gives the
  2765. // implementation the freedom to choose any possible mapping of iterations to
  2766. // threads in the team.
  2767. //
  2768. // When schedule(runtime) is specified, the decision regarding scheduling is
  2769. // deferred until run time, and the schedule and chunk size are taken from the
  2770. // run-sched-var ICV. If the ICV is set to auto, the schedule is
  2771. // implementation defined
  2772. //
  2773. // while(__kmpc_dispatch_next(&LB, &UB)) {
  2774. // idx = LB;
  2775. // while (idx <= UB) { BODY; ++idx;
  2776. // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
  2777. // } // inner loop
  2778. // }
  2779. //
  2780. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  2781. // When schedule(static, chunk_size) is specified, iterations are divided into
  2782. // chunks of size chunk_size, and the chunks are assigned to the threads in
  2783. // the team in a round-robin fashion in the order of the thread number.
  2784. //
  2785. // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
  2786. // while (idx <= UB) { BODY; ++idx; } // inner loop
  2787. // LB = LB + ST;
  2788. // UB = UB + ST;
  2789. // }
  2790. //
  2791. const Expr *IVExpr = S.getIterationVariable();
  2792. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2793. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2794. if (DynamicOrOrdered) {
  2795. const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
  2796. CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
  2797. llvm::Value *LBVal = DispatchBounds.first;
  2798. llvm::Value *UBVal = DispatchBounds.second;
  2799. CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
  2800. LoopArgs.Chunk};
  2801. RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
  2802. IVSigned, Ordered, DipatchRTInputValues);
  2803. } else {
  2804. CGOpenMPRuntime::StaticRTInput StaticInit(
  2805. IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
  2806. LoopArgs.ST, LoopArgs.Chunk);
  2807. RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
  2808. ScheduleKind, StaticInit);
  2809. }
  2810. auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
  2811. const unsigned IVSize,
  2812. const bool IVSigned) {
  2813. if (Ordered) {
  2814. CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
  2815. IVSigned);
  2816. }
  2817. };
  2818. OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
  2819. LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
  2820. OuterLoopArgs.IncExpr = S.getInc();
  2821. OuterLoopArgs.Init = S.getInit();
  2822. OuterLoopArgs.Cond = S.getCond();
  2823. OuterLoopArgs.NextLB = S.getNextLowerBound();
  2824. OuterLoopArgs.NextUB = S.getNextUpperBound();
  2825. EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
  2826. emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
  2827. }
  2828. static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
  2829. const unsigned IVSize, const bool IVSigned) {}
  2830. void CodeGenFunction::EmitOMPDistributeOuterLoop(
  2831. OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
  2832. OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
  2833. const CodeGenLoopTy &CodeGenLoopContent) {
  2834. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  2835. // Emit outer loop.
  2836. // Same behavior as a OMPForOuterLoop, except that schedule cannot be
  2837. // dynamic
  2838. //
  2839. const Expr *IVExpr = S.getIterationVariable();
  2840. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2841. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2842. CGOpenMPRuntime::StaticRTInput StaticInit(
  2843. IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
  2844. LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
  2845. RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
  2846. // for combined 'distribute' and 'for' the increment expression of distribute
  2847. // is stored in DistInc. For 'distribute' alone, it is in Inc.
  2848. Expr *IncExpr;
  2849. if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
  2850. IncExpr = S.getDistInc();
  2851. else
  2852. IncExpr = S.getInc();
  2853. // this routine is shared by 'omp distribute parallel for' and
  2854. // 'omp distribute': select the right EUB expression depending on the
  2855. // directive
  2856. OMPLoopArguments OuterLoopArgs;
  2857. OuterLoopArgs.LB = LoopArgs.LB;
  2858. OuterLoopArgs.UB = LoopArgs.UB;
  2859. OuterLoopArgs.ST = LoopArgs.ST;
  2860. OuterLoopArgs.IL = LoopArgs.IL;
  2861. OuterLoopArgs.Chunk = LoopArgs.Chunk;
  2862. OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2863. ? S.getCombinedEnsureUpperBound()
  2864. : S.getEnsureUpperBound();
  2865. OuterLoopArgs.IncExpr = IncExpr;
  2866. OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2867. ? S.getCombinedInit()
  2868. : S.getInit();
  2869. OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2870. ? S.getCombinedCond()
  2871. : S.getCond();
  2872. OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2873. ? S.getCombinedNextLowerBound()
  2874. : S.getNextLowerBound();
  2875. OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2876. ? S.getCombinedNextUpperBound()
  2877. : S.getNextUpperBound();
  2878. EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
  2879. LoopScope, OuterLoopArgs, CodeGenLoopContent,
  2880. emitEmptyOrdered);
  2881. }
  2882. static std::pair<LValue, LValue>
  2883. emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
  2884. const OMPExecutableDirective &S) {
  2885. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  2886. LValue LB =
  2887. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  2888. LValue UB =
  2889. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  2890. // When composing 'distribute' with 'for' (e.g. as in 'distribute
  2891. // parallel for') we need to use the 'distribute'
  2892. // chunk lower and upper bounds rather than the whole loop iteration
  2893. // space. These are parameters to the outlined function for 'parallel'
  2894. // and we copy the bounds of the previous schedule into the
  2895. // the current ones.
  2896. LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
  2897. LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
  2898. llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
  2899. PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
  2900. PrevLBVal = CGF.EmitScalarConversion(
  2901. PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
  2902. LS.getIterationVariable()->getType(),
  2903. LS.getPrevLowerBoundVariable()->getExprLoc());
  2904. llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
  2905. PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
  2906. PrevUBVal = CGF.EmitScalarConversion(
  2907. PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
  2908. LS.getIterationVariable()->getType(),
  2909. LS.getPrevUpperBoundVariable()->getExprLoc());
  2910. CGF.EmitStoreOfScalar(PrevLBVal, LB);
  2911. CGF.EmitStoreOfScalar(PrevUBVal, UB);
  2912. return {LB, UB};
  2913. }
  2914. /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
  2915. /// we need to use the LB and UB expressions generated by the worksharing
  2916. /// code generation support, whereas in non combined situations we would
  2917. /// just emit 0 and the LastIteration expression
  2918. /// This function is necessary due to the difference of the LB and UB
  2919. /// types for the RT emission routines for 'for_static_init' and
  2920. /// 'for_dispatch_init'
  2921. static std::pair<llvm::Value *, llvm::Value *>
  2922. emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
  2923. const OMPExecutableDirective &S,
  2924. Address LB, Address UB) {
  2925. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  2926. const Expr *IVExpr = LS.getIterationVariable();
  2927. // when implementing a dynamic schedule for a 'for' combined with a
  2928. // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
  2929. // is not normalized as each team only executes its own assigned
  2930. // distribute chunk
  2931. QualType IteratorTy = IVExpr->getType();
  2932. llvm::Value *LBVal =
  2933. CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
  2934. llvm::Value *UBVal =
  2935. CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
  2936. return {LBVal, UBVal};
  2937. }
  2938. static void emitDistributeParallelForDistributeInnerBoundParams(
  2939. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  2940. llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
  2941. const auto &Dir = cast<OMPLoopDirective>(S);
  2942. LValue LB =
  2943. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
  2944. llvm::Value *LBCast =
  2945. CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
  2946. CGF.SizeTy, /*isSigned=*/false);
  2947. CapturedVars.push_back(LBCast);
  2948. LValue UB =
  2949. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
  2950. llvm::Value *UBCast =
  2951. CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
  2952. CGF.SizeTy, /*isSigned=*/false);
  2953. CapturedVars.push_back(UBCast);
  2954. }
  2955. static void
  2956. emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
  2957. const OMPLoopDirective &S,
  2958. CodeGenFunction::JumpDest LoopExit) {
  2959. auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
  2960. PrePostActionTy &Action) {
  2961. Action.Enter(CGF);
  2962. bool HasCancel = false;
  2963. if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
  2964. if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
  2965. HasCancel = D->hasCancel();
  2966. else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
  2967. HasCancel = D->hasCancel();
  2968. else if (const auto *D =
  2969. dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
  2970. HasCancel = D->hasCancel();
  2971. }
  2972. CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
  2973. HasCancel);
  2974. CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
  2975. emitDistributeParallelForInnerBounds,
  2976. emitDistributeParallelForDispatchBounds);
  2977. };
  2978. emitCommonOMPParallelDirective(
  2979. CGF, S,
  2980. isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
  2981. CGInlinedWorksharingLoop,
  2982. emitDistributeParallelForDistributeInnerBoundParams);
  2983. }
  2984. void CodeGenFunction::EmitOMPDistributeParallelForDirective(
  2985. const OMPDistributeParallelForDirective &S) {
  2986. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2987. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  2988. S.getDistInc());
  2989. };
  2990. OMPLexicalScope Scope(*this, S, OMPD_parallel);
  2991. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  2992. }
  2993. void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
  2994. const OMPDistributeParallelForSimdDirective &S) {
  2995. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2996. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  2997. S.getDistInc());
  2998. };
  2999. OMPLexicalScope Scope(*this, S, OMPD_parallel);
  3000. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  3001. }
  3002. void CodeGenFunction::EmitOMPDistributeSimdDirective(
  3003. const OMPDistributeSimdDirective &S) {
  3004. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3005. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  3006. };
  3007. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3008. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  3009. }
  3010. void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
  3011. CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
  3012. // Emit SPMD target parallel for region as a standalone region.
  3013. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3014. emitOMPSimdRegion(CGF, S, Action);
  3015. };
  3016. llvm::Function *Fn;
  3017. llvm::Constant *Addr;
  3018. // Emit target region as a standalone region.
  3019. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3020. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3021. assert(Fn && Addr && "Target device function emission failed.");
  3022. }
  3023. void CodeGenFunction::EmitOMPTargetSimdDirective(
  3024. const OMPTargetSimdDirective &S) {
  3025. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3026. emitOMPSimdRegion(CGF, S, Action);
  3027. };
  3028. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3029. }
  3030. namespace {
  3031. struct ScheduleKindModifiersTy {
  3032. OpenMPScheduleClauseKind Kind;
  3033. OpenMPScheduleClauseModifier M1;
  3034. OpenMPScheduleClauseModifier M2;
  3035. ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
  3036. OpenMPScheduleClauseModifier M1,
  3037. OpenMPScheduleClauseModifier M2)
  3038. : Kind(Kind), M1(M1), M2(M2) {}
  3039. };
  3040. } // namespace
  3041. bool CodeGenFunction::EmitOMPWorksharingLoop(
  3042. const OMPLoopDirective &S, Expr *EUB,
  3043. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  3044. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  3045. // Emit the loop iteration variable.
  3046. const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  3047. const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
  3048. EmitVarDecl(*IVDecl);
  3049. // Emit the iterations count variable.
  3050. // If it is not a variable, Sema decided to calculate iterations count on each
  3051. // iteration (e.g., it is foldable into a constant).
  3052. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  3053. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  3054. // Emit calculation of the iterations count.
  3055. EmitIgnoredExpr(S.getCalcLastIteration());
  3056. }
  3057. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  3058. bool HasLastprivateClause;
  3059. // Check pre-condition.
  3060. {
  3061. OMPLoopScope PreInitScope(*this, S);
  3062. // Skip the entire loop if we don't meet the precondition.
  3063. // If the condition constant folds and can be elided, avoid emitting the
  3064. // whole loop.
  3065. bool CondConstant;
  3066. llvm::BasicBlock *ContBlock = nullptr;
  3067. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  3068. if (!CondConstant)
  3069. return false;
  3070. } else {
  3071. llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
  3072. ContBlock = createBasicBlock("omp.precond.end");
  3073. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  3074. getProfileCount(&S));
  3075. EmitBlock(ThenBlock);
  3076. incrementProfileCounter(&S);
  3077. }
  3078. RunCleanupsScope DoacrossCleanupScope(*this);
  3079. bool Ordered = false;
  3080. if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
  3081. if (OrderedClause->getNumForLoops())
  3082. RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
  3083. else
  3084. Ordered = true;
  3085. }
  3086. llvm::DenseSet<const Expr *> EmittedFinals;
  3087. emitAlignedClause(*this, S);
  3088. bool HasLinears = EmitOMPLinearClauseInit(S);
  3089. // Emit helper vars inits.
  3090. std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
  3091. LValue LB = Bounds.first;
  3092. LValue UB = Bounds.second;
  3093. LValue ST =
  3094. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  3095. LValue IL =
  3096. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  3097. // Emit 'then' code.
  3098. {
  3099. OMPPrivateScope LoopScope(*this);
  3100. if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
  3101. // Emit implicit barrier to synchronize threads and avoid data races on
  3102. // initialization of firstprivate variables and post-update of
  3103. // lastprivate variables.
  3104. CGM.getOpenMPRuntime().emitBarrierCall(
  3105. *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  3106. /*ForceSimpleCall=*/true);
  3107. }
  3108. EmitOMPPrivateClause(S, LoopScope);
  3109. CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
  3110. *this, S, EmitLValue(S.getIterationVariable()));
  3111. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  3112. EmitOMPReductionClauseInit(S, LoopScope);
  3113. EmitOMPPrivateLoopCounters(S, LoopScope);
  3114. EmitOMPLinearClause(S, LoopScope);
  3115. (void)LoopScope.Privatize();
  3116. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  3117. CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
  3118. // Detect the loop schedule kind and chunk.
  3119. const Expr *ChunkExpr = nullptr;
  3120. OpenMPScheduleTy ScheduleKind;
  3121. if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
  3122. ScheduleKind.Schedule = C->getScheduleKind();
  3123. ScheduleKind.M1 = C->getFirstScheduleModifier();
  3124. ScheduleKind.M2 = C->getSecondScheduleModifier();
  3125. ChunkExpr = C->getChunkSize();
  3126. } else {
  3127. // Default behaviour for schedule clause.
  3128. CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
  3129. *this, S, ScheduleKind.Schedule, ChunkExpr);
  3130. }
  3131. bool HasChunkSizeOne = false;
  3132. llvm::Value *Chunk = nullptr;
  3133. if (ChunkExpr) {
  3134. Chunk = EmitScalarExpr(ChunkExpr);
  3135. Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
  3136. S.getIterationVariable()->getType(),
  3137. S.getBeginLoc());
  3138. Expr::EvalResult Result;
  3139. if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
  3140. llvm::APSInt EvaluatedChunk = Result.Val.getInt();
  3141. HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
  3142. }
  3143. }
  3144. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  3145. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  3146. // OpenMP 4.5, 2.7.1 Loop Construct, Description.
  3147. // If the static schedule kind is specified or if the ordered clause is
  3148. // specified, and if no monotonic modifier is specified, the effect will
  3149. // be as if the monotonic modifier was specified.
  3150. bool StaticChunkedOne =
  3151. RT.isStaticChunked(ScheduleKind.Schedule,
  3152. /* Chunked */ Chunk != nullptr) &&
  3153. HasChunkSizeOne &&
  3154. isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
  3155. bool IsMonotonic =
  3156. Ordered ||
  3157. (ScheduleKind.Schedule == OMPC_SCHEDULE_static &&
  3158. !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3159. ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) ||
  3160. ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
  3161. ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
  3162. if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
  3163. /* Chunked */ Chunk != nullptr) ||
  3164. StaticChunkedOne) &&
  3165. !Ordered) {
  3166. JumpDest LoopExit =
  3167. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  3168. emitCommonSimdLoop(
  3169. *this, S,
  3170. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3171. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  3172. CGF.EmitOMPSimdInit(S);
  3173. } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
  3174. if (C->getKind() == OMPC_ORDER_concurrent)
  3175. CGF.LoopStack.setParallel(/*Enable=*/true);
  3176. }
  3177. },
  3178. [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
  3179. &S, ScheduleKind, LoopExit,
  3180. &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
  3181. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  3182. // When no chunk_size is specified, the iteration space is divided
  3183. // into chunks that are approximately equal in size, and at most
  3184. // one chunk is distributed to each thread. Note that the size of
  3185. // the chunks is unspecified in this case.
  3186. CGOpenMPRuntime::StaticRTInput StaticInit(
  3187. IVSize, IVSigned, Ordered, IL.getAddress(CGF),
  3188. LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
  3189. StaticChunkedOne ? Chunk : nullptr);
  3190. CGF.CGM.getOpenMPRuntime().emitForStaticInit(
  3191. CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
  3192. StaticInit);
  3193. // UB = min(UB, GlobalUB);
  3194. if (!StaticChunkedOne)
  3195. CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
  3196. // IV = LB;
  3197. CGF.EmitIgnoredExpr(S.getInit());
  3198. // For unchunked static schedule generate:
  3199. //
  3200. // while (idx <= UB) {
  3201. // BODY;
  3202. // ++idx;
  3203. // }
  3204. //
  3205. // For static schedule with chunk one:
  3206. //
  3207. // while (IV <= PrevUB) {
  3208. // BODY;
  3209. // IV += ST;
  3210. // }
  3211. CGF.EmitOMPInnerLoop(
  3212. S, LoopScope.requiresCleanups(),
  3213. StaticChunkedOne ? S.getCombinedParForInDistCond()
  3214. : S.getCond(),
  3215. StaticChunkedOne ? S.getDistInc() : S.getInc(),
  3216. [&S, LoopExit](CodeGenFunction &CGF) {
  3217. emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit);
  3218. },
  3219. [](CodeGenFunction &) {});
  3220. });
  3221. EmitBlock(LoopExit.getBlock());
  3222. // Tell the runtime we are done.
  3223. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  3224. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  3225. S.getDirectiveKind());
  3226. };
  3227. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  3228. } else {
  3229. // Emit the outer loop, which requests its work chunk [LB..UB] from
  3230. // runtime and runs the inner loop to process it.
  3231. const OMPLoopArguments LoopArguments(
  3232. LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
  3233. IL.getAddress(*this), Chunk, EUB);
  3234. EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
  3235. LoopArguments, CGDispatchBounds);
  3236. }
  3237. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  3238. EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
  3239. return CGF.Builder.CreateIsNotNull(
  3240. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3241. });
  3242. }
  3243. EmitOMPReductionClauseFinal(
  3244. S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
  3245. ? /*Parallel and Simd*/ OMPD_parallel_for_simd
  3246. : /*Parallel only*/ OMPD_parallel);
  3247. // Emit post-update of the reduction variables if IsLastIter != 0.
  3248. emitPostUpdateForReductionClause(
  3249. *this, S, [IL, &S](CodeGenFunction &CGF) {
  3250. return CGF.Builder.CreateIsNotNull(
  3251. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3252. });
  3253. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  3254. if (HasLastprivateClause)
  3255. EmitOMPLastprivateClauseFinal(
  3256. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  3257. Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
  3258. LoopScope.restoreMap();
  3259. EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
  3260. return CGF.Builder.CreateIsNotNull(
  3261. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3262. });
  3263. }
  3264. DoacrossCleanupScope.ForceCleanup();
  3265. // We're now done with the loop, so jump to the continuation block.
  3266. if (ContBlock) {
  3267. EmitBranch(ContBlock);
  3268. EmitBlock(ContBlock, /*IsFinished=*/true);
  3269. }
  3270. }
  3271. return HasLastprivateClause;
  3272. }
  3273. /// The following two functions generate expressions for the loop lower
  3274. /// and upper bounds in case of static and dynamic (dispatch) schedule
  3275. /// of the associated 'for' or 'distribute' loop.
  3276. static std::pair<LValue, LValue>
  3277. emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  3278. const auto &LS = cast<OMPLoopDirective>(S);
  3279. LValue LB =
  3280. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  3281. LValue UB =
  3282. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  3283. return {LB, UB};
  3284. }
  3285. /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
  3286. /// consider the lower and upper bound expressions generated by the
  3287. /// worksharing loop support, but we use 0 and the iteration space size as
  3288. /// constants
  3289. static std::pair<llvm::Value *, llvm::Value *>
  3290. emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
  3291. Address LB, Address UB) {
  3292. const auto &LS = cast<OMPLoopDirective>(S);
  3293. const Expr *IVExpr = LS.getIterationVariable();
  3294. const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
  3295. llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
  3296. llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
  3297. return {LBVal, UBVal};
  3298. }
  3299. /// Emits internal temp array declarations for the directive with inscan
  3300. /// reductions.
  3301. /// The code is the following:
  3302. /// \code
  3303. /// size num_iters = <num_iters>;
  3304. /// <type> buffer[num_iters];
  3305. /// \endcode
  3306. static void emitScanBasedDirectiveDecls(
  3307. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3308. llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
  3309. llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
  3310. NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
  3311. SmallVector<const Expr *, 4> Shareds;
  3312. SmallVector<const Expr *, 4> Privates;
  3313. SmallVector<const Expr *, 4> ReductionOps;
  3314. SmallVector<const Expr *, 4> CopyArrayTemps;
  3315. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  3316. assert(C->getModifier() == OMPC_REDUCTION_inscan &&
  3317. "Only inscan reductions are expected.");
  3318. Shareds.append(C->varlist_begin(), C->varlist_end());
  3319. Privates.append(C->privates().begin(), C->privates().end());
  3320. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  3321. CopyArrayTemps.append(C->copy_array_temps().begin(),
  3322. C->copy_array_temps().end());
  3323. }
  3324. {
  3325. // Emit buffers for each reduction variables.
  3326. // ReductionCodeGen is required to emit correctly the code for array
  3327. // reductions.
  3328. ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
  3329. unsigned Count = 0;
  3330. auto *ITA = CopyArrayTemps.begin();
  3331. for (const Expr *IRef : Privates) {
  3332. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
  3333. // Emit variably modified arrays, used for arrays/array sections
  3334. // reductions.
  3335. if (PrivateVD->getType()->isVariablyModifiedType()) {
  3336. RedCG.emitSharedOrigLValue(CGF, Count);
  3337. RedCG.emitAggregateType(CGF, Count);
  3338. }
  3339. CodeGenFunction::OpaqueValueMapping DimMapping(
  3340. CGF,
  3341. cast<OpaqueValueExpr>(
  3342. cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe())
  3343. ->getSizeExpr()),
  3344. RValue::get(OMPScanNumIterations));
  3345. // Emit temp buffer.
  3346. CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl()));
  3347. ++ITA;
  3348. ++Count;
  3349. }
  3350. }
  3351. }
  3352. /// Copies final inscan reductions values to the original variables.
  3353. /// The code is the following:
  3354. /// \code
  3355. /// <orig_var> = buffer[num_iters-1];
  3356. /// \endcode
  3357. static void emitScanBasedDirectiveFinals(
  3358. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3359. llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
  3360. llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
  3361. NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
  3362. SmallVector<const Expr *, 4> Shareds;
  3363. SmallVector<const Expr *, 4> LHSs;
  3364. SmallVector<const Expr *, 4> RHSs;
  3365. SmallVector<const Expr *, 4> Privates;
  3366. SmallVector<const Expr *, 4> CopyOps;
  3367. SmallVector<const Expr *, 4> CopyArrayElems;
  3368. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  3369. assert(C->getModifier() == OMPC_REDUCTION_inscan &&
  3370. "Only inscan reductions are expected.");
  3371. Shareds.append(C->varlist_begin(), C->varlist_end());
  3372. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  3373. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  3374. Privates.append(C->privates().begin(), C->privates().end());
  3375. CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
  3376. CopyArrayElems.append(C->copy_array_elems().begin(),
  3377. C->copy_array_elems().end());
  3378. }
  3379. // Create temp var and copy LHS value to this temp value.
  3380. // LHS = TMP[LastIter];
  3381. llvm::Value *OMPLast = CGF.Builder.CreateNSWSub(
  3382. OMPScanNumIterations,
  3383. llvm::ConstantInt::get(CGF.SizeTy, 1, /*isSigned=*/false));
  3384. for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
  3385. const Expr *PrivateExpr = Privates[I];
  3386. const Expr *OrigExpr = Shareds[I];
  3387. const Expr *CopyArrayElem = CopyArrayElems[I];
  3388. CodeGenFunction::OpaqueValueMapping IdxMapping(
  3389. CGF,
  3390. cast<OpaqueValueExpr>(
  3391. cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
  3392. RValue::get(OMPLast));
  3393. LValue DestLVal = CGF.EmitLValue(OrigExpr);
  3394. LValue SrcLVal = CGF.EmitLValue(CopyArrayElem);
  3395. CGF.EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(CGF),
  3396. SrcLVal.getAddress(CGF),
  3397. cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
  3398. cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
  3399. CopyOps[I]);
  3400. }
  3401. }
  3402. /// Emits the code for the directive with inscan reductions.
  3403. /// The code is the following:
  3404. /// \code
  3405. /// #pragma omp ...
  3406. /// for (i: 0..<num_iters>) {
  3407. /// <input phase>;
  3408. /// buffer[i] = red;
  3409. /// }
  3410. /// #pragma omp master // in parallel region
  3411. /// for (int k = 0; k != ceil(log2(num_iters)); ++k)
  3412. /// for (size cnt = last_iter; cnt >= pow(2, k); --k)
  3413. /// buffer[i] op= buffer[i-pow(2,k)];
  3414. /// #pragma omp barrier // in parallel region
  3415. /// #pragma omp ...
  3416. /// for (0..<num_iters>) {
  3417. /// red = InclusiveScan ? buffer[i] : buffer[i-1];
  3418. /// <scan phase>;
  3419. /// }
  3420. /// \endcode
  3421. static void emitScanBasedDirective(
  3422. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3423. llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen,
  3424. llvm::function_ref<void(CodeGenFunction &)> FirstGen,
  3425. llvm::function_ref<void(CodeGenFunction &)> SecondGen) {
  3426. llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
  3427. NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
  3428. SmallVector<const Expr *, 4> Privates;
  3429. SmallVector<const Expr *, 4> ReductionOps;
  3430. SmallVector<const Expr *, 4> LHSs;
  3431. SmallVector<const Expr *, 4> RHSs;
  3432. SmallVector<const Expr *, 4> CopyArrayElems;
  3433. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  3434. assert(C->getModifier() == OMPC_REDUCTION_inscan &&
  3435. "Only inscan reductions are expected.");
  3436. Privates.append(C->privates().begin(), C->privates().end());
  3437. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  3438. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  3439. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  3440. CopyArrayElems.append(C->copy_array_elems().begin(),
  3441. C->copy_array_elems().end());
  3442. }
  3443. CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S);
  3444. {
  3445. // Emit loop with input phase:
  3446. // #pragma omp ...
  3447. // for (i: 0..<num_iters>) {
  3448. // <input phase>;
  3449. // buffer[i] = red;
  3450. // }
  3451. CGF.OMPFirstScanLoop = true;
  3452. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  3453. FirstGen(CGF);
  3454. }
  3455. // #pragma omp barrier // in parallel region
  3456. auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems,
  3457. &ReductionOps,
  3458. &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3459. Action.Enter(CGF);
  3460. // Emit prefix reduction:
  3461. // #pragma omp master // in parallel region
  3462. // for (int k = 0; k <= ceil(log2(n)); ++k)
  3463. llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock();
  3464. llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body");
  3465. llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit");
  3466. llvm::Function *F =
  3467. CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy);
  3468. llvm::Value *Arg =
  3469. CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy);
  3470. llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg);
  3471. F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy);
  3472. LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal);
  3473. LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy);
  3474. llvm::Value *NMin1 = CGF.Builder.CreateNUWSub(
  3475. OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1));
  3476. auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc());
  3477. CGF.EmitBlock(LoopBB);
  3478. auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2);
  3479. // size pow2k = 1;
  3480. auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
  3481. Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB);
  3482. Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB);
  3483. // for (size i = n - 1; i >= 2 ^ k; --i)
  3484. // tmp[i] op= tmp[i-pow2k];
  3485. llvm::BasicBlock *InnerLoopBB =
  3486. CGF.createBasicBlock("omp.inner.log.scan.body");
  3487. llvm::BasicBlock *InnerExitBB =
  3488. CGF.createBasicBlock("omp.inner.log.scan.exit");
  3489. llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K);
  3490. CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
  3491. CGF.EmitBlock(InnerLoopBB);
  3492. auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
  3493. IVal->addIncoming(NMin1, LoopBB);
  3494. {
  3495. CodeGenFunction::OMPPrivateScope PrivScope(CGF);
  3496. auto *ILHS = LHSs.begin();
  3497. auto *IRHS = RHSs.begin();
  3498. for (const Expr *CopyArrayElem : CopyArrayElems) {
  3499. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  3500. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  3501. Address LHSAddr = Address::invalid();
  3502. {
  3503. CodeGenFunction::OpaqueValueMapping IdxMapping(
  3504. CGF,
  3505. cast<OpaqueValueExpr>(
  3506. cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
  3507. RValue::get(IVal));
  3508. LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF);
  3509. }
  3510. PrivScope.addPrivate(LHSVD, LHSAddr);
  3511. Address RHSAddr = Address::invalid();
  3512. {
  3513. llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K);
  3514. CodeGenFunction::OpaqueValueMapping IdxMapping(
  3515. CGF,
  3516. cast<OpaqueValueExpr>(
  3517. cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
  3518. RValue::get(OffsetIVal));
  3519. RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF);
  3520. }
  3521. PrivScope.addPrivate(RHSVD, RHSAddr);
  3522. ++ILHS;
  3523. ++IRHS;
  3524. }
  3525. PrivScope.Privatize();
  3526. CGF.CGM.getOpenMPRuntime().emitReduction(
  3527. CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
  3528. {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown});
  3529. }
  3530. llvm::Value *NextIVal =
  3531. CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1));
  3532. IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock());
  3533. CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K);
  3534. CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
  3535. CGF.EmitBlock(InnerExitBB);
  3536. llvm::Value *Next =
  3537. CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1));
  3538. Counter->addIncoming(Next, CGF.Builder.GetInsertBlock());
  3539. // pow2k <<= 1;
  3540. llvm::Value *NextPow2K =
  3541. CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
  3542. Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock());
  3543. llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal);
  3544. CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
  3545. auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc());
  3546. CGF.EmitBlock(ExitBB);
  3547. };
  3548. if (isOpenMPParallelDirective(S.getDirectiveKind())) {
  3549. CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
  3550. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  3551. CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  3552. /*ForceSimpleCall=*/true);
  3553. } else {
  3554. RegionCodeGenTy RCG(CodeGen);
  3555. RCG(CGF);
  3556. }
  3557. CGF.OMPFirstScanLoop = false;
  3558. SecondGen(CGF);
  3559. }
  3560. static bool emitWorksharingDirective(CodeGenFunction &CGF,
  3561. const OMPLoopDirective &S,
  3562. bool HasCancel) {
  3563. bool HasLastprivates;
  3564. if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
  3565. [](const OMPReductionClause *C) {
  3566. return C->getModifier() == OMPC_REDUCTION_inscan;
  3567. })) {
  3568. const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
  3569. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  3570. OMPLoopScope LoopScope(CGF, S);
  3571. return CGF.EmitScalarExpr(S.getNumIterations());
  3572. };
  3573. const auto &&FirstGen = [&S, HasCancel](CodeGenFunction &CGF) {
  3574. CodeGenFunction::OMPCancelStackRAII CancelRegion(
  3575. CGF, S.getDirectiveKind(), HasCancel);
  3576. (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  3577. emitForLoopBounds,
  3578. emitDispatchForLoopBounds);
  3579. // Emit an implicit barrier at the end.
  3580. CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(),
  3581. OMPD_for);
  3582. };
  3583. const auto &&SecondGen = [&S, HasCancel,
  3584. &HasLastprivates](CodeGenFunction &CGF) {
  3585. CodeGenFunction::OMPCancelStackRAII CancelRegion(
  3586. CGF, S.getDirectiveKind(), HasCancel);
  3587. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  3588. emitForLoopBounds,
  3589. emitDispatchForLoopBounds);
  3590. };
  3591. if (!isOpenMPParallelDirective(S.getDirectiveKind()))
  3592. emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen);
  3593. emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen);
  3594. if (!isOpenMPParallelDirective(S.getDirectiveKind()))
  3595. emitScanBasedDirectiveFinals(CGF, S, NumIteratorsGen);
  3596. } else {
  3597. CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
  3598. HasCancel);
  3599. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  3600. emitForLoopBounds,
  3601. emitDispatchForLoopBounds);
  3602. }
  3603. return HasLastprivates;
  3604. }
  3605. static bool isSupportedByOpenMPIRBuilder(const OMPForDirective &S) {
  3606. if (S.hasCancel())
  3607. return false;
  3608. for (OMPClause *C : S.clauses()) {
  3609. if (isa<OMPNowaitClause>(C))
  3610. continue;
  3611. if (auto *SC = dyn_cast<OMPScheduleClause>(C)) {
  3612. if (SC->getFirstScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
  3613. return false;
  3614. if (SC->getSecondScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown)
  3615. return false;
  3616. switch (SC->getScheduleKind()) {
  3617. case OMPC_SCHEDULE_auto:
  3618. case OMPC_SCHEDULE_dynamic:
  3619. case OMPC_SCHEDULE_runtime:
  3620. case OMPC_SCHEDULE_guided:
  3621. case OMPC_SCHEDULE_static:
  3622. continue;
  3623. case OMPC_SCHEDULE_unknown:
  3624. return false;
  3625. }
  3626. }
  3627. return false;
  3628. }
  3629. return true;
  3630. }
  3631. static llvm::omp::ScheduleKind
  3632. convertClauseKindToSchedKind(OpenMPScheduleClauseKind ScheduleClauseKind) {
  3633. switch (ScheduleClauseKind) {
  3634. case OMPC_SCHEDULE_unknown:
  3635. return llvm::omp::OMP_SCHEDULE_Default;
  3636. case OMPC_SCHEDULE_auto:
  3637. return llvm::omp::OMP_SCHEDULE_Auto;
  3638. case OMPC_SCHEDULE_dynamic:
  3639. return llvm::omp::OMP_SCHEDULE_Dynamic;
  3640. case OMPC_SCHEDULE_guided:
  3641. return llvm::omp::OMP_SCHEDULE_Guided;
  3642. case OMPC_SCHEDULE_runtime:
  3643. return llvm::omp::OMP_SCHEDULE_Runtime;
  3644. case OMPC_SCHEDULE_static:
  3645. return llvm::omp::OMP_SCHEDULE_Static;
  3646. }
  3647. llvm_unreachable("Unhandled schedule kind");
  3648. }
  3649. void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
  3650. bool HasLastprivates = false;
  3651. bool UseOMPIRBuilder =
  3652. CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S);
  3653. auto &&CodeGen = [this, &S, &HasLastprivates,
  3654. UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) {
  3655. // Use the OpenMPIRBuilder if enabled.
  3656. if (UseOMPIRBuilder) {
  3657. bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>();
  3658. llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default;
  3659. llvm::Value *ChunkSize = nullptr;
  3660. if (auto *SchedClause = S.getSingleClause<OMPScheduleClause>()) {
  3661. SchedKind =
  3662. convertClauseKindToSchedKind(SchedClause->getScheduleKind());
  3663. if (const Expr *ChunkSizeExpr = SchedClause->getChunkSize())
  3664. ChunkSize = EmitScalarExpr(ChunkSizeExpr);
  3665. }
  3666. // Emit the associated statement and get its loop representation.
  3667. const Stmt *Inner = S.getRawStmt();
  3668. llvm::CanonicalLoopInfo *CLI =
  3669. EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
  3670. llvm::OpenMPIRBuilder &OMPBuilder =
  3671. CGM.getOpenMPRuntime().getOMPBuilder();
  3672. llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
  3673. AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
  3674. OMPBuilder.applyWorkshareLoop(
  3675. Builder.getCurrentDebugLocation(), CLI, AllocaIP, NeedsBarrier,
  3676. SchedKind, ChunkSize, /*HasSimdModifier=*/false,
  3677. /*HasMonotonicModifier=*/false, /*HasNonmonotonicModifier=*/false,
  3678. /*HasOrderedClause=*/false);
  3679. return;
  3680. }
  3681. HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel());
  3682. };
  3683. {
  3684. auto LPCRegion =
  3685. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  3686. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3687. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
  3688. S.hasCancel());
  3689. }
  3690. if (!UseOMPIRBuilder) {
  3691. // Emit an implicit barrier at the end.
  3692. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
  3693. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
  3694. }
  3695. // Check for outer lastprivate conditional update.
  3696. checkForLastprivateConditionalUpdate(*this, S);
  3697. }
  3698. void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
  3699. bool HasLastprivates = false;
  3700. auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
  3701. PrePostActionTy &) {
  3702. HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
  3703. };
  3704. {
  3705. auto LPCRegion =
  3706. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  3707. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3708. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  3709. }
  3710. // Emit an implicit barrier at the end.
  3711. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
  3712. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
  3713. // Check for outer lastprivate conditional update.
  3714. checkForLastprivateConditionalUpdate(*this, S);
  3715. }
  3716. static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
  3717. const Twine &Name,
  3718. llvm::Value *Init = nullptr) {
  3719. LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
  3720. if (Init)
  3721. CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
  3722. return LVal;
  3723. }
  3724. void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
  3725. const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
  3726. const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
  3727. bool HasLastprivates = false;
  3728. auto &&CodeGen = [&S, CapturedStmt, CS,
  3729. &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
  3730. const ASTContext &C = CGF.getContext();
  3731. QualType KmpInt32Ty =
  3732. C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  3733. // Emit helper vars inits.
  3734. LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
  3735. CGF.Builder.getInt32(0));
  3736. llvm::ConstantInt *GlobalUBVal = CS != nullptr
  3737. ? CGF.Builder.getInt32(CS->size() - 1)
  3738. : CGF.Builder.getInt32(0);
  3739. LValue UB =
  3740. createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
  3741. LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
  3742. CGF.Builder.getInt32(1));
  3743. LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
  3744. CGF.Builder.getInt32(0));
  3745. // Loop counter.
  3746. LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
  3747. OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
  3748. CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
  3749. OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
  3750. CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
  3751. // Generate condition for loop.
  3752. BinaryOperator *Cond = BinaryOperator::Create(
  3753. C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary,
  3754. S.getBeginLoc(), FPOptionsOverride());
  3755. // Increment for loop counter.
  3756. UnaryOperator *Inc = UnaryOperator::Create(
  3757. C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary,
  3758. S.getBeginLoc(), true, FPOptionsOverride());
  3759. auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
  3760. // Iterate through all sections and emit a switch construct:
  3761. // switch (IV) {
  3762. // case 0:
  3763. // <SectionStmt[0]>;
  3764. // break;
  3765. // ...
  3766. // case <NumSection> - 1:
  3767. // <SectionStmt[<NumSection> - 1]>;
  3768. // break;
  3769. // }
  3770. // .omp.sections.exit:
  3771. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
  3772. llvm::SwitchInst *SwitchStmt =
  3773. CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
  3774. ExitBB, CS == nullptr ? 1 : CS->size());
  3775. if (CS) {
  3776. unsigned CaseNumber = 0;
  3777. for (const Stmt *SubStmt : CS->children()) {
  3778. auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
  3779. CGF.EmitBlock(CaseBB);
  3780. SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
  3781. CGF.EmitStmt(SubStmt);
  3782. CGF.EmitBranch(ExitBB);
  3783. ++CaseNumber;
  3784. }
  3785. } else {
  3786. llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
  3787. CGF.EmitBlock(CaseBB);
  3788. SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
  3789. CGF.EmitStmt(CapturedStmt);
  3790. CGF.EmitBranch(ExitBB);
  3791. }
  3792. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  3793. };
  3794. CodeGenFunction::OMPPrivateScope LoopScope(CGF);
  3795. if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
  3796. // Emit implicit barrier to synchronize threads and avoid data races on
  3797. // initialization of firstprivate variables and post-update of lastprivate
  3798. // variables.
  3799. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  3800. CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  3801. /*ForceSimpleCall=*/true);
  3802. }
  3803. CGF.EmitOMPPrivateClause(S, LoopScope);
  3804. CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
  3805. HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  3806. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  3807. (void)LoopScope.Privatize();
  3808. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  3809. CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
  3810. // Emit static non-chunked loop.
  3811. OpenMPScheduleTy ScheduleKind;
  3812. ScheduleKind.Schedule = OMPC_SCHEDULE_static;
  3813. CGOpenMPRuntime::StaticRTInput StaticInit(
  3814. /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
  3815. LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
  3816. CGF.CGM.getOpenMPRuntime().emitForStaticInit(
  3817. CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
  3818. // UB = min(UB, GlobalUB);
  3819. llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
  3820. llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
  3821. CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
  3822. CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
  3823. // IV = LB;
  3824. CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
  3825. // while (idx <= UB) { BODY; ++idx; }
  3826. CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen,
  3827. [](CodeGenFunction &) {});
  3828. // Tell the runtime we are done.
  3829. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  3830. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  3831. S.getDirectiveKind());
  3832. };
  3833. CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
  3834. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  3835. // Emit post-update of the reduction variables if IsLastIter != 0.
  3836. emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
  3837. return CGF.Builder.CreateIsNotNull(
  3838. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3839. });
  3840. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  3841. if (HasLastprivates)
  3842. CGF.EmitOMPLastprivateClauseFinal(
  3843. S, /*NoFinals=*/false,
  3844. CGF.Builder.CreateIsNotNull(
  3845. CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
  3846. };
  3847. bool HasCancel = false;
  3848. if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
  3849. HasCancel = OSD->hasCancel();
  3850. else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
  3851. HasCancel = OPSD->hasCancel();
  3852. OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
  3853. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
  3854. HasCancel);
  3855. // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
  3856. // clause. Otherwise the barrier will be generated by the codegen for the
  3857. // directive.
  3858. if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
  3859. // Emit implicit barrier to synchronize threads and avoid data races on
  3860. // initialization of firstprivate variables.
  3861. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
  3862. OMPD_unknown);
  3863. }
  3864. }
  3865. void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
  3866. if (CGM.getLangOpts().OpenMPIRBuilder) {
  3867. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  3868. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  3869. using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
  3870. auto FiniCB = [this](InsertPointTy IP) {
  3871. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  3872. };
  3873. const CapturedStmt *ICS = S.getInnermostCapturedStmt();
  3874. const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
  3875. const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
  3876. llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
  3877. if (CS) {
  3878. for (const Stmt *SubStmt : CS->children()) {
  3879. auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
  3880. InsertPointTy CodeGenIP) {
  3881. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  3882. *this, SubStmt, AllocaIP, CodeGenIP, "section");
  3883. };
  3884. SectionCBVector.push_back(SectionCB);
  3885. }
  3886. } else {
  3887. auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
  3888. InsertPointTy CodeGenIP) {
  3889. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  3890. *this, CapturedStmt, AllocaIP, CodeGenIP, "section");
  3891. };
  3892. SectionCBVector.push_back(SectionCB);
  3893. }
  3894. // Privatization callback that performs appropriate action for
  3895. // shared/private/firstprivate/lastprivate/copyin/... variables.
  3896. //
  3897. // TODO: This defaults to shared right now.
  3898. auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
  3899. llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
  3900. // The next line is appropriate only for variables (Val) with the
  3901. // data-sharing attribute "shared".
  3902. ReplVal = &Val;
  3903. return CodeGenIP;
  3904. };
  3905. CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
  3906. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
  3907. llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
  3908. AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
  3909. Builder.restoreIP(OMPBuilder.createSections(
  3910. Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(),
  3911. S.getSingleClause<OMPNowaitClause>()));
  3912. return;
  3913. }
  3914. {
  3915. auto LPCRegion =
  3916. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  3917. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3918. EmitSections(S);
  3919. }
  3920. // Emit an implicit barrier at the end.
  3921. if (!S.getSingleClause<OMPNowaitClause>()) {
  3922. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
  3923. OMPD_sections);
  3924. }
  3925. // Check for outer lastprivate conditional update.
  3926. checkForLastprivateConditionalUpdate(*this, S);
  3927. }
  3928. void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
  3929. if (CGM.getLangOpts().OpenMPIRBuilder) {
  3930. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  3931. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  3932. const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt();
  3933. auto FiniCB = [this](InsertPointTy IP) {
  3934. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  3935. };
  3936. auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP,
  3937. InsertPointTy CodeGenIP) {
  3938. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  3939. *this, SectionRegionBodyStmt, AllocaIP, CodeGenIP, "section");
  3940. };
  3941. LexicalScope Scope(*this, S.getSourceRange());
  3942. EmitStopPoint(&S);
  3943. Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB));
  3944. return;
  3945. }
  3946. LexicalScope Scope(*this, S.getSourceRange());
  3947. EmitStopPoint(&S);
  3948. EmitStmt(S.getAssociatedStmt());
  3949. }
  3950. void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
  3951. llvm::SmallVector<const Expr *, 8> CopyprivateVars;
  3952. llvm::SmallVector<const Expr *, 8> DestExprs;
  3953. llvm::SmallVector<const Expr *, 8> SrcExprs;
  3954. llvm::SmallVector<const Expr *, 8> AssignmentOps;
  3955. // Check if there are any 'copyprivate' clauses associated with this
  3956. // 'single' construct.
  3957. // Build a list of copyprivate variables along with helper expressions
  3958. // (<source>, <destination>, <destination>=<source> expressions)
  3959. for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
  3960. CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
  3961. DestExprs.append(C->destination_exprs().begin(),
  3962. C->destination_exprs().end());
  3963. SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
  3964. AssignmentOps.append(C->assignment_ops().begin(),
  3965. C->assignment_ops().end());
  3966. }
  3967. // Emit code for 'single' region along with 'copyprivate' clauses
  3968. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3969. Action.Enter(CGF);
  3970. OMPPrivateScope SingleScope(CGF);
  3971. (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
  3972. CGF.EmitOMPPrivateClause(S, SingleScope);
  3973. (void)SingleScope.Privatize();
  3974. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  3975. };
  3976. {
  3977. auto LPCRegion =
  3978. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  3979. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3980. CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
  3981. CopyprivateVars, DestExprs,
  3982. SrcExprs, AssignmentOps);
  3983. }
  3984. // Emit an implicit barrier at the end (to avoid data race on firstprivate
  3985. // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
  3986. if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
  3987. CGM.getOpenMPRuntime().emitBarrierCall(
  3988. *this, S.getBeginLoc(),
  3989. S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
  3990. }
  3991. // Check for outer lastprivate conditional update.
  3992. checkForLastprivateConditionalUpdate(*this, S);
  3993. }
  3994. static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  3995. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3996. Action.Enter(CGF);
  3997. CGF.EmitStmt(S.getRawStmt());
  3998. };
  3999. CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
  4000. }
  4001. void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
  4002. if (CGM.getLangOpts().OpenMPIRBuilder) {
  4003. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  4004. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  4005. const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt();
  4006. auto FiniCB = [this](InsertPointTy IP) {
  4007. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  4008. };
  4009. auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP,
  4010. InsertPointTy CodeGenIP) {
  4011. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  4012. *this, MasterRegionBodyStmt, AllocaIP, CodeGenIP, "master");
  4013. };
  4014. LexicalScope Scope(*this, S.getSourceRange());
  4015. EmitStopPoint(&S);
  4016. Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
  4017. return;
  4018. }
  4019. LexicalScope Scope(*this, S.getSourceRange());
  4020. EmitStopPoint(&S);
  4021. emitMaster(*this, S);
  4022. }
  4023. static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  4024. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4025. Action.Enter(CGF);
  4026. CGF.EmitStmt(S.getRawStmt());
  4027. };
  4028. Expr *Filter = nullptr;
  4029. if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
  4030. Filter = FilterClause->getThreadID();
  4031. CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(),
  4032. Filter);
  4033. }
  4034. void CodeGenFunction::EmitOMPMaskedDirective(const OMPMaskedDirective &S) {
  4035. if (CGM.getLangOpts().OpenMPIRBuilder) {
  4036. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  4037. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  4038. const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt();
  4039. const Expr *Filter = nullptr;
  4040. if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
  4041. Filter = FilterClause->getThreadID();
  4042. llvm::Value *FilterVal = Filter
  4043. ? EmitScalarExpr(Filter, CGM.Int32Ty)
  4044. : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
  4045. auto FiniCB = [this](InsertPointTy IP) {
  4046. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  4047. };
  4048. auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP,
  4049. InsertPointTy CodeGenIP) {
  4050. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  4051. *this, MaskedRegionBodyStmt, AllocaIP, CodeGenIP, "masked");
  4052. };
  4053. LexicalScope Scope(*this, S.getSourceRange());
  4054. EmitStopPoint(&S);
  4055. Builder.restoreIP(
  4056. OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal));
  4057. return;
  4058. }
  4059. LexicalScope Scope(*this, S.getSourceRange());
  4060. EmitStopPoint(&S);
  4061. emitMasked(*this, S);
  4062. }
  4063. void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
  4064. if (CGM.getLangOpts().OpenMPIRBuilder) {
  4065. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  4066. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  4067. const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt();
  4068. const Expr *Hint = nullptr;
  4069. if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
  4070. Hint = HintClause->getHint();
  4071. // TODO: This is slightly different from what's currently being done in
  4072. // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
  4073. // about typing is final.
  4074. llvm::Value *HintInst = nullptr;
  4075. if (Hint)
  4076. HintInst =
  4077. Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
  4078. auto FiniCB = [this](InsertPointTy IP) {
  4079. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  4080. };
  4081. auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP,
  4082. InsertPointTy CodeGenIP) {
  4083. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  4084. *this, CriticalRegionBodyStmt, AllocaIP, CodeGenIP, "critical");
  4085. };
  4086. LexicalScope Scope(*this, S.getSourceRange());
  4087. EmitStopPoint(&S);
  4088. Builder.restoreIP(OMPBuilder.createCritical(
  4089. Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(),
  4090. HintInst));
  4091. return;
  4092. }
  4093. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4094. Action.Enter(CGF);
  4095. CGF.EmitStmt(S.getAssociatedStmt());
  4096. };
  4097. const Expr *Hint = nullptr;
  4098. if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
  4099. Hint = HintClause->getHint();
  4100. LexicalScope Scope(*this, S.getSourceRange());
  4101. EmitStopPoint(&S);
  4102. CGM.getOpenMPRuntime().emitCriticalRegion(*this,
  4103. S.getDirectiveName().getAsString(),
  4104. CodeGen, S.getBeginLoc(), Hint);
  4105. }
  4106. void CodeGenFunction::EmitOMPParallelForDirective(
  4107. const OMPParallelForDirective &S) {
  4108. // Emit directive as a combined directive that consists of two implicit
  4109. // directives: 'parallel' with 'for' directive.
  4110. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4111. Action.Enter(CGF);
  4112. emitOMPCopyinClause(CGF, S);
  4113. (void)emitWorksharingDirective(CGF, S, S.hasCancel());
  4114. };
  4115. {
  4116. const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
  4117. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  4118. CGCapturedStmtInfo CGSI(CR_OpenMP);
  4119. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
  4120. OMPLoopScope LoopScope(CGF, S);
  4121. return CGF.EmitScalarExpr(S.getNumIterations());
  4122. };
  4123. bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
  4124. [](const OMPReductionClause *C) {
  4125. return C->getModifier() == OMPC_REDUCTION_inscan;
  4126. });
  4127. if (IsInscan)
  4128. emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
  4129. auto LPCRegion =
  4130. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  4131. emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
  4132. emitEmptyBoundParameters);
  4133. if (IsInscan)
  4134. emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
  4135. }
  4136. // Check for outer lastprivate conditional update.
  4137. checkForLastprivateConditionalUpdate(*this, S);
  4138. }
  4139. void CodeGenFunction::EmitOMPParallelForSimdDirective(
  4140. const OMPParallelForSimdDirective &S) {
  4141. // Emit directive as a combined directive that consists of two implicit
  4142. // directives: 'parallel' with 'for' directive.
  4143. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4144. Action.Enter(CGF);
  4145. emitOMPCopyinClause(CGF, S);
  4146. (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
  4147. };
  4148. {
  4149. const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
  4150. CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
  4151. CGCapturedStmtInfo CGSI(CR_OpenMP);
  4152. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
  4153. OMPLoopScope LoopScope(CGF, S);
  4154. return CGF.EmitScalarExpr(S.getNumIterations());
  4155. };
  4156. bool IsInscan = llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
  4157. [](const OMPReductionClause *C) {
  4158. return C->getModifier() == OMPC_REDUCTION_inscan;
  4159. });
  4160. if (IsInscan)
  4161. emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
  4162. auto LPCRegion =
  4163. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  4164. emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen,
  4165. emitEmptyBoundParameters);
  4166. if (IsInscan)
  4167. emitScanBasedDirectiveFinals(*this, S, NumIteratorsGen);
  4168. }
  4169. // Check for outer lastprivate conditional update.
  4170. checkForLastprivateConditionalUpdate(*this, S);
  4171. }
  4172. void CodeGenFunction::EmitOMPParallelMasterDirective(
  4173. const OMPParallelMasterDirective &S) {
  4174. // Emit directive as a combined directive that consists of two implicit
  4175. // directives: 'parallel' with 'master' directive.
  4176. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4177. Action.Enter(CGF);
  4178. OMPPrivateScope PrivateScope(CGF);
  4179. emitOMPCopyinClause(CGF, S);
  4180. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  4181. CGF.EmitOMPPrivateClause(S, PrivateScope);
  4182. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4183. (void)PrivateScope.Privatize();
  4184. emitMaster(CGF, S);
  4185. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  4186. };
  4187. {
  4188. auto LPCRegion =
  4189. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  4190. emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
  4191. emitEmptyBoundParameters);
  4192. emitPostUpdateForReductionClause(*this, S,
  4193. [](CodeGenFunction &) { return nullptr; });
  4194. }
  4195. // Check for outer lastprivate conditional update.
  4196. checkForLastprivateConditionalUpdate(*this, S);
  4197. }
  4198. void CodeGenFunction::EmitOMPParallelSectionsDirective(
  4199. const OMPParallelSectionsDirective &S) {
  4200. // Emit directive as a combined directive that consists of two implicit
  4201. // directives: 'parallel' with 'sections' directive.
  4202. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4203. Action.Enter(CGF);
  4204. emitOMPCopyinClause(CGF, S);
  4205. CGF.EmitSections(S);
  4206. };
  4207. {
  4208. auto LPCRegion =
  4209. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  4210. emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
  4211. emitEmptyBoundParameters);
  4212. }
  4213. // Check for outer lastprivate conditional update.
  4214. checkForLastprivateConditionalUpdate(*this, S);
  4215. }
  4216. namespace {
  4217. /// Get the list of variables declared in the context of the untied tasks.
  4218. class CheckVarsEscapingUntiedTaskDeclContext final
  4219. : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> {
  4220. llvm::SmallVector<const VarDecl *, 4> PrivateDecls;
  4221. public:
  4222. explicit CheckVarsEscapingUntiedTaskDeclContext() = default;
  4223. virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default;
  4224. void VisitDeclStmt(const DeclStmt *S) {
  4225. if (!S)
  4226. return;
  4227. // Need to privatize only local vars, static locals can be processed as is.
  4228. for (const Decl *D : S->decls()) {
  4229. if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
  4230. if (VD->hasLocalStorage())
  4231. PrivateDecls.push_back(VD);
  4232. }
  4233. }
  4234. void VisitOMPExecutableDirective(const OMPExecutableDirective *) {}
  4235. void VisitCapturedStmt(const CapturedStmt *) {}
  4236. void VisitLambdaExpr(const LambdaExpr *) {}
  4237. void VisitBlockExpr(const BlockExpr *) {}
  4238. void VisitStmt(const Stmt *S) {
  4239. if (!S)
  4240. return;
  4241. for (const Stmt *Child : S->children())
  4242. if (Child)
  4243. Visit(Child);
  4244. }
  4245. /// Swaps list of vars with the provided one.
  4246. ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; }
  4247. };
  4248. } // anonymous namespace
  4249. static void buildDependences(const OMPExecutableDirective &S,
  4250. OMPTaskDataTy &Data) {
  4251. // First look for 'omp_all_memory' and add this first.
  4252. bool OmpAllMemory = false;
  4253. if (llvm::any_of(
  4254. S.getClausesOfKind<OMPDependClause>(), [](const OMPDependClause *C) {
  4255. return C->getDependencyKind() == OMPC_DEPEND_outallmemory ||
  4256. C->getDependencyKind() == OMPC_DEPEND_inoutallmemory;
  4257. })) {
  4258. OmpAllMemory = true;
  4259. // Since both OMPC_DEPEND_outallmemory and OMPC_DEPEND_inoutallmemory are
  4260. // equivalent to the runtime, always use OMPC_DEPEND_outallmemory to
  4261. // simplify.
  4262. OMPTaskDataTy::DependData &DD =
  4263. Data.Dependences.emplace_back(OMPC_DEPEND_outallmemory,
  4264. /*IteratorExpr=*/nullptr);
  4265. // Add a nullptr Expr to simplify the codegen in emitDependData.
  4266. DD.DepExprs.push_back(nullptr);
  4267. }
  4268. // Add remaining dependences skipping any 'out' or 'inout' if they are
  4269. // overridden by 'omp_all_memory'.
  4270. for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
  4271. OpenMPDependClauseKind Kind = C->getDependencyKind();
  4272. if (Kind == OMPC_DEPEND_outallmemory || Kind == OMPC_DEPEND_inoutallmemory)
  4273. continue;
  4274. if (OmpAllMemory && (Kind == OMPC_DEPEND_out || Kind == OMPC_DEPEND_inout))
  4275. continue;
  4276. OMPTaskDataTy::DependData &DD =
  4277. Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
  4278. DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
  4279. }
  4280. }
  4281. void CodeGenFunction::EmitOMPTaskBasedDirective(
  4282. const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
  4283. const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
  4284. OMPTaskDataTy &Data) {
  4285. // Emit outlined function for task construct.
  4286. const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
  4287. auto I = CS->getCapturedDecl()->param_begin();
  4288. auto PartId = std::next(I);
  4289. auto TaskT = std::next(I, 4);
  4290. // Check if the task is final
  4291. if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
  4292. // If the condition constant folds and can be elided, try to avoid emitting
  4293. // the condition and the dead arm of the if/else.
  4294. const Expr *Cond = Clause->getCondition();
  4295. bool CondConstant;
  4296. if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
  4297. Data.Final.setInt(CondConstant);
  4298. else
  4299. Data.Final.setPointer(EvaluateExprAsBool(Cond));
  4300. } else {
  4301. // By default the task is not final.
  4302. Data.Final.setInt(/*IntVal=*/false);
  4303. }
  4304. // Check if the task has 'priority' clause.
  4305. if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
  4306. const Expr *Prio = Clause->getPriority();
  4307. Data.Priority.setInt(/*IntVal=*/true);
  4308. Data.Priority.setPointer(EmitScalarConversion(
  4309. EmitScalarExpr(Prio), Prio->getType(),
  4310. getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
  4311. Prio->getExprLoc()));
  4312. }
  4313. // The first function argument for tasks is a thread id, the second one is a
  4314. // part id (0 for tied tasks, >=0 for untied task).
  4315. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  4316. // Get list of private variables.
  4317. for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
  4318. auto IRef = C->varlist_begin();
  4319. for (const Expr *IInit : C->private_copies()) {
  4320. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  4321. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  4322. Data.PrivateVars.push_back(*IRef);
  4323. Data.PrivateCopies.push_back(IInit);
  4324. }
  4325. ++IRef;
  4326. }
  4327. }
  4328. EmittedAsPrivate.clear();
  4329. // Get list of firstprivate variables.
  4330. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  4331. auto IRef = C->varlist_begin();
  4332. auto IElemInitRef = C->inits().begin();
  4333. for (const Expr *IInit : C->private_copies()) {
  4334. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  4335. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  4336. Data.FirstprivateVars.push_back(*IRef);
  4337. Data.FirstprivateCopies.push_back(IInit);
  4338. Data.FirstprivateInits.push_back(*IElemInitRef);
  4339. }
  4340. ++IRef;
  4341. ++IElemInitRef;
  4342. }
  4343. }
  4344. // Get list of lastprivate variables (for taskloops).
  4345. llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
  4346. for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
  4347. auto IRef = C->varlist_begin();
  4348. auto ID = C->destination_exprs().begin();
  4349. for (const Expr *IInit : C->private_copies()) {
  4350. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  4351. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  4352. Data.LastprivateVars.push_back(*IRef);
  4353. Data.LastprivateCopies.push_back(IInit);
  4354. }
  4355. LastprivateDstsOrigs.insert(
  4356. std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
  4357. cast<DeclRefExpr>(*IRef)));
  4358. ++IRef;
  4359. ++ID;
  4360. }
  4361. }
  4362. SmallVector<const Expr *, 4> LHSs;
  4363. SmallVector<const Expr *, 4> RHSs;
  4364. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  4365. Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
  4366. Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
  4367. Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
  4368. Data.ReductionOps.append(C->reduction_ops().begin(),
  4369. C->reduction_ops().end());
  4370. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  4371. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  4372. }
  4373. Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
  4374. *this, S.getBeginLoc(), LHSs, RHSs, Data);
  4375. // Build list of dependences.
  4376. buildDependences(S, Data);
  4377. // Get list of local vars for untied tasks.
  4378. if (!Data.Tied) {
  4379. CheckVarsEscapingUntiedTaskDeclContext Checker;
  4380. Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt());
  4381. Data.PrivateLocals.append(Checker.getPrivateDecls().begin(),
  4382. Checker.getPrivateDecls().end());
  4383. }
  4384. auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
  4385. CapturedRegion](CodeGenFunction &CGF,
  4386. PrePostActionTy &Action) {
  4387. llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
  4388. std::pair<Address, Address>>
  4389. UntiedLocalVars;
  4390. // Set proper addresses for generated private copies.
  4391. OMPPrivateScope Scope(CGF);
  4392. // Generate debug info for variables present in shared clause.
  4393. if (auto *DI = CGF.getDebugInfo()) {
  4394. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields =
  4395. CGF.CapturedStmtInfo->getCaptureFields();
  4396. llvm::Value *ContextValue = CGF.CapturedStmtInfo->getContextValue();
  4397. if (CaptureFields.size() && ContextValue) {
  4398. unsigned CharWidth = CGF.getContext().getCharWidth();
  4399. // The shared variables are packed together as members of structure.
  4400. // So the address of each shared variable can be computed by adding
  4401. // offset of it (within record) to the base address of record. For each
  4402. // shared variable, debug intrinsic llvm.dbg.declare is generated with
  4403. // appropriate expressions (DIExpression).
  4404. // Ex:
  4405. // %12 = load %struct.anon*, %struct.anon** %__context.addr.i
  4406. // call void @llvm.dbg.declare(metadata %struct.anon* %12,
  4407. // metadata !svar1,
  4408. // metadata !DIExpression(DW_OP_deref))
  4409. // call void @llvm.dbg.declare(metadata %struct.anon* %12,
  4410. // metadata !svar2,
  4411. // metadata !DIExpression(DW_OP_plus_uconst, 8, DW_OP_deref))
  4412. for (auto It = CaptureFields.begin(); It != CaptureFields.end(); ++It) {
  4413. const VarDecl *SharedVar = It->first;
  4414. RecordDecl *CaptureRecord = It->second->getParent();
  4415. const ASTRecordLayout &Layout =
  4416. CGF.getContext().getASTRecordLayout(CaptureRecord);
  4417. unsigned Offset =
  4418. Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth;
  4419. if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
  4420. (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue,
  4421. CGF.Builder, false);
  4422. llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back();
  4423. // Get the call dbg.declare instruction we just created and update
  4424. // its DIExpression to add offset to base address.
  4425. if (auto DDI = dyn_cast<llvm::DbgVariableIntrinsic>(&Last)) {
  4426. SmallVector<uint64_t, 8> Ops;
  4427. // Add offset to the base address if non zero.
  4428. if (Offset) {
  4429. Ops.push_back(llvm::dwarf::DW_OP_plus_uconst);
  4430. Ops.push_back(Offset);
  4431. }
  4432. Ops.push_back(llvm::dwarf::DW_OP_deref);
  4433. auto &Ctx = DDI->getContext();
  4434. llvm::DIExpression *DIExpr = llvm::DIExpression::get(Ctx, Ops);
  4435. Last.setOperand(2, llvm::MetadataAsValue::get(Ctx, DIExpr));
  4436. }
  4437. }
  4438. }
  4439. }
  4440. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs;
  4441. if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
  4442. !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) {
  4443. enum { PrivatesParam = 2, CopyFnParam = 3 };
  4444. llvm::Value *CopyFn = CGF.Builder.CreateLoad(
  4445. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
  4446. llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
  4447. CS->getCapturedDecl()->getParam(PrivatesParam)));
  4448. // Map privates.
  4449. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
  4450. llvm::SmallVector<llvm::Value *, 16> CallArgs;
  4451. llvm::SmallVector<llvm::Type *, 4> ParamTypes;
  4452. CallArgs.push_back(PrivatesPtr);
  4453. ParamTypes.push_back(PrivatesPtr->getType());
  4454. for (const Expr *E : Data.PrivateVars) {
  4455. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4456. Address PrivatePtr = CGF.CreateMemTemp(
  4457. CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
  4458. PrivatePtrs.emplace_back(VD, PrivatePtr);
  4459. CallArgs.push_back(PrivatePtr.getPointer());
  4460. ParamTypes.push_back(PrivatePtr.getType());
  4461. }
  4462. for (const Expr *E : Data.FirstprivateVars) {
  4463. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4464. Address PrivatePtr =
  4465. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  4466. ".firstpriv.ptr.addr");
  4467. PrivatePtrs.emplace_back(VD, PrivatePtr);
  4468. FirstprivatePtrs.emplace_back(VD, PrivatePtr);
  4469. CallArgs.push_back(PrivatePtr.getPointer());
  4470. ParamTypes.push_back(PrivatePtr.getType());
  4471. }
  4472. for (const Expr *E : Data.LastprivateVars) {
  4473. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4474. Address PrivatePtr =
  4475. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  4476. ".lastpriv.ptr.addr");
  4477. PrivatePtrs.emplace_back(VD, PrivatePtr);
  4478. CallArgs.push_back(PrivatePtr.getPointer());
  4479. ParamTypes.push_back(PrivatePtr.getType());
  4480. }
  4481. for (const VarDecl *VD : Data.PrivateLocals) {
  4482. QualType Ty = VD->getType().getNonReferenceType();
  4483. if (VD->getType()->isLValueReferenceType())
  4484. Ty = CGF.getContext().getPointerType(Ty);
  4485. if (isAllocatableDecl(VD))
  4486. Ty = CGF.getContext().getPointerType(Ty);
  4487. Address PrivatePtr = CGF.CreateMemTemp(
  4488. CGF.getContext().getPointerType(Ty), ".local.ptr.addr");
  4489. auto Result = UntiedLocalVars.insert(
  4490. std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid())));
  4491. // If key exists update in place.
  4492. if (Result.second == false)
  4493. *Result.first = std::make_pair(
  4494. VD, std::make_pair(PrivatePtr, Address::invalid()));
  4495. CallArgs.push_back(PrivatePtr.getPointer());
  4496. ParamTypes.push_back(PrivatePtr.getType());
  4497. }
  4498. auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
  4499. ParamTypes, /*isVarArg=*/false);
  4500. CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4501. CopyFn, CopyFnTy->getPointerTo());
  4502. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  4503. CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
  4504. for (const auto &Pair : LastprivateDstsOrigs) {
  4505. const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
  4506. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
  4507. /*RefersToEnclosingVariableOrCapture=*/
  4508. CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
  4509. Pair.second->getType(), VK_LValue,
  4510. Pair.second->getExprLoc());
  4511. Scope.addPrivate(Pair.first, CGF.EmitLValue(&DRE).getAddress(CGF));
  4512. }
  4513. for (const auto &Pair : PrivatePtrs) {
  4514. Address Replacement = Address(
  4515. CGF.Builder.CreateLoad(Pair.second),
  4516. CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
  4517. CGF.getContext().getDeclAlign(Pair.first));
  4518. Scope.addPrivate(Pair.first, Replacement);
  4519. if (auto *DI = CGF.getDebugInfo())
  4520. if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
  4521. (void)DI->EmitDeclareOfAutoVariable(
  4522. Pair.first, Pair.second.getPointer(), CGF.Builder,
  4523. /*UsePointerValue*/ true);
  4524. }
  4525. // Adjust mapping for internal locals by mapping actual memory instead of
  4526. // a pointer to this memory.
  4527. for (auto &Pair : UntiedLocalVars) {
  4528. QualType VDType = Pair.first->getType().getNonReferenceType();
  4529. if (isAllocatableDecl(Pair.first)) {
  4530. llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
  4531. Address Replacement(
  4532. Ptr,
  4533. CGF.ConvertTypeForMem(CGF.getContext().getPointerType(VDType)),
  4534. CGF.getPointerAlign());
  4535. Pair.second.first = Replacement;
  4536. Ptr = CGF.Builder.CreateLoad(Replacement);
  4537. Replacement = Address(Ptr, CGF.ConvertTypeForMem(VDType),
  4538. CGF.getContext().getDeclAlign(Pair.first));
  4539. Pair.second.second = Replacement;
  4540. } else {
  4541. llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
  4542. Address Replacement(Ptr, CGF.ConvertTypeForMem(VDType),
  4543. CGF.getContext().getDeclAlign(Pair.first));
  4544. Pair.second.first = Replacement;
  4545. }
  4546. }
  4547. }
  4548. if (Data.Reductions) {
  4549. OMPPrivateScope FirstprivateScope(CGF);
  4550. for (const auto &Pair : FirstprivatePtrs) {
  4551. Address Replacement(
  4552. CGF.Builder.CreateLoad(Pair.second),
  4553. CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
  4554. CGF.getContext().getDeclAlign(Pair.first));
  4555. FirstprivateScope.addPrivate(Pair.first, Replacement);
  4556. }
  4557. (void)FirstprivateScope.Privatize();
  4558. OMPLexicalScope LexScope(CGF, S, CapturedRegion);
  4559. ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
  4560. Data.ReductionCopies, Data.ReductionOps);
  4561. llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
  4562. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
  4563. for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
  4564. RedCG.emitSharedOrigLValue(CGF, Cnt);
  4565. RedCG.emitAggregateType(CGF, Cnt);
  4566. // FIXME: This must removed once the runtime library is fixed.
  4567. // Emit required threadprivate variables for
  4568. // initializer/combiner/finalizer.
  4569. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  4570. RedCG, Cnt);
  4571. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  4572. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  4573. Replacement =
  4574. Address(CGF.EmitScalarConversion(
  4575. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  4576. CGF.getContext().getPointerType(
  4577. Data.ReductionCopies[Cnt]->getType()),
  4578. Data.ReductionCopies[Cnt]->getExprLoc()),
  4579. CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
  4580. Replacement.getAlignment());
  4581. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  4582. Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
  4583. }
  4584. }
  4585. // Privatize all private variables except for in_reduction items.
  4586. (void)Scope.Privatize();
  4587. SmallVector<const Expr *, 4> InRedVars;
  4588. SmallVector<const Expr *, 4> InRedPrivs;
  4589. SmallVector<const Expr *, 4> InRedOps;
  4590. SmallVector<const Expr *, 4> TaskgroupDescriptors;
  4591. for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
  4592. auto IPriv = C->privates().begin();
  4593. auto IRed = C->reduction_ops().begin();
  4594. auto ITD = C->taskgroup_descriptors().begin();
  4595. for (const Expr *Ref : C->varlists()) {
  4596. InRedVars.emplace_back(Ref);
  4597. InRedPrivs.emplace_back(*IPriv);
  4598. InRedOps.emplace_back(*IRed);
  4599. TaskgroupDescriptors.emplace_back(*ITD);
  4600. std::advance(IPriv, 1);
  4601. std::advance(IRed, 1);
  4602. std::advance(ITD, 1);
  4603. }
  4604. }
  4605. // Privatize in_reduction items here, because taskgroup descriptors must be
  4606. // privatized earlier.
  4607. OMPPrivateScope InRedScope(CGF);
  4608. if (!InRedVars.empty()) {
  4609. ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
  4610. for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
  4611. RedCG.emitSharedOrigLValue(CGF, Cnt);
  4612. RedCG.emitAggregateType(CGF, Cnt);
  4613. // The taskgroup descriptor variable is always implicit firstprivate and
  4614. // privatized already during processing of the firstprivates.
  4615. // FIXME: This must removed once the runtime library is fixed.
  4616. // Emit required threadprivate variables for
  4617. // initializer/combiner/finalizer.
  4618. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  4619. RedCG, Cnt);
  4620. llvm::Value *ReductionsPtr;
  4621. if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
  4622. ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr),
  4623. TRExpr->getExprLoc());
  4624. } else {
  4625. ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4626. }
  4627. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  4628. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  4629. Replacement = Address(
  4630. CGF.EmitScalarConversion(
  4631. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  4632. CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
  4633. InRedPrivs[Cnt]->getExprLoc()),
  4634. CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
  4635. Replacement.getAlignment());
  4636. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  4637. InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
  4638. }
  4639. }
  4640. (void)InRedScope.Privatize();
  4641. CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF,
  4642. UntiedLocalVars);
  4643. Action.Enter(CGF);
  4644. BodyGen(CGF);
  4645. };
  4646. llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
  4647. S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
  4648. Data.NumberOfParts);
  4649. OMPLexicalScope Scope(*this, S, std::nullopt,
  4650. !isOpenMPParallelDirective(S.getDirectiveKind()) &&
  4651. !isOpenMPSimdDirective(S.getDirectiveKind()));
  4652. TaskGen(*this, OutlinedFn, Data);
  4653. }
  4654. static ImplicitParamDecl *
  4655. createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
  4656. QualType Ty, CapturedDecl *CD,
  4657. SourceLocation Loc) {
  4658. auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
  4659. ImplicitParamDecl::Other);
  4660. auto *OrigRef = DeclRefExpr::Create(
  4661. C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
  4662. /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
  4663. auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
  4664. ImplicitParamDecl::Other);
  4665. auto *PrivateRef = DeclRefExpr::Create(
  4666. C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
  4667. /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
  4668. QualType ElemType = C.getBaseElementType(Ty);
  4669. auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
  4670. ImplicitParamDecl::Other);
  4671. auto *InitRef = DeclRefExpr::Create(
  4672. C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
  4673. /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
  4674. PrivateVD->setInitStyle(VarDecl::CInit);
  4675. PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
  4676. InitRef, /*BasePath=*/nullptr,
  4677. VK_PRValue, FPOptionsOverride()));
  4678. Data.FirstprivateVars.emplace_back(OrigRef);
  4679. Data.FirstprivateCopies.emplace_back(PrivateRef);
  4680. Data.FirstprivateInits.emplace_back(InitRef);
  4681. return OrigVD;
  4682. }
  4683. void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
  4684. const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
  4685. OMPTargetDataInfo &InputInfo) {
  4686. // Emit outlined function for task construct.
  4687. const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
  4688. Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
  4689. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  4690. auto I = CS->getCapturedDecl()->param_begin();
  4691. auto PartId = std::next(I);
  4692. auto TaskT = std::next(I, 4);
  4693. OMPTaskDataTy Data;
  4694. // The task is not final.
  4695. Data.Final.setInt(/*IntVal=*/false);
  4696. // Get list of firstprivate variables.
  4697. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  4698. auto IRef = C->varlist_begin();
  4699. auto IElemInitRef = C->inits().begin();
  4700. for (auto *IInit : C->private_copies()) {
  4701. Data.FirstprivateVars.push_back(*IRef);
  4702. Data.FirstprivateCopies.push_back(IInit);
  4703. Data.FirstprivateInits.push_back(*IElemInitRef);
  4704. ++IRef;
  4705. ++IElemInitRef;
  4706. }
  4707. }
  4708. SmallVector<const Expr *, 4> LHSs;
  4709. SmallVector<const Expr *, 4> RHSs;
  4710. for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
  4711. Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
  4712. Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
  4713. Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
  4714. Data.ReductionOps.append(C->reduction_ops().begin(),
  4715. C->reduction_ops().end());
  4716. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  4717. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  4718. }
  4719. OMPPrivateScope TargetScope(*this);
  4720. VarDecl *BPVD = nullptr;
  4721. VarDecl *PVD = nullptr;
  4722. VarDecl *SVD = nullptr;
  4723. VarDecl *MVD = nullptr;
  4724. if (InputInfo.NumberOfTargetItems > 0) {
  4725. auto *CD = CapturedDecl::Create(
  4726. getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
  4727. llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
  4728. QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType(
  4729. getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
  4730. /*IndexTypeQuals=*/0);
  4731. BPVD = createImplicitFirstprivateForType(
  4732. getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
  4733. PVD = createImplicitFirstprivateForType(
  4734. getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
  4735. QualType SizesType = getContext().getConstantArrayType(
  4736. getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
  4737. ArrSize, nullptr, ArrayType::Normal,
  4738. /*IndexTypeQuals=*/0);
  4739. SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
  4740. S.getBeginLoc());
  4741. TargetScope.addPrivate(BPVD, InputInfo.BasePointersArray);
  4742. TargetScope.addPrivate(PVD, InputInfo.PointersArray);
  4743. TargetScope.addPrivate(SVD, InputInfo.SizesArray);
  4744. // If there is no user-defined mapper, the mapper array will be nullptr. In
  4745. // this case, we don't need to privatize it.
  4746. if (!isa_and_nonnull<llvm::ConstantPointerNull>(
  4747. InputInfo.MappersArray.getPointer())) {
  4748. MVD = createImplicitFirstprivateForType(
  4749. getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
  4750. TargetScope.addPrivate(MVD, InputInfo.MappersArray);
  4751. }
  4752. }
  4753. (void)TargetScope.Privatize();
  4754. buildDependences(S, Data);
  4755. auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD,
  4756. &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4757. // Set proper addresses for generated private copies.
  4758. OMPPrivateScope Scope(CGF);
  4759. if (!Data.FirstprivateVars.empty()) {
  4760. enum { PrivatesParam = 2, CopyFnParam = 3 };
  4761. llvm::Value *CopyFn = CGF.Builder.CreateLoad(
  4762. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
  4763. llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
  4764. CS->getCapturedDecl()->getParam(PrivatesParam)));
  4765. // Map privates.
  4766. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
  4767. llvm::SmallVector<llvm::Value *, 16> CallArgs;
  4768. llvm::SmallVector<llvm::Type *, 4> ParamTypes;
  4769. CallArgs.push_back(PrivatesPtr);
  4770. ParamTypes.push_back(PrivatesPtr->getType());
  4771. for (const Expr *E : Data.FirstprivateVars) {
  4772. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4773. Address PrivatePtr =
  4774. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  4775. ".firstpriv.ptr.addr");
  4776. PrivatePtrs.emplace_back(VD, PrivatePtr);
  4777. CallArgs.push_back(PrivatePtr.getPointer());
  4778. ParamTypes.push_back(PrivatePtr.getType());
  4779. }
  4780. auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
  4781. ParamTypes, /*isVarArg=*/false);
  4782. CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4783. CopyFn, CopyFnTy->getPointerTo());
  4784. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  4785. CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
  4786. for (const auto &Pair : PrivatePtrs) {
  4787. Address Replacement(
  4788. CGF.Builder.CreateLoad(Pair.second),
  4789. CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()),
  4790. CGF.getContext().getDeclAlign(Pair.first));
  4791. Scope.addPrivate(Pair.first, Replacement);
  4792. }
  4793. }
  4794. CGF.processInReduction(S, Data, CGF, CS, Scope);
  4795. if (InputInfo.NumberOfTargetItems > 0) {
  4796. InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
  4797. CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
  4798. InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
  4799. CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
  4800. InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
  4801. CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
  4802. // If MVD is nullptr, the mapper array is not privatized
  4803. if (MVD)
  4804. InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
  4805. CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
  4806. }
  4807. Action.Enter(CGF);
  4808. OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
  4809. BodyGen(CGF);
  4810. };
  4811. llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
  4812. S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
  4813. Data.NumberOfParts);
  4814. llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
  4815. IntegerLiteral IfCond(getContext(), TrueOrFalse,
  4816. getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  4817. SourceLocation());
  4818. CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
  4819. SharedsTy, CapturedStruct, &IfCond, Data);
  4820. }
  4821. void CodeGenFunction::processInReduction(const OMPExecutableDirective &S,
  4822. OMPTaskDataTy &Data,
  4823. CodeGenFunction &CGF,
  4824. const CapturedStmt *CS,
  4825. OMPPrivateScope &Scope) {
  4826. if (Data.Reductions) {
  4827. OpenMPDirectiveKind CapturedRegion = S.getDirectiveKind();
  4828. OMPLexicalScope LexScope(CGF, S, CapturedRegion);
  4829. ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
  4830. Data.ReductionCopies, Data.ReductionOps);
  4831. llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
  4832. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(4)));
  4833. for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
  4834. RedCG.emitSharedOrigLValue(CGF, Cnt);
  4835. RedCG.emitAggregateType(CGF, Cnt);
  4836. // FIXME: This must removed once the runtime library is fixed.
  4837. // Emit required threadprivate variables for
  4838. // initializer/combiner/finalizer.
  4839. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  4840. RedCG, Cnt);
  4841. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  4842. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  4843. Replacement =
  4844. Address(CGF.EmitScalarConversion(
  4845. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  4846. CGF.getContext().getPointerType(
  4847. Data.ReductionCopies[Cnt]->getType()),
  4848. Data.ReductionCopies[Cnt]->getExprLoc()),
  4849. CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()),
  4850. Replacement.getAlignment());
  4851. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  4852. Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
  4853. }
  4854. }
  4855. (void)Scope.Privatize();
  4856. SmallVector<const Expr *, 4> InRedVars;
  4857. SmallVector<const Expr *, 4> InRedPrivs;
  4858. SmallVector<const Expr *, 4> InRedOps;
  4859. SmallVector<const Expr *, 4> TaskgroupDescriptors;
  4860. for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
  4861. auto IPriv = C->privates().begin();
  4862. auto IRed = C->reduction_ops().begin();
  4863. auto ITD = C->taskgroup_descriptors().begin();
  4864. for (const Expr *Ref : C->varlists()) {
  4865. InRedVars.emplace_back(Ref);
  4866. InRedPrivs.emplace_back(*IPriv);
  4867. InRedOps.emplace_back(*IRed);
  4868. TaskgroupDescriptors.emplace_back(*ITD);
  4869. std::advance(IPriv, 1);
  4870. std::advance(IRed, 1);
  4871. std::advance(ITD, 1);
  4872. }
  4873. }
  4874. OMPPrivateScope InRedScope(CGF);
  4875. if (!InRedVars.empty()) {
  4876. ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
  4877. for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
  4878. RedCG.emitSharedOrigLValue(CGF, Cnt);
  4879. RedCG.emitAggregateType(CGF, Cnt);
  4880. // FIXME: This must removed once the runtime library is fixed.
  4881. // Emit required threadprivate variables for
  4882. // initializer/combiner/finalizer.
  4883. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  4884. RedCG, Cnt);
  4885. llvm::Value *ReductionsPtr;
  4886. if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
  4887. ReductionsPtr =
  4888. CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), TRExpr->getExprLoc());
  4889. } else {
  4890. ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4891. }
  4892. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  4893. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  4894. Replacement = Address(
  4895. CGF.EmitScalarConversion(
  4896. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  4897. CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
  4898. InRedPrivs[Cnt]->getExprLoc()),
  4899. CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()),
  4900. Replacement.getAlignment());
  4901. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  4902. InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement);
  4903. }
  4904. }
  4905. (void)InRedScope.Privatize();
  4906. }
  4907. void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
  4908. // Emit outlined function for task construct.
  4909. const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
  4910. Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
  4911. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  4912. const Expr *IfCond = nullptr;
  4913. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  4914. if (C->getNameModifier() == OMPD_unknown ||
  4915. C->getNameModifier() == OMPD_task) {
  4916. IfCond = C->getCondition();
  4917. break;
  4918. }
  4919. }
  4920. OMPTaskDataTy Data;
  4921. // Check if we should emit tied or untied task.
  4922. Data.Tied = !S.getSingleClause<OMPUntiedClause>();
  4923. auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
  4924. CGF.EmitStmt(CS->getCapturedStmt());
  4925. };
  4926. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  4927. IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
  4928. const OMPTaskDataTy &Data) {
  4929. CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
  4930. SharedsTy, CapturedStruct, IfCond,
  4931. Data);
  4932. };
  4933. auto LPCRegion =
  4934. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  4935. EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
  4936. }
  4937. void CodeGenFunction::EmitOMPTaskyieldDirective(
  4938. const OMPTaskyieldDirective &S) {
  4939. CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
  4940. }
  4941. void CodeGenFunction::EmitOMPErrorDirective(const OMPErrorDirective &S) {
  4942. const OMPMessageClause *MC = S.getSingleClause<OMPMessageClause>();
  4943. Expr *ME = MC ? MC->getMessageString() : nullptr;
  4944. const OMPSeverityClause *SC = S.getSingleClause<OMPSeverityClause>();
  4945. bool IsFatal = false;
  4946. if (!SC || SC->getSeverityKind() == OMPC_SEVERITY_fatal)
  4947. IsFatal = true;
  4948. CGM.getOpenMPRuntime().emitErrorCall(*this, S.getBeginLoc(), ME, IsFatal);
  4949. }
  4950. void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
  4951. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
  4952. }
  4953. void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
  4954. OMPTaskDataTy Data;
  4955. // Build list of dependences
  4956. buildDependences(S, Data);
  4957. Data.HasNowaitClause = S.hasClausesOfKind<OMPNowaitClause>();
  4958. CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc(), Data);
  4959. }
  4960. bool isSupportedByOpenMPIRBuilder(const OMPTaskgroupDirective &T) {
  4961. return T.clauses().empty();
  4962. }
  4963. void CodeGenFunction::EmitOMPTaskgroupDirective(
  4964. const OMPTaskgroupDirective &S) {
  4965. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  4966. if (CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S)) {
  4967. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  4968. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  4969. InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
  4970. AllocaInsertPt->getIterator());
  4971. auto BodyGenCB = [&, this](InsertPointTy AllocaIP,
  4972. InsertPointTy CodeGenIP) {
  4973. Builder.restoreIP(CodeGenIP);
  4974. EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  4975. };
  4976. CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
  4977. if (!CapturedStmtInfo)
  4978. CapturedStmtInfo = &CapStmtInfo;
  4979. Builder.restoreIP(OMPBuilder.createTaskgroup(Builder, AllocaIP, BodyGenCB));
  4980. return;
  4981. }
  4982. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4983. Action.Enter(CGF);
  4984. if (const Expr *E = S.getReductionRef()) {
  4985. SmallVector<const Expr *, 4> LHSs;
  4986. SmallVector<const Expr *, 4> RHSs;
  4987. OMPTaskDataTy Data;
  4988. for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
  4989. Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
  4990. Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
  4991. Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
  4992. Data.ReductionOps.append(C->reduction_ops().begin(),
  4993. C->reduction_ops().end());
  4994. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  4995. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  4996. }
  4997. llvm::Value *ReductionDesc =
  4998. CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
  4999. LHSs, RHSs, Data);
  5000. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  5001. CGF.EmitVarDecl(*VD);
  5002. CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
  5003. /*Volatile=*/false, E->getType());
  5004. }
  5005. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  5006. };
  5007. CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
  5008. }
  5009. void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
  5010. llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
  5011. ? llvm::AtomicOrdering::NotAtomic
  5012. : llvm::AtomicOrdering::AcquireRelease;
  5013. CGM.getOpenMPRuntime().emitFlush(
  5014. *this,
  5015. [&S]() -> ArrayRef<const Expr *> {
  5016. if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
  5017. return llvm::ArrayRef(FlushClause->varlist_begin(),
  5018. FlushClause->varlist_end());
  5019. return std::nullopt;
  5020. }(),
  5021. S.getBeginLoc(), AO);
  5022. }
  5023. void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) {
  5024. const auto *DO = S.getSingleClause<OMPDepobjClause>();
  5025. LValue DOLVal = EmitLValue(DO->getDepobj());
  5026. if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
  5027. OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
  5028. DC->getModifier());
  5029. Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
  5030. Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause(
  5031. *this, Dependencies, DC->getBeginLoc());
  5032. EmitStoreOfScalar(DepAddr.getPointer(), DOLVal);
  5033. return;
  5034. }
  5035. if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) {
  5036. CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc());
  5037. return;
  5038. }
  5039. if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) {
  5040. CGM.getOpenMPRuntime().emitUpdateClause(
  5041. *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc());
  5042. return;
  5043. }
  5044. }
  5045. void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) {
  5046. if (!OMPParentLoopDirectiveForScan)
  5047. return;
  5048. const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan;
  5049. bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>();
  5050. SmallVector<const Expr *, 4> Shareds;
  5051. SmallVector<const Expr *, 4> Privates;
  5052. SmallVector<const Expr *, 4> LHSs;
  5053. SmallVector<const Expr *, 4> RHSs;
  5054. SmallVector<const Expr *, 4> ReductionOps;
  5055. SmallVector<const Expr *, 4> CopyOps;
  5056. SmallVector<const Expr *, 4> CopyArrayTemps;
  5057. SmallVector<const Expr *, 4> CopyArrayElems;
  5058. for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) {
  5059. if (C->getModifier() != OMPC_REDUCTION_inscan)
  5060. continue;
  5061. Shareds.append(C->varlist_begin(), C->varlist_end());
  5062. Privates.append(C->privates().begin(), C->privates().end());
  5063. LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  5064. RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  5065. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  5066. CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
  5067. CopyArrayTemps.append(C->copy_array_temps().begin(),
  5068. C->copy_array_temps().end());
  5069. CopyArrayElems.append(C->copy_array_elems().begin(),
  5070. C->copy_array_elems().end());
  5071. }
  5072. if (ParentDir.getDirectiveKind() == OMPD_simd ||
  5073. (getLangOpts().OpenMPSimd &&
  5074. isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) {
  5075. // For simd directive and simd-based directives in simd only mode, use the
  5076. // following codegen:
  5077. // int x = 0;
  5078. // #pragma omp simd reduction(inscan, +: x)
  5079. // for (..) {
  5080. // <first part>
  5081. // #pragma omp scan inclusive(x)
  5082. // <second part>
  5083. // }
  5084. // is transformed to:
  5085. // int x = 0;
  5086. // for (..) {
  5087. // int x_priv = 0;
  5088. // <first part>
  5089. // x = x_priv + x;
  5090. // x_priv = x;
  5091. // <second part>
  5092. // }
  5093. // and
  5094. // int x = 0;
  5095. // #pragma omp simd reduction(inscan, +: x)
  5096. // for (..) {
  5097. // <first part>
  5098. // #pragma omp scan exclusive(x)
  5099. // <second part>
  5100. // }
  5101. // to
  5102. // int x = 0;
  5103. // for (..) {
  5104. // int x_priv = 0;
  5105. // <second part>
  5106. // int temp = x;
  5107. // x = x_priv + x;
  5108. // x_priv = temp;
  5109. // <first part>
  5110. // }
  5111. llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce");
  5112. EmitBranch(IsInclusive
  5113. ? OMPScanReduce
  5114. : BreakContinueStack.back().ContinueBlock.getBlock());
  5115. EmitBlock(OMPScanDispatch);
  5116. {
  5117. // New scope for correct construction/destruction of temp variables for
  5118. // exclusive scan.
  5119. LexicalScope Scope(*this, S.getSourceRange());
  5120. EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock);
  5121. EmitBlock(OMPScanReduce);
  5122. if (!IsInclusive) {
  5123. // Create temp var and copy LHS value to this temp value.
  5124. // TMP = LHS;
  5125. for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
  5126. const Expr *PrivateExpr = Privates[I];
  5127. const Expr *TempExpr = CopyArrayTemps[I];
  5128. EmitAutoVarDecl(
  5129. *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl()));
  5130. LValue DestLVal = EmitLValue(TempExpr);
  5131. LValue SrcLVal = EmitLValue(LHSs[I]);
  5132. EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
  5133. SrcLVal.getAddress(*this),
  5134. cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
  5135. cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
  5136. CopyOps[I]);
  5137. }
  5138. }
  5139. CGM.getOpenMPRuntime().emitReduction(
  5140. *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
  5141. {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd});
  5142. for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
  5143. const Expr *PrivateExpr = Privates[I];
  5144. LValue DestLVal;
  5145. LValue SrcLVal;
  5146. if (IsInclusive) {
  5147. DestLVal = EmitLValue(RHSs[I]);
  5148. SrcLVal = EmitLValue(LHSs[I]);
  5149. } else {
  5150. const Expr *TempExpr = CopyArrayTemps[I];
  5151. DestLVal = EmitLValue(RHSs[I]);
  5152. SrcLVal = EmitLValue(TempExpr);
  5153. }
  5154. EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
  5155. SrcLVal.getAddress(*this),
  5156. cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
  5157. cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
  5158. CopyOps[I]);
  5159. }
  5160. }
  5161. EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock);
  5162. OMPScanExitBlock = IsInclusive
  5163. ? BreakContinueStack.back().ContinueBlock.getBlock()
  5164. : OMPScanReduce;
  5165. EmitBlock(OMPAfterScanBlock);
  5166. return;
  5167. }
  5168. if (!IsInclusive) {
  5169. EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
  5170. EmitBlock(OMPScanExitBlock);
  5171. }
  5172. if (OMPFirstScanLoop) {
  5173. // Emit buffer[i] = red; at the end of the input phase.
  5174. const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
  5175. .getIterationVariable()
  5176. ->IgnoreParenImpCasts();
  5177. LValue IdxLVal = EmitLValue(IVExpr);
  5178. llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
  5179. IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
  5180. for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
  5181. const Expr *PrivateExpr = Privates[I];
  5182. const Expr *OrigExpr = Shareds[I];
  5183. const Expr *CopyArrayElem = CopyArrayElems[I];
  5184. OpaqueValueMapping IdxMapping(
  5185. *this,
  5186. cast<OpaqueValueExpr>(
  5187. cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
  5188. RValue::get(IdxVal));
  5189. LValue DestLVal = EmitLValue(CopyArrayElem);
  5190. LValue SrcLVal = EmitLValue(OrigExpr);
  5191. EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
  5192. SrcLVal.getAddress(*this),
  5193. cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
  5194. cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
  5195. CopyOps[I]);
  5196. }
  5197. }
  5198. EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
  5199. if (IsInclusive) {
  5200. EmitBlock(OMPScanExitBlock);
  5201. EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
  5202. }
  5203. EmitBlock(OMPScanDispatch);
  5204. if (!OMPFirstScanLoop) {
  5205. // Emit red = buffer[i]; at the entrance to the scan phase.
  5206. const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
  5207. .getIterationVariable()
  5208. ->IgnoreParenImpCasts();
  5209. LValue IdxLVal = EmitLValue(IVExpr);
  5210. llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
  5211. IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
  5212. llvm::BasicBlock *ExclusiveExitBB = nullptr;
  5213. if (!IsInclusive) {
  5214. llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec");
  5215. ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit");
  5216. llvm::Value *Cmp = Builder.CreateIsNull(IdxVal);
  5217. Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB);
  5218. EmitBlock(ContBB);
  5219. // Use idx - 1 iteration for exclusive scan.
  5220. IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1));
  5221. }
  5222. for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
  5223. const Expr *PrivateExpr = Privates[I];
  5224. const Expr *OrigExpr = Shareds[I];
  5225. const Expr *CopyArrayElem = CopyArrayElems[I];
  5226. OpaqueValueMapping IdxMapping(
  5227. *this,
  5228. cast<OpaqueValueExpr>(
  5229. cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
  5230. RValue::get(IdxVal));
  5231. LValue SrcLVal = EmitLValue(CopyArrayElem);
  5232. LValue DestLVal = EmitLValue(OrigExpr);
  5233. EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
  5234. SrcLVal.getAddress(*this),
  5235. cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
  5236. cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
  5237. CopyOps[I]);
  5238. }
  5239. if (!IsInclusive) {
  5240. EmitBlock(ExclusiveExitBB);
  5241. }
  5242. }
  5243. EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock
  5244. : OMPAfterScanBlock);
  5245. EmitBlock(OMPAfterScanBlock);
  5246. }
  5247. void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
  5248. const CodeGenLoopTy &CodeGenLoop,
  5249. Expr *IncExpr) {
  5250. // Emit the loop iteration variable.
  5251. const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  5252. const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
  5253. EmitVarDecl(*IVDecl);
  5254. // Emit the iterations count variable.
  5255. // If it is not a variable, Sema decided to calculate iterations count on each
  5256. // iteration (e.g., it is foldable into a constant).
  5257. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  5258. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  5259. // Emit calculation of the iterations count.
  5260. EmitIgnoredExpr(S.getCalcLastIteration());
  5261. }
  5262. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  5263. bool HasLastprivateClause = false;
  5264. // Check pre-condition.
  5265. {
  5266. OMPLoopScope PreInitScope(*this, S);
  5267. // Skip the entire loop if we don't meet the precondition.
  5268. // If the condition constant folds and can be elided, avoid emitting the
  5269. // whole loop.
  5270. bool CondConstant;
  5271. llvm::BasicBlock *ContBlock = nullptr;
  5272. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  5273. if (!CondConstant)
  5274. return;
  5275. } else {
  5276. llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
  5277. ContBlock = createBasicBlock("omp.precond.end");
  5278. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  5279. getProfileCount(&S));
  5280. EmitBlock(ThenBlock);
  5281. incrementProfileCounter(&S);
  5282. }
  5283. emitAlignedClause(*this, S);
  5284. // Emit 'then' code.
  5285. {
  5286. // Emit helper vars inits.
  5287. LValue LB = EmitOMPHelperVar(
  5288. *this, cast<DeclRefExpr>(
  5289. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  5290. ? S.getCombinedLowerBoundVariable()
  5291. : S.getLowerBoundVariable())));
  5292. LValue UB = EmitOMPHelperVar(
  5293. *this, cast<DeclRefExpr>(
  5294. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  5295. ? S.getCombinedUpperBoundVariable()
  5296. : S.getUpperBoundVariable())));
  5297. LValue ST =
  5298. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  5299. LValue IL =
  5300. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  5301. OMPPrivateScope LoopScope(*this);
  5302. if (EmitOMPFirstprivateClause(S, LoopScope)) {
  5303. // Emit implicit barrier to synchronize threads and avoid data races
  5304. // on initialization of firstprivate variables and post-update of
  5305. // lastprivate variables.
  5306. CGM.getOpenMPRuntime().emitBarrierCall(
  5307. *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  5308. /*ForceSimpleCall=*/true);
  5309. }
  5310. EmitOMPPrivateClause(S, LoopScope);
  5311. if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
  5312. !isOpenMPParallelDirective(S.getDirectiveKind()) &&
  5313. !isOpenMPTeamsDirective(S.getDirectiveKind()))
  5314. EmitOMPReductionClauseInit(S, LoopScope);
  5315. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  5316. EmitOMPPrivateLoopCounters(S, LoopScope);
  5317. (void)LoopScope.Privatize();
  5318. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  5319. CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
  5320. // Detect the distribute schedule kind and chunk.
  5321. llvm::Value *Chunk = nullptr;
  5322. OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
  5323. if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
  5324. ScheduleKind = C->getDistScheduleKind();
  5325. if (const Expr *Ch = C->getChunkSize()) {
  5326. Chunk = EmitScalarExpr(Ch);
  5327. Chunk = EmitScalarConversion(Chunk, Ch->getType(),
  5328. S.getIterationVariable()->getType(),
  5329. S.getBeginLoc());
  5330. }
  5331. } else {
  5332. // Default behaviour for dist_schedule clause.
  5333. CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
  5334. *this, S, ScheduleKind, Chunk);
  5335. }
  5336. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  5337. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  5338. // OpenMP [2.10.8, distribute Construct, Description]
  5339. // If dist_schedule is specified, kind must be static. If specified,
  5340. // iterations are divided into chunks of size chunk_size, chunks are
  5341. // assigned to the teams of the league in a round-robin fashion in the
  5342. // order of the team number. When no chunk_size is specified, the
  5343. // iteration space is divided into chunks that are approximately equal
  5344. // in size, and at most one chunk is distributed to each team of the
  5345. // league. The size of the chunks is unspecified in this case.
  5346. bool StaticChunked =
  5347. RT.isStaticChunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
  5348. isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
  5349. if (RT.isStaticNonchunked(ScheduleKind,
  5350. /* Chunked */ Chunk != nullptr) ||
  5351. StaticChunked) {
  5352. CGOpenMPRuntime::StaticRTInput StaticInit(
  5353. IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
  5354. LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
  5355. StaticChunked ? Chunk : nullptr);
  5356. RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
  5357. StaticInit);
  5358. JumpDest LoopExit =
  5359. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  5360. // UB = min(UB, GlobalUB);
  5361. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  5362. ? S.getCombinedEnsureUpperBound()
  5363. : S.getEnsureUpperBound());
  5364. // IV = LB;
  5365. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  5366. ? S.getCombinedInit()
  5367. : S.getInit());
  5368. const Expr *Cond =
  5369. isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  5370. ? S.getCombinedCond()
  5371. : S.getCond();
  5372. if (StaticChunked)
  5373. Cond = S.getCombinedDistCond();
  5374. // For static unchunked schedules generate:
  5375. //
  5376. // 1. For distribute alone, codegen
  5377. // while (idx <= UB) {
  5378. // BODY;
  5379. // ++idx;
  5380. // }
  5381. //
  5382. // 2. When combined with 'for' (e.g. as in 'distribute parallel for')
  5383. // while (idx <= UB) {
  5384. // <CodeGen rest of pragma>(LB, UB);
  5385. // idx += ST;
  5386. // }
  5387. //
  5388. // For static chunk one schedule generate:
  5389. //
  5390. // while (IV <= GlobalUB) {
  5391. // <CodeGen rest of pragma>(LB, UB);
  5392. // LB += ST;
  5393. // UB += ST;
  5394. // UB = min(UB, GlobalUB);
  5395. // IV = LB;
  5396. // }
  5397. //
  5398. emitCommonSimdLoop(
  5399. *this, S,
  5400. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  5401. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  5402. CGF.EmitOMPSimdInit(S);
  5403. },
  5404. [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
  5405. StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
  5406. CGF.EmitOMPInnerLoop(
  5407. S, LoopScope.requiresCleanups(), Cond, IncExpr,
  5408. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  5409. CodeGenLoop(CGF, S, LoopExit);
  5410. },
  5411. [&S, StaticChunked](CodeGenFunction &CGF) {
  5412. if (StaticChunked) {
  5413. CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
  5414. CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
  5415. CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
  5416. CGF.EmitIgnoredExpr(S.getCombinedInit());
  5417. }
  5418. });
  5419. });
  5420. EmitBlock(LoopExit.getBlock());
  5421. // Tell the runtime we are done.
  5422. RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
  5423. } else {
  5424. // Emit the outer loop, which requests its work chunk [LB..UB] from
  5425. // runtime and runs the inner loop to process it.
  5426. const OMPLoopArguments LoopArguments = {
  5427. LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
  5428. IL.getAddress(*this), Chunk};
  5429. EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
  5430. CodeGenLoop);
  5431. }
  5432. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  5433. EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
  5434. return CGF.Builder.CreateIsNotNull(
  5435. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  5436. });
  5437. }
  5438. if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
  5439. !isOpenMPParallelDirective(S.getDirectiveKind()) &&
  5440. !isOpenMPTeamsDirective(S.getDirectiveKind())) {
  5441. EmitOMPReductionClauseFinal(S, OMPD_simd);
  5442. // Emit post-update of the reduction variables if IsLastIter != 0.
  5443. emitPostUpdateForReductionClause(
  5444. *this, S, [IL, &S](CodeGenFunction &CGF) {
  5445. return CGF.Builder.CreateIsNotNull(
  5446. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  5447. });
  5448. }
  5449. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  5450. if (HasLastprivateClause) {
  5451. EmitOMPLastprivateClauseFinal(
  5452. S, /*NoFinals=*/false,
  5453. Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
  5454. }
  5455. }
  5456. // We're now done with the loop, so jump to the continuation block.
  5457. if (ContBlock) {
  5458. EmitBranch(ContBlock);
  5459. EmitBlock(ContBlock, true);
  5460. }
  5461. }
  5462. }
  5463. void CodeGenFunction::EmitOMPDistributeDirective(
  5464. const OMPDistributeDirective &S) {
  5465. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  5466. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  5467. };
  5468. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  5469. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  5470. }
  5471. static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
  5472. const CapturedStmt *S,
  5473. SourceLocation Loc) {
  5474. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  5475. CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
  5476. CGF.CapturedStmtInfo = &CapStmtInfo;
  5477. llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
  5478. Fn->setDoesNotRecurse();
  5479. return Fn;
  5480. }
  5481. void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
  5482. if (CGM.getLangOpts().OpenMPIRBuilder) {
  5483. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  5484. using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
  5485. if (S.hasClausesOfKind<OMPDependClause>()) {
  5486. // The ordered directive with depend clause.
  5487. assert(!S.hasAssociatedStmt() &&
  5488. "No associated statement must be in ordered depend construct.");
  5489. InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
  5490. AllocaInsertPt->getIterator());
  5491. for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) {
  5492. unsigned NumLoops = DC->getNumLoops();
  5493. QualType Int64Ty = CGM.getContext().getIntTypeForBitwidth(
  5494. /*DestWidth=*/64, /*Signed=*/1);
  5495. llvm::SmallVector<llvm::Value *> StoreValues;
  5496. for (unsigned I = 0; I < NumLoops; I++) {
  5497. const Expr *CounterVal = DC->getLoopData(I);
  5498. assert(CounterVal);
  5499. llvm::Value *StoreValue = EmitScalarConversion(
  5500. EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
  5501. CounterVal->getExprLoc());
  5502. StoreValues.emplace_back(StoreValue);
  5503. }
  5504. bool IsDependSource = false;
  5505. if (DC->getDependencyKind() == OMPC_DEPEND_source)
  5506. IsDependSource = true;
  5507. Builder.restoreIP(OMPBuilder.createOrderedDepend(
  5508. Builder, AllocaIP, NumLoops, StoreValues, ".cnt.addr",
  5509. IsDependSource));
  5510. }
  5511. } else {
  5512. // The ordered directive with threads or simd clause, or without clause.
  5513. // Without clause, it behaves as if the threads clause is specified.
  5514. const auto *C = S.getSingleClause<OMPSIMDClause>();
  5515. auto FiniCB = [this](InsertPointTy IP) {
  5516. OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
  5517. };
  5518. auto BodyGenCB = [&S, C, this](InsertPointTy AllocaIP,
  5519. InsertPointTy CodeGenIP) {
  5520. Builder.restoreIP(CodeGenIP);
  5521. const CapturedStmt *CS = S.getInnermostCapturedStmt();
  5522. if (C) {
  5523. llvm::BasicBlock *FiniBB = splitBBWithSuffix(
  5524. Builder, /*CreateBranch=*/false, ".ordered.after");
  5525. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  5526. GenerateOpenMPCapturedVars(*CS, CapturedVars);
  5527. llvm::Function *OutlinedFn =
  5528. emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
  5529. assert(S.getBeginLoc().isValid() &&
  5530. "Outlined function call location must be valid.");
  5531. ApplyDebugLocation::CreateDefaultArtificial(*this, S.getBeginLoc());
  5532. OMPBuilderCBHelpers::EmitCaptureStmt(*this, CodeGenIP, *FiniBB,
  5533. OutlinedFn, CapturedVars);
  5534. } else {
  5535. OMPBuilderCBHelpers::EmitOMPInlinedRegionBody(
  5536. *this, CS->getCapturedStmt(), AllocaIP, CodeGenIP, "ordered");
  5537. }
  5538. };
  5539. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  5540. Builder.restoreIP(
  5541. OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, !C));
  5542. }
  5543. return;
  5544. }
  5545. if (S.hasClausesOfKind<OMPDependClause>()) {
  5546. assert(!S.hasAssociatedStmt() &&
  5547. "No associated statement must be in ordered depend construct.");
  5548. for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
  5549. CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
  5550. return;
  5551. }
  5552. const auto *C = S.getSingleClause<OMPSIMDClause>();
  5553. auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
  5554. PrePostActionTy &Action) {
  5555. const CapturedStmt *CS = S.getInnermostCapturedStmt();
  5556. if (C) {
  5557. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  5558. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  5559. llvm::Function *OutlinedFn =
  5560. emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
  5561. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
  5562. OutlinedFn, CapturedVars);
  5563. } else {
  5564. Action.Enter(CGF);
  5565. CGF.EmitStmt(CS->getCapturedStmt());
  5566. }
  5567. };
  5568. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  5569. CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
  5570. }
  5571. static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
  5572. QualType SrcType, QualType DestType,
  5573. SourceLocation Loc) {
  5574. assert(CGF.hasScalarEvaluationKind(DestType) &&
  5575. "DestType must have scalar evaluation kind.");
  5576. assert(!Val.isAggregate() && "Must be a scalar or complex.");
  5577. return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
  5578. DestType, Loc)
  5579. : CGF.EmitComplexToScalarConversion(
  5580. Val.getComplexVal(), SrcType, DestType, Loc);
  5581. }
  5582. static CodeGenFunction::ComplexPairTy
  5583. convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
  5584. QualType DestType, SourceLocation Loc) {
  5585. assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
  5586. "DestType must have complex evaluation kind.");
  5587. CodeGenFunction::ComplexPairTy ComplexVal;
  5588. if (Val.isScalar()) {
  5589. // Convert the input element to the element type of the complex.
  5590. QualType DestElementType =
  5591. DestType->castAs<ComplexType>()->getElementType();
  5592. llvm::Value *ScalarVal = CGF.EmitScalarConversion(
  5593. Val.getScalarVal(), SrcType, DestElementType, Loc);
  5594. ComplexVal = CodeGenFunction::ComplexPairTy(
  5595. ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
  5596. } else {
  5597. assert(Val.isComplex() && "Must be a scalar or complex.");
  5598. QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
  5599. QualType DestElementType =
  5600. DestType->castAs<ComplexType>()->getElementType();
  5601. ComplexVal.first = CGF.EmitScalarConversion(
  5602. Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
  5603. ComplexVal.second = CGF.EmitScalarConversion(
  5604. Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
  5605. }
  5606. return ComplexVal;
  5607. }
  5608. static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
  5609. LValue LVal, RValue RVal) {
  5610. if (LVal.isGlobalReg())
  5611. CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
  5612. else
  5613. CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
  5614. }
  5615. static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF,
  5616. llvm::AtomicOrdering AO, LValue LVal,
  5617. SourceLocation Loc) {
  5618. if (LVal.isGlobalReg())
  5619. return CGF.EmitLoadOfLValue(LVal, Loc);
  5620. return CGF.EmitAtomicLoad(
  5621. LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
  5622. LVal.isVolatile());
  5623. }
  5624. void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
  5625. QualType RValTy, SourceLocation Loc) {
  5626. switch (getEvaluationKind(LVal.getType())) {
  5627. case TEK_Scalar:
  5628. EmitStoreThroughLValue(RValue::get(convertToScalarValue(
  5629. *this, RVal, RValTy, LVal.getType(), Loc)),
  5630. LVal);
  5631. break;
  5632. case TEK_Complex:
  5633. EmitStoreOfComplex(
  5634. convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
  5635. /*isInit=*/false);
  5636. break;
  5637. case TEK_Aggregate:
  5638. llvm_unreachable("Must be a scalar or complex.");
  5639. }
  5640. }
  5641. static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
  5642. const Expr *X, const Expr *V,
  5643. SourceLocation Loc) {
  5644. // v = x;
  5645. assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
  5646. assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
  5647. LValue XLValue = CGF.EmitLValue(X);
  5648. LValue VLValue = CGF.EmitLValue(V);
  5649. RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
  5650. // OpenMP, 2.17.7, atomic Construct
  5651. // If the read or capture clause is specified and the acquire, acq_rel, or
  5652. // seq_cst clause is specified then the strong flush on exit from the atomic
  5653. // operation is also an acquire flush.
  5654. switch (AO) {
  5655. case llvm::AtomicOrdering::Acquire:
  5656. case llvm::AtomicOrdering::AcquireRelease:
  5657. case llvm::AtomicOrdering::SequentiallyConsistent:
  5658. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
  5659. llvm::AtomicOrdering::Acquire);
  5660. break;
  5661. case llvm::AtomicOrdering::Monotonic:
  5662. case llvm::AtomicOrdering::Release:
  5663. break;
  5664. case llvm::AtomicOrdering::NotAtomic:
  5665. case llvm::AtomicOrdering::Unordered:
  5666. llvm_unreachable("Unexpected ordering.");
  5667. }
  5668. CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
  5669. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
  5670. }
  5671. static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF,
  5672. llvm::AtomicOrdering AO, const Expr *X,
  5673. const Expr *E, SourceLocation Loc) {
  5674. // x = expr;
  5675. assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
  5676. emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
  5677. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
  5678. // OpenMP, 2.17.7, atomic Construct
  5679. // If the write, update, or capture clause is specified and the release,
  5680. // acq_rel, or seq_cst clause is specified then the strong flush on entry to
  5681. // the atomic operation is also a release flush.
  5682. switch (AO) {
  5683. case llvm::AtomicOrdering::Release:
  5684. case llvm::AtomicOrdering::AcquireRelease:
  5685. case llvm::AtomicOrdering::SequentiallyConsistent:
  5686. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
  5687. llvm::AtomicOrdering::Release);
  5688. break;
  5689. case llvm::AtomicOrdering::Acquire:
  5690. case llvm::AtomicOrdering::Monotonic:
  5691. break;
  5692. case llvm::AtomicOrdering::NotAtomic:
  5693. case llvm::AtomicOrdering::Unordered:
  5694. llvm_unreachable("Unexpected ordering.");
  5695. }
  5696. }
  5697. static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
  5698. RValue Update,
  5699. BinaryOperatorKind BO,
  5700. llvm::AtomicOrdering AO,
  5701. bool IsXLHSInRHSPart) {
  5702. ASTContext &Context = CGF.getContext();
  5703. // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
  5704. // expression is simple and atomic is allowed for the given type for the
  5705. // target platform.
  5706. if (BO == BO_Comma || !Update.isScalar() || !X.isSimple() ||
  5707. (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
  5708. (Update.getScalarVal()->getType() !=
  5709. X.getAddress(CGF).getElementType())) ||
  5710. !Context.getTargetInfo().hasBuiltinAtomic(
  5711. Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
  5712. return std::make_pair(false, RValue::get(nullptr));
  5713. auto &&CheckAtomicSupport = [&CGF](llvm::Type *T, BinaryOperatorKind BO) {
  5714. if (T->isIntegerTy())
  5715. return true;
  5716. if (T->isFloatingPointTy() && (BO == BO_Add || BO == BO_Sub))
  5717. return llvm::isPowerOf2_64(CGF.CGM.getDataLayout().getTypeStoreSize(T));
  5718. return false;
  5719. };
  5720. if (!CheckAtomicSupport(Update.getScalarVal()->getType(), BO) ||
  5721. !CheckAtomicSupport(X.getAddress(CGF).getElementType(), BO))
  5722. return std::make_pair(false, RValue::get(nullptr));
  5723. bool IsInteger = X.getAddress(CGF).getElementType()->isIntegerTy();
  5724. llvm::AtomicRMWInst::BinOp RMWOp;
  5725. switch (BO) {
  5726. case BO_Add:
  5727. RMWOp = IsInteger ? llvm::AtomicRMWInst::Add : llvm::AtomicRMWInst::FAdd;
  5728. break;
  5729. case BO_Sub:
  5730. if (!IsXLHSInRHSPart)
  5731. return std::make_pair(false, RValue::get(nullptr));
  5732. RMWOp = IsInteger ? llvm::AtomicRMWInst::Sub : llvm::AtomicRMWInst::FSub;
  5733. break;
  5734. case BO_And:
  5735. RMWOp = llvm::AtomicRMWInst::And;
  5736. break;
  5737. case BO_Or:
  5738. RMWOp = llvm::AtomicRMWInst::Or;
  5739. break;
  5740. case BO_Xor:
  5741. RMWOp = llvm::AtomicRMWInst::Xor;
  5742. break;
  5743. case BO_LT:
  5744. if (IsInteger)
  5745. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  5746. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
  5747. : llvm::AtomicRMWInst::Max)
  5748. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
  5749. : llvm::AtomicRMWInst::UMax);
  5750. else
  5751. RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMin
  5752. : llvm::AtomicRMWInst::FMax;
  5753. break;
  5754. case BO_GT:
  5755. if (IsInteger)
  5756. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  5757. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
  5758. : llvm::AtomicRMWInst::Min)
  5759. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
  5760. : llvm::AtomicRMWInst::UMin);
  5761. else
  5762. RMWOp = IsXLHSInRHSPart ? llvm::AtomicRMWInst::FMax
  5763. : llvm::AtomicRMWInst::FMin;
  5764. break;
  5765. case BO_Assign:
  5766. RMWOp = llvm::AtomicRMWInst::Xchg;
  5767. break;
  5768. case BO_Mul:
  5769. case BO_Div:
  5770. case BO_Rem:
  5771. case BO_Shl:
  5772. case BO_Shr:
  5773. case BO_LAnd:
  5774. case BO_LOr:
  5775. return std::make_pair(false, RValue::get(nullptr));
  5776. case BO_PtrMemD:
  5777. case BO_PtrMemI:
  5778. case BO_LE:
  5779. case BO_GE:
  5780. case BO_EQ:
  5781. case BO_NE:
  5782. case BO_Cmp:
  5783. case BO_AddAssign:
  5784. case BO_SubAssign:
  5785. case BO_AndAssign:
  5786. case BO_OrAssign:
  5787. case BO_XorAssign:
  5788. case BO_MulAssign:
  5789. case BO_DivAssign:
  5790. case BO_RemAssign:
  5791. case BO_ShlAssign:
  5792. case BO_ShrAssign:
  5793. case BO_Comma:
  5794. llvm_unreachable("Unsupported atomic update operation");
  5795. }
  5796. llvm::Value *UpdateVal = Update.getScalarVal();
  5797. if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
  5798. if (IsInteger)
  5799. UpdateVal = CGF.Builder.CreateIntCast(
  5800. IC, X.getAddress(CGF).getElementType(),
  5801. X.getType()->hasSignedIntegerRepresentation());
  5802. else
  5803. UpdateVal = CGF.Builder.CreateCast(llvm::Instruction::CastOps::UIToFP, IC,
  5804. X.getAddress(CGF).getElementType());
  5805. }
  5806. llvm::Value *Res =
  5807. CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
  5808. return std::make_pair(true, RValue::get(Res));
  5809. }
  5810. std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
  5811. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  5812. llvm::AtomicOrdering AO, SourceLocation Loc,
  5813. const llvm::function_ref<RValue(RValue)> CommonGen) {
  5814. // Update expressions are allowed to have the following forms:
  5815. // x binop= expr; -> xrval + expr;
  5816. // x++, ++x -> xrval + 1;
  5817. // x--, --x -> xrval - 1;
  5818. // x = x binop expr; -> xrval binop expr
  5819. // x = expr Op x; - > expr binop xrval;
  5820. auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
  5821. if (!Res.first) {
  5822. if (X.isGlobalReg()) {
  5823. // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
  5824. // 'xrval'.
  5825. EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
  5826. } else {
  5827. // Perform compare-and-swap procedure.
  5828. EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
  5829. }
  5830. }
  5831. return Res;
  5832. }
  5833. static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF,
  5834. llvm::AtomicOrdering AO, const Expr *X,
  5835. const Expr *E, const Expr *UE,
  5836. bool IsXLHSInRHSPart, SourceLocation Loc) {
  5837. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  5838. "Update expr in 'atomic update' must be a binary operator.");
  5839. const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  5840. // Update expressions are allowed to have the following forms:
  5841. // x binop= expr; -> xrval + expr;
  5842. // x++, ++x -> xrval + 1;
  5843. // x--, --x -> xrval - 1;
  5844. // x = x binop expr; -> xrval binop expr
  5845. // x = expr Op x; - > expr binop xrval;
  5846. assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
  5847. LValue XLValue = CGF.EmitLValue(X);
  5848. RValue ExprRValue = CGF.EmitAnyExpr(E);
  5849. const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  5850. const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  5851. const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  5852. const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  5853. auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
  5854. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  5855. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  5856. return CGF.EmitAnyExpr(UE);
  5857. };
  5858. (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
  5859. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  5860. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
  5861. // OpenMP, 2.17.7, atomic Construct
  5862. // If the write, update, or capture clause is specified and the release,
  5863. // acq_rel, or seq_cst clause is specified then the strong flush on entry to
  5864. // the atomic operation is also a release flush.
  5865. switch (AO) {
  5866. case llvm::AtomicOrdering::Release:
  5867. case llvm::AtomicOrdering::AcquireRelease:
  5868. case llvm::AtomicOrdering::SequentiallyConsistent:
  5869. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
  5870. llvm::AtomicOrdering::Release);
  5871. break;
  5872. case llvm::AtomicOrdering::Acquire:
  5873. case llvm::AtomicOrdering::Monotonic:
  5874. break;
  5875. case llvm::AtomicOrdering::NotAtomic:
  5876. case llvm::AtomicOrdering::Unordered:
  5877. llvm_unreachable("Unexpected ordering.");
  5878. }
  5879. }
  5880. static RValue convertToType(CodeGenFunction &CGF, RValue Value,
  5881. QualType SourceType, QualType ResType,
  5882. SourceLocation Loc) {
  5883. switch (CGF.getEvaluationKind(ResType)) {
  5884. case TEK_Scalar:
  5885. return RValue::get(
  5886. convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
  5887. case TEK_Complex: {
  5888. auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
  5889. return RValue::getComplex(Res.first, Res.second);
  5890. }
  5891. case TEK_Aggregate:
  5892. break;
  5893. }
  5894. llvm_unreachable("Must be a scalar or complex.");
  5895. }
  5896. static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF,
  5897. llvm::AtomicOrdering AO,
  5898. bool IsPostfixUpdate, const Expr *V,
  5899. const Expr *X, const Expr *E,
  5900. const Expr *UE, bool IsXLHSInRHSPart,
  5901. SourceLocation Loc) {
  5902. assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
  5903. assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
  5904. RValue NewVVal;
  5905. LValue VLValue = CGF.EmitLValue(V);
  5906. LValue XLValue = CGF.EmitLValue(X);
  5907. RValue ExprRValue = CGF.EmitAnyExpr(E);
  5908. QualType NewVValType;
  5909. if (UE) {
  5910. // 'x' is updated with some additional value.
  5911. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  5912. "Update expr in 'atomic capture' must be a binary operator.");
  5913. const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  5914. // Update expressions are allowed to have the following forms:
  5915. // x binop= expr; -> xrval + expr;
  5916. // x++, ++x -> xrval + 1;
  5917. // x--, --x -> xrval - 1;
  5918. // x = x binop expr; -> xrval binop expr
  5919. // x = expr Op x; - > expr binop xrval;
  5920. const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  5921. const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  5922. const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  5923. NewVValType = XRValExpr->getType();
  5924. const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  5925. auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
  5926. IsPostfixUpdate](RValue XRValue) {
  5927. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  5928. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  5929. RValue Res = CGF.EmitAnyExpr(UE);
  5930. NewVVal = IsPostfixUpdate ? XRValue : Res;
  5931. return Res;
  5932. };
  5933. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  5934. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  5935. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
  5936. if (Res.first) {
  5937. // 'atomicrmw' instruction was generated.
  5938. if (IsPostfixUpdate) {
  5939. // Use old value from 'atomicrmw'.
  5940. NewVVal = Res.second;
  5941. } else {
  5942. // 'atomicrmw' does not provide new value, so evaluate it using old
  5943. // value of 'x'.
  5944. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  5945. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
  5946. NewVVal = CGF.EmitAnyExpr(UE);
  5947. }
  5948. }
  5949. } else {
  5950. // 'x' is simply rewritten with some 'expr'.
  5951. NewVValType = X->getType().getNonReferenceType();
  5952. ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
  5953. X->getType().getNonReferenceType(), Loc);
  5954. auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
  5955. NewVVal = XRValue;
  5956. return ExprRValue;
  5957. };
  5958. // Try to perform atomicrmw xchg, otherwise simple exchange.
  5959. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  5960. XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
  5961. Loc, Gen);
  5962. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
  5963. if (Res.first) {
  5964. // 'atomicrmw' instruction was generated.
  5965. NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
  5966. }
  5967. }
  5968. // Emit post-update store to 'v' of old/new 'x' value.
  5969. CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
  5970. CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
  5971. // OpenMP 5.1 removes the required flush for capture clause.
  5972. if (CGF.CGM.getLangOpts().OpenMP < 51) {
  5973. // OpenMP, 2.17.7, atomic Construct
  5974. // If the write, update, or capture clause is specified and the release,
  5975. // acq_rel, or seq_cst clause is specified then the strong flush on entry to
  5976. // the atomic operation is also a release flush.
  5977. // If the read or capture clause is specified and the acquire, acq_rel, or
  5978. // seq_cst clause is specified then the strong flush on exit from the atomic
  5979. // operation is also an acquire flush.
  5980. switch (AO) {
  5981. case llvm::AtomicOrdering::Release:
  5982. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
  5983. llvm::AtomicOrdering::Release);
  5984. break;
  5985. case llvm::AtomicOrdering::Acquire:
  5986. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, std::nullopt, Loc,
  5987. llvm::AtomicOrdering::Acquire);
  5988. break;
  5989. case llvm::AtomicOrdering::AcquireRelease:
  5990. case llvm::AtomicOrdering::SequentiallyConsistent:
  5991. CGF.CGM.getOpenMPRuntime().emitFlush(
  5992. CGF, std::nullopt, Loc, llvm::AtomicOrdering::AcquireRelease);
  5993. break;
  5994. case llvm::AtomicOrdering::Monotonic:
  5995. break;
  5996. case llvm::AtomicOrdering::NotAtomic:
  5997. case llvm::AtomicOrdering::Unordered:
  5998. llvm_unreachable("Unexpected ordering.");
  5999. }
  6000. }
  6001. }
  6002. static void emitOMPAtomicCompareExpr(CodeGenFunction &CGF,
  6003. llvm::AtomicOrdering AO, const Expr *X,
  6004. const Expr *V, const Expr *R,
  6005. const Expr *E, const Expr *D,
  6006. const Expr *CE, bool IsXBinopExpr,
  6007. bool IsPostfixUpdate, bool IsFailOnly,
  6008. SourceLocation Loc) {
  6009. llvm::OpenMPIRBuilder &OMPBuilder =
  6010. CGF.CGM.getOpenMPRuntime().getOMPBuilder();
  6011. OMPAtomicCompareOp Op;
  6012. assert(isa<BinaryOperator>(CE) && "CE is not a BinaryOperator");
  6013. switch (cast<BinaryOperator>(CE)->getOpcode()) {
  6014. case BO_EQ:
  6015. Op = OMPAtomicCompareOp::EQ;
  6016. break;
  6017. case BO_LT:
  6018. Op = OMPAtomicCompareOp::MIN;
  6019. break;
  6020. case BO_GT:
  6021. Op = OMPAtomicCompareOp::MAX;
  6022. break;
  6023. default:
  6024. llvm_unreachable("unsupported atomic compare binary operator");
  6025. }
  6026. LValue XLVal = CGF.EmitLValue(X);
  6027. Address XAddr = XLVal.getAddress(CGF);
  6028. auto EmitRValueWithCastIfNeeded = [&CGF, Loc](const Expr *X, const Expr *E) {
  6029. if (X->getType() == E->getType())
  6030. return CGF.EmitScalarExpr(E);
  6031. const Expr *NewE = E->IgnoreImplicitAsWritten();
  6032. llvm::Value *V = CGF.EmitScalarExpr(NewE);
  6033. if (NewE->getType() == X->getType())
  6034. return V;
  6035. return CGF.EmitScalarConversion(V, NewE->getType(), X->getType(), Loc);
  6036. };
  6037. llvm::Value *EVal = EmitRValueWithCastIfNeeded(X, E);
  6038. llvm::Value *DVal = D ? EmitRValueWithCastIfNeeded(X, D) : nullptr;
  6039. if (auto *CI = dyn_cast<llvm::ConstantInt>(EVal))
  6040. EVal = CGF.Builder.CreateIntCast(
  6041. CI, XLVal.getAddress(CGF).getElementType(),
  6042. E->getType()->hasSignedIntegerRepresentation());
  6043. if (DVal)
  6044. if (auto *CI = dyn_cast<llvm::ConstantInt>(DVal))
  6045. DVal = CGF.Builder.CreateIntCast(
  6046. CI, XLVal.getAddress(CGF).getElementType(),
  6047. D->getType()->hasSignedIntegerRepresentation());
  6048. llvm::OpenMPIRBuilder::AtomicOpValue XOpVal{
  6049. XAddr.getPointer(), XAddr.getElementType(),
  6050. X->getType()->hasSignedIntegerRepresentation(),
  6051. X->getType().isVolatileQualified()};
  6052. llvm::OpenMPIRBuilder::AtomicOpValue VOpVal, ROpVal;
  6053. if (V) {
  6054. LValue LV = CGF.EmitLValue(V);
  6055. Address Addr = LV.getAddress(CGF);
  6056. VOpVal = {Addr.getPointer(), Addr.getElementType(),
  6057. V->getType()->hasSignedIntegerRepresentation(),
  6058. V->getType().isVolatileQualified()};
  6059. }
  6060. if (R) {
  6061. LValue LV = CGF.EmitLValue(R);
  6062. Address Addr = LV.getAddress(CGF);
  6063. ROpVal = {Addr.getPointer(), Addr.getElementType(),
  6064. R->getType()->hasSignedIntegerRepresentation(),
  6065. R->getType().isVolatileQualified()};
  6066. }
  6067. CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare(
  6068. CGF.Builder, XOpVal, VOpVal, ROpVal, EVal, DVal, AO, Op, IsXBinopExpr,
  6069. IsPostfixUpdate, IsFailOnly));
  6070. }
  6071. static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
  6072. llvm::AtomicOrdering AO, bool IsPostfixUpdate,
  6073. const Expr *X, const Expr *V, const Expr *R,
  6074. const Expr *E, const Expr *UE, const Expr *D,
  6075. const Expr *CE, bool IsXLHSInRHSPart,
  6076. bool IsFailOnly, SourceLocation Loc) {
  6077. switch (Kind) {
  6078. case OMPC_read:
  6079. emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
  6080. break;
  6081. case OMPC_write:
  6082. emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
  6083. break;
  6084. case OMPC_unknown:
  6085. case OMPC_update:
  6086. emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
  6087. break;
  6088. case OMPC_capture:
  6089. emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
  6090. IsXLHSInRHSPart, Loc);
  6091. break;
  6092. case OMPC_compare: {
  6093. emitOMPAtomicCompareExpr(CGF, AO, X, V, R, E, D, CE, IsXLHSInRHSPart,
  6094. IsPostfixUpdate, IsFailOnly, Loc);
  6095. break;
  6096. }
  6097. default:
  6098. llvm_unreachable("Clause is not allowed in 'omp atomic'.");
  6099. }
  6100. }
  6101. void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
  6102. llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic;
  6103. bool MemOrderingSpecified = false;
  6104. if (S.getSingleClause<OMPSeqCstClause>()) {
  6105. AO = llvm::AtomicOrdering::SequentiallyConsistent;
  6106. MemOrderingSpecified = true;
  6107. } else if (S.getSingleClause<OMPAcqRelClause>()) {
  6108. AO = llvm::AtomicOrdering::AcquireRelease;
  6109. MemOrderingSpecified = true;
  6110. } else if (S.getSingleClause<OMPAcquireClause>()) {
  6111. AO = llvm::AtomicOrdering::Acquire;
  6112. MemOrderingSpecified = true;
  6113. } else if (S.getSingleClause<OMPReleaseClause>()) {
  6114. AO = llvm::AtomicOrdering::Release;
  6115. MemOrderingSpecified = true;
  6116. } else if (S.getSingleClause<OMPRelaxedClause>()) {
  6117. AO = llvm::AtomicOrdering::Monotonic;
  6118. MemOrderingSpecified = true;
  6119. }
  6120. llvm::SmallSet<OpenMPClauseKind, 2> KindsEncountered;
  6121. OpenMPClauseKind Kind = OMPC_unknown;
  6122. for (const OMPClause *C : S.clauses()) {
  6123. // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause,
  6124. // if it is first).
  6125. OpenMPClauseKind K = C->getClauseKind();
  6126. if (K == OMPC_seq_cst || K == OMPC_acq_rel || K == OMPC_acquire ||
  6127. K == OMPC_release || K == OMPC_relaxed || K == OMPC_hint)
  6128. continue;
  6129. Kind = K;
  6130. KindsEncountered.insert(K);
  6131. }
  6132. // We just need to correct Kind here. No need to set a bool saying it is
  6133. // actually compare capture because we can tell from whether V and R are
  6134. // nullptr.
  6135. if (KindsEncountered.contains(OMPC_compare) &&
  6136. KindsEncountered.contains(OMPC_capture))
  6137. Kind = OMPC_compare;
  6138. if (!MemOrderingSpecified) {
  6139. llvm::AtomicOrdering DefaultOrder =
  6140. CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
  6141. if (DefaultOrder == llvm::AtomicOrdering::Monotonic ||
  6142. DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent ||
  6143. (DefaultOrder == llvm::AtomicOrdering::AcquireRelease &&
  6144. Kind == OMPC_capture)) {
  6145. AO = DefaultOrder;
  6146. } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) {
  6147. if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) {
  6148. AO = llvm::AtomicOrdering::Release;
  6149. } else if (Kind == OMPC_read) {
  6150. assert(Kind == OMPC_read && "Unexpected atomic kind.");
  6151. AO = llvm::AtomicOrdering::Acquire;
  6152. }
  6153. }
  6154. }
  6155. LexicalScope Scope(*this, S.getSourceRange());
  6156. EmitStopPoint(S.getAssociatedStmt());
  6157. emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(),
  6158. S.getR(), S.getExpr(), S.getUpdateExpr(), S.getD(),
  6159. S.getCondExpr(), S.isXLHSInRHSPart(), S.isFailOnly(),
  6160. S.getBeginLoc());
  6161. }
  6162. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  6163. const OMPExecutableDirective &S,
  6164. const RegionCodeGenTy &CodeGen) {
  6165. assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
  6166. CodeGenModule &CGM = CGF.CGM;
  6167. // On device emit this construct as inlined code.
  6168. if (CGM.getLangOpts().OpenMPIsDevice) {
  6169. OMPLexicalScope Scope(CGF, S, OMPD_target);
  6170. CGM.getOpenMPRuntime().emitInlinedDirective(
  6171. CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6172. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  6173. });
  6174. return;
  6175. }
  6176. auto LPCRegion = CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
  6177. llvm::Function *Fn = nullptr;
  6178. llvm::Constant *FnID = nullptr;
  6179. const Expr *IfCond = nullptr;
  6180. // Check for the at most one if clause associated with the target region.
  6181. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  6182. if (C->getNameModifier() == OMPD_unknown ||
  6183. C->getNameModifier() == OMPD_target) {
  6184. IfCond = C->getCondition();
  6185. break;
  6186. }
  6187. }
  6188. // Check if we have any device clause associated with the directive.
  6189. llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device(
  6190. nullptr, OMPC_DEVICE_unknown);
  6191. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  6192. Device.setPointerAndInt(C->getDevice(), C->getModifier());
  6193. // Check if we have an if clause whose conditional always evaluates to false
  6194. // or if we do not have any targets specified. If so the target region is not
  6195. // an offload entry point.
  6196. bool IsOffloadEntry = true;
  6197. if (IfCond) {
  6198. bool Val;
  6199. if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
  6200. IsOffloadEntry = false;
  6201. }
  6202. if (CGM.getLangOpts().OMPTargetTriples.empty())
  6203. IsOffloadEntry = false;
  6204. if (CGM.getLangOpts().OpenMPOffloadMandatory && !IsOffloadEntry) {
  6205. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  6206. DiagnosticsEngine::Error,
  6207. "No offloading entry generated while offloading is mandatory.");
  6208. CGM.getDiags().Report(DiagID);
  6209. }
  6210. assert(CGF.CurFuncDecl && "No parent declaration for target region!");
  6211. StringRef ParentName;
  6212. // In case we have Ctors/Dtors we use the complete type variant to produce
  6213. // the mangling of the device outlined kernel.
  6214. if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
  6215. ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
  6216. else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
  6217. ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
  6218. else
  6219. ParentName =
  6220. CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
  6221. // Emit target region as a standalone region.
  6222. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
  6223. IsOffloadEntry, CodeGen);
  6224. OMPLexicalScope Scope(CGF, S, OMPD_task);
  6225. auto &&SizeEmitter =
  6226. [IsOffloadEntry](CodeGenFunction &CGF,
  6227. const OMPLoopDirective &D) -> llvm::Value * {
  6228. if (IsOffloadEntry) {
  6229. OMPLoopScope(CGF, D);
  6230. // Emit calculation of the iterations count.
  6231. llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
  6232. NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
  6233. /*isSigned=*/false);
  6234. return NumIterations;
  6235. }
  6236. return nullptr;
  6237. };
  6238. CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
  6239. SizeEmitter);
  6240. }
  6241. static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
  6242. PrePostActionTy &Action) {
  6243. Action.Enter(CGF);
  6244. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6245. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  6246. CGF.EmitOMPPrivateClause(S, PrivateScope);
  6247. (void)PrivateScope.Privatize();
  6248. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  6249. CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
  6250. CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
  6251. CGF.EnsureInsertPoint();
  6252. }
  6253. void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  6254. StringRef ParentName,
  6255. const OMPTargetDirective &S) {
  6256. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6257. emitTargetRegion(CGF, S, Action);
  6258. };
  6259. llvm::Function *Fn;
  6260. llvm::Constant *Addr;
  6261. // Emit target region as a standalone region.
  6262. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6263. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6264. assert(Fn && Addr && "Target device function emission failed.");
  6265. }
  6266. void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
  6267. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6268. emitTargetRegion(CGF, S, Action);
  6269. };
  6270. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6271. }
  6272. static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
  6273. const OMPExecutableDirective &S,
  6274. OpenMPDirectiveKind InnermostKind,
  6275. const RegionCodeGenTy &CodeGen) {
  6276. const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
  6277. llvm::Function *OutlinedFn =
  6278. CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
  6279. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  6280. const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
  6281. const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
  6282. if (NT || TL) {
  6283. const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
  6284. const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
  6285. CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
  6286. S.getBeginLoc());
  6287. }
  6288. OMPTeamsScope Scope(CGF, S);
  6289. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  6290. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  6291. CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
  6292. CapturedVars);
  6293. }
  6294. void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
  6295. // Emit teams region as a standalone region.
  6296. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6297. Action.Enter(CGF);
  6298. OMPPrivateScope PrivateScope(CGF);
  6299. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  6300. CGF.EmitOMPPrivateClause(S, PrivateScope);
  6301. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6302. (void)PrivateScope.Privatize();
  6303. CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
  6304. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6305. };
  6306. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
  6307. emitPostUpdateForReductionClause(*this, S,
  6308. [](CodeGenFunction &) { return nullptr; });
  6309. }
  6310. static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  6311. const OMPTargetTeamsDirective &S) {
  6312. auto *CS = S.getCapturedStmt(OMPD_teams);
  6313. Action.Enter(CGF);
  6314. // Emit teams region as a standalone region.
  6315. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6316. Action.Enter(CGF);
  6317. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6318. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  6319. CGF.EmitOMPPrivateClause(S, PrivateScope);
  6320. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6321. (void)PrivateScope.Privatize();
  6322. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  6323. CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
  6324. CGF.EmitStmt(CS->getCapturedStmt());
  6325. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6326. };
  6327. emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
  6328. emitPostUpdateForReductionClause(CGF, S,
  6329. [](CodeGenFunction &) { return nullptr; });
  6330. }
  6331. void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  6332. CodeGenModule &CGM, StringRef ParentName,
  6333. const OMPTargetTeamsDirective &S) {
  6334. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6335. emitTargetTeamsRegion(CGF, Action, S);
  6336. };
  6337. llvm::Function *Fn;
  6338. llvm::Constant *Addr;
  6339. // Emit target region as a standalone region.
  6340. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6341. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6342. assert(Fn && Addr && "Target device function emission failed.");
  6343. }
  6344. void CodeGenFunction::EmitOMPTargetTeamsDirective(
  6345. const OMPTargetTeamsDirective &S) {
  6346. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6347. emitTargetTeamsRegion(CGF, Action, S);
  6348. };
  6349. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6350. }
  6351. static void
  6352. emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  6353. const OMPTargetTeamsDistributeDirective &S) {
  6354. Action.Enter(CGF);
  6355. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6356. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  6357. };
  6358. // Emit teams region as a standalone region.
  6359. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6360. PrePostActionTy &Action) {
  6361. Action.Enter(CGF);
  6362. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6363. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6364. (void)PrivateScope.Privatize();
  6365. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  6366. CodeGenDistribute);
  6367. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6368. };
  6369. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
  6370. emitPostUpdateForReductionClause(CGF, S,
  6371. [](CodeGenFunction &) { return nullptr; });
  6372. }
  6373. void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
  6374. CodeGenModule &CGM, StringRef ParentName,
  6375. const OMPTargetTeamsDistributeDirective &S) {
  6376. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6377. emitTargetTeamsDistributeRegion(CGF, Action, S);
  6378. };
  6379. llvm::Function *Fn;
  6380. llvm::Constant *Addr;
  6381. // Emit target region as a standalone region.
  6382. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6383. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6384. assert(Fn && Addr && "Target device function emission failed.");
  6385. }
  6386. void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
  6387. const OMPTargetTeamsDistributeDirective &S) {
  6388. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6389. emitTargetTeamsDistributeRegion(CGF, Action, S);
  6390. };
  6391. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6392. }
  6393. static void emitTargetTeamsDistributeSimdRegion(
  6394. CodeGenFunction &CGF, PrePostActionTy &Action,
  6395. const OMPTargetTeamsDistributeSimdDirective &S) {
  6396. Action.Enter(CGF);
  6397. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6398. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  6399. };
  6400. // Emit teams region as a standalone region.
  6401. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6402. PrePostActionTy &Action) {
  6403. Action.Enter(CGF);
  6404. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6405. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6406. (void)PrivateScope.Privatize();
  6407. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  6408. CodeGenDistribute);
  6409. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6410. };
  6411. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
  6412. emitPostUpdateForReductionClause(CGF, S,
  6413. [](CodeGenFunction &) { return nullptr; });
  6414. }
  6415. void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  6416. CodeGenModule &CGM, StringRef ParentName,
  6417. const OMPTargetTeamsDistributeSimdDirective &S) {
  6418. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6419. emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
  6420. };
  6421. llvm::Function *Fn;
  6422. llvm::Constant *Addr;
  6423. // Emit target region as a standalone region.
  6424. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6425. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6426. assert(Fn && Addr && "Target device function emission failed.");
  6427. }
  6428. void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
  6429. const OMPTargetTeamsDistributeSimdDirective &S) {
  6430. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6431. emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
  6432. };
  6433. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6434. }
  6435. void CodeGenFunction::EmitOMPTeamsDistributeDirective(
  6436. const OMPTeamsDistributeDirective &S) {
  6437. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6438. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  6439. };
  6440. // Emit teams region as a standalone region.
  6441. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6442. PrePostActionTy &Action) {
  6443. Action.Enter(CGF);
  6444. OMPPrivateScope PrivateScope(CGF);
  6445. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6446. (void)PrivateScope.Privatize();
  6447. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  6448. CodeGenDistribute);
  6449. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6450. };
  6451. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
  6452. emitPostUpdateForReductionClause(*this, S,
  6453. [](CodeGenFunction &) { return nullptr; });
  6454. }
  6455. void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
  6456. const OMPTeamsDistributeSimdDirective &S) {
  6457. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6458. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  6459. };
  6460. // Emit teams region as a standalone region.
  6461. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6462. PrePostActionTy &Action) {
  6463. Action.Enter(CGF);
  6464. OMPPrivateScope PrivateScope(CGF);
  6465. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6466. (void)PrivateScope.Privatize();
  6467. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
  6468. CodeGenDistribute);
  6469. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6470. };
  6471. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
  6472. emitPostUpdateForReductionClause(*this, S,
  6473. [](CodeGenFunction &) { return nullptr; });
  6474. }
  6475. void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
  6476. const OMPTeamsDistributeParallelForDirective &S) {
  6477. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6478. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  6479. S.getDistInc());
  6480. };
  6481. // Emit teams region as a standalone region.
  6482. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6483. PrePostActionTy &Action) {
  6484. Action.Enter(CGF);
  6485. OMPPrivateScope PrivateScope(CGF);
  6486. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6487. (void)PrivateScope.Privatize();
  6488. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  6489. CodeGenDistribute);
  6490. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6491. };
  6492. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
  6493. emitPostUpdateForReductionClause(*this, S,
  6494. [](CodeGenFunction &) { return nullptr; });
  6495. }
  6496. void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
  6497. const OMPTeamsDistributeParallelForSimdDirective &S) {
  6498. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6499. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  6500. S.getDistInc());
  6501. };
  6502. // Emit teams region as a standalone region.
  6503. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6504. PrePostActionTy &Action) {
  6505. Action.Enter(CGF);
  6506. OMPPrivateScope PrivateScope(CGF);
  6507. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6508. (void)PrivateScope.Privatize();
  6509. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  6510. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  6511. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6512. };
  6513. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
  6514. CodeGen);
  6515. emitPostUpdateForReductionClause(*this, S,
  6516. [](CodeGenFunction &) { return nullptr; });
  6517. }
  6518. void CodeGenFunction::EmitOMPInteropDirective(const OMPInteropDirective &S) {
  6519. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  6520. llvm::Value *Device = nullptr;
  6521. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  6522. Device = EmitScalarExpr(C->getDevice());
  6523. llvm::Value *NumDependences = nullptr;
  6524. llvm::Value *DependenceAddress = nullptr;
  6525. if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
  6526. OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
  6527. DC->getModifier());
  6528. Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
  6529. std::pair<llvm::Value *, Address> DependencePair =
  6530. CGM.getOpenMPRuntime().emitDependClause(*this, Dependencies,
  6531. DC->getBeginLoc());
  6532. NumDependences = DependencePair.first;
  6533. DependenceAddress = Builder.CreatePointerCast(
  6534. DependencePair.second.getPointer(), CGM.Int8PtrTy);
  6535. }
  6536. assert(!(S.hasClausesOfKind<OMPNowaitClause>() &&
  6537. !(S.getSingleClause<OMPInitClause>() ||
  6538. S.getSingleClause<OMPDestroyClause>() ||
  6539. S.getSingleClause<OMPUseClause>())) &&
  6540. "OMPNowaitClause clause is used separately in OMPInteropDirective.");
  6541. if (const auto *C = S.getSingleClause<OMPInitClause>()) {
  6542. llvm::Value *InteropvarPtr =
  6543. EmitLValue(C->getInteropVar()).getPointer(*this);
  6544. llvm::omp::OMPInteropType InteropType = llvm::omp::OMPInteropType::Unknown;
  6545. if (C->getIsTarget()) {
  6546. InteropType = llvm::omp::OMPInteropType::Target;
  6547. } else {
  6548. assert(C->getIsTargetSync() && "Expected interop-type target/targetsync");
  6549. InteropType = llvm::omp::OMPInteropType::TargetSync;
  6550. }
  6551. OMPBuilder.createOMPInteropInit(Builder, InteropvarPtr, InteropType, Device,
  6552. NumDependences, DependenceAddress,
  6553. S.hasClausesOfKind<OMPNowaitClause>());
  6554. } else if (const auto *C = S.getSingleClause<OMPDestroyClause>()) {
  6555. llvm::Value *InteropvarPtr =
  6556. EmitLValue(C->getInteropVar()).getPointer(*this);
  6557. OMPBuilder.createOMPInteropDestroy(Builder, InteropvarPtr, Device,
  6558. NumDependences, DependenceAddress,
  6559. S.hasClausesOfKind<OMPNowaitClause>());
  6560. } else if (const auto *C = S.getSingleClause<OMPUseClause>()) {
  6561. llvm::Value *InteropvarPtr =
  6562. EmitLValue(C->getInteropVar()).getPointer(*this);
  6563. OMPBuilder.createOMPInteropUse(Builder, InteropvarPtr, Device,
  6564. NumDependences, DependenceAddress,
  6565. S.hasClausesOfKind<OMPNowaitClause>());
  6566. }
  6567. }
  6568. static void emitTargetTeamsDistributeParallelForRegion(
  6569. CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
  6570. PrePostActionTy &Action) {
  6571. Action.Enter(CGF);
  6572. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6573. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  6574. S.getDistInc());
  6575. };
  6576. // Emit teams region as a standalone region.
  6577. auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6578. PrePostActionTy &Action) {
  6579. Action.Enter(CGF);
  6580. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6581. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6582. (void)PrivateScope.Privatize();
  6583. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  6584. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  6585. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6586. };
  6587. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
  6588. CodeGenTeams);
  6589. emitPostUpdateForReductionClause(CGF, S,
  6590. [](CodeGenFunction &) { return nullptr; });
  6591. }
  6592. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  6593. CodeGenModule &CGM, StringRef ParentName,
  6594. const OMPTargetTeamsDistributeParallelForDirective &S) {
  6595. // Emit SPMD target teams distribute parallel for region as a standalone
  6596. // region.
  6597. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6598. emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
  6599. };
  6600. llvm::Function *Fn;
  6601. llvm::Constant *Addr;
  6602. // Emit target region as a standalone region.
  6603. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6604. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6605. assert(Fn && Addr && "Target device function emission failed.");
  6606. }
  6607. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
  6608. const OMPTargetTeamsDistributeParallelForDirective &S) {
  6609. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6610. emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
  6611. };
  6612. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6613. }
  6614. static void emitTargetTeamsDistributeParallelForSimdRegion(
  6615. CodeGenFunction &CGF,
  6616. const OMPTargetTeamsDistributeParallelForSimdDirective &S,
  6617. PrePostActionTy &Action) {
  6618. Action.Enter(CGF);
  6619. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6620. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  6621. S.getDistInc());
  6622. };
  6623. // Emit teams region as a standalone region.
  6624. auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  6625. PrePostActionTy &Action) {
  6626. Action.Enter(CGF);
  6627. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6628. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6629. (void)PrivateScope.Privatize();
  6630. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  6631. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  6632. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  6633. };
  6634. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
  6635. CodeGenTeams);
  6636. emitPostUpdateForReductionClause(CGF, S,
  6637. [](CodeGenFunction &) { return nullptr; });
  6638. }
  6639. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  6640. CodeGenModule &CGM, StringRef ParentName,
  6641. const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
  6642. // Emit SPMD target teams distribute parallel for simd region as a standalone
  6643. // region.
  6644. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6645. emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
  6646. };
  6647. llvm::Function *Fn;
  6648. llvm::Constant *Addr;
  6649. // Emit target region as a standalone region.
  6650. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6651. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6652. assert(Fn && Addr && "Target device function emission failed.");
  6653. }
  6654. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  6655. const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
  6656. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6657. emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
  6658. };
  6659. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6660. }
  6661. void CodeGenFunction::EmitOMPCancellationPointDirective(
  6662. const OMPCancellationPointDirective &S) {
  6663. CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
  6664. S.getCancelRegion());
  6665. }
  6666. void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
  6667. const Expr *IfCond = nullptr;
  6668. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  6669. if (C->getNameModifier() == OMPD_unknown ||
  6670. C->getNameModifier() == OMPD_cancel) {
  6671. IfCond = C->getCondition();
  6672. break;
  6673. }
  6674. }
  6675. if (CGM.getLangOpts().OpenMPIRBuilder) {
  6676. llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
  6677. // TODO: This check is necessary as we only generate `omp parallel` through
  6678. // the OpenMPIRBuilder for now.
  6679. if (S.getCancelRegion() == OMPD_parallel ||
  6680. S.getCancelRegion() == OMPD_sections ||
  6681. S.getCancelRegion() == OMPD_section) {
  6682. llvm::Value *IfCondition = nullptr;
  6683. if (IfCond)
  6684. IfCondition = EmitScalarExpr(IfCond,
  6685. /*IgnoreResultAssign=*/true);
  6686. return Builder.restoreIP(
  6687. OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion()));
  6688. }
  6689. }
  6690. CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
  6691. S.getCancelRegion());
  6692. }
  6693. CodeGenFunction::JumpDest
  6694. CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
  6695. if (Kind == OMPD_parallel || Kind == OMPD_task ||
  6696. Kind == OMPD_target_parallel || Kind == OMPD_taskloop ||
  6697. Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop)
  6698. return ReturnBlock;
  6699. assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
  6700. Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
  6701. Kind == OMPD_distribute_parallel_for ||
  6702. Kind == OMPD_target_parallel_for ||
  6703. Kind == OMPD_teams_distribute_parallel_for ||
  6704. Kind == OMPD_target_teams_distribute_parallel_for);
  6705. return OMPCancelStack.getExitBlock();
  6706. }
  6707. void CodeGenFunction::EmitOMPUseDevicePtrClause(
  6708. const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
  6709. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
  6710. auto OrigVarIt = C.varlist_begin();
  6711. auto InitIt = C.inits().begin();
  6712. for (const Expr *PvtVarIt : C.private_copies()) {
  6713. const auto *OrigVD =
  6714. cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
  6715. const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
  6716. const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
  6717. // In order to identify the right initializer we need to match the
  6718. // declaration used by the mapping logic. In some cases we may get
  6719. // OMPCapturedExprDecl that refers to the original declaration.
  6720. const ValueDecl *MatchingVD = OrigVD;
  6721. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
  6722. // OMPCapturedExprDecl are used to privative fields of the current
  6723. // structure.
  6724. const auto *ME = cast<MemberExpr>(OED->getInit());
  6725. assert(isa<CXXThisExpr>(ME->getBase()) &&
  6726. "Base should be the current struct!");
  6727. MatchingVD = ME->getMemberDecl();
  6728. }
  6729. // If we don't have information about the current list item, move on to
  6730. // the next one.
  6731. auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
  6732. if (InitAddrIt == CaptureDeviceAddrMap.end())
  6733. continue;
  6734. // Initialize the temporary initialization variable with the address
  6735. // we get from the runtime library. We have to cast the source address
  6736. // because it is always a void *. References are materialized in the
  6737. // privatization scope, so the initialization here disregards the fact
  6738. // the original variable is a reference.
  6739. llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
  6740. Address InitAddr = Builder.CreateElementBitCast(InitAddrIt->second, Ty);
  6741. setAddrOfLocalVar(InitVD, InitAddr);
  6742. // Emit private declaration, it will be initialized by the value we
  6743. // declaration we just added to the local declarations map.
  6744. EmitDecl(*PvtVD);
  6745. // The initialization variables reached its purpose in the emission
  6746. // of the previous declaration, so we don't need it anymore.
  6747. LocalDeclMap.erase(InitVD);
  6748. // Return the address of the private variable.
  6749. bool IsRegistered =
  6750. PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(PvtVD));
  6751. assert(IsRegistered && "firstprivate var already registered as private");
  6752. // Silence the warning about unused variable.
  6753. (void)IsRegistered;
  6754. ++OrigVarIt;
  6755. ++InitIt;
  6756. }
  6757. }
  6758. static const VarDecl *getBaseDecl(const Expr *Ref) {
  6759. const Expr *Base = Ref->IgnoreParenImpCasts();
  6760. while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base))
  6761. Base = OASE->getBase()->IgnoreParenImpCasts();
  6762. while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base))
  6763. Base = ASE->getBase()->IgnoreParenImpCasts();
  6764. return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl());
  6765. }
  6766. void CodeGenFunction::EmitOMPUseDeviceAddrClause(
  6767. const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
  6768. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
  6769. llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
  6770. for (const Expr *Ref : C.varlists()) {
  6771. const VarDecl *OrigVD = getBaseDecl(Ref);
  6772. if (!Processed.insert(OrigVD).second)
  6773. continue;
  6774. // In order to identify the right initializer we need to match the
  6775. // declaration used by the mapping logic. In some cases we may get
  6776. // OMPCapturedExprDecl that refers to the original declaration.
  6777. const ValueDecl *MatchingVD = OrigVD;
  6778. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
  6779. // OMPCapturedExprDecl are used to privative fields of the current
  6780. // structure.
  6781. const auto *ME = cast<MemberExpr>(OED->getInit());
  6782. assert(isa<CXXThisExpr>(ME->getBase()) &&
  6783. "Base should be the current struct!");
  6784. MatchingVD = ME->getMemberDecl();
  6785. }
  6786. // If we don't have information about the current list item, move on to
  6787. // the next one.
  6788. auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
  6789. if (InitAddrIt == CaptureDeviceAddrMap.end())
  6790. continue;
  6791. Address PrivAddr = InitAddrIt->getSecond();
  6792. // For declrefs and variable length array need to load the pointer for
  6793. // correct mapping, since the pointer to the data was passed to the runtime.
  6794. if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) ||
  6795. MatchingVD->getType()->isArrayType()) {
  6796. QualType PtrTy = getContext().getPointerType(
  6797. OrigVD->getType().getNonReferenceType());
  6798. PrivAddr = EmitLoadOfPointer(
  6799. Builder.CreateElementBitCast(PrivAddr, ConvertTypeForMem(PtrTy)),
  6800. PtrTy->castAs<PointerType>());
  6801. }
  6802. (void)PrivateScope.addPrivate(OrigVD, PrivAddr);
  6803. }
  6804. }
  6805. // Generate the instructions for '#pragma omp target data' directive.
  6806. void CodeGenFunction::EmitOMPTargetDataDirective(
  6807. const OMPTargetDataDirective &S) {
  6808. CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true,
  6809. /*SeparateBeginEndCalls=*/true);
  6810. // Create a pre/post action to signal the privatization of the device pointer.
  6811. // This action can be replaced by the OpenMP runtime code generation to
  6812. // deactivate privatization.
  6813. bool PrivatizeDevicePointers = false;
  6814. class DevicePointerPrivActionTy : public PrePostActionTy {
  6815. bool &PrivatizeDevicePointers;
  6816. public:
  6817. explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
  6818. : PrivatizeDevicePointers(PrivatizeDevicePointers) {}
  6819. void Enter(CodeGenFunction &CGF) override {
  6820. PrivatizeDevicePointers = true;
  6821. }
  6822. };
  6823. DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
  6824. auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
  6825. CodeGenFunction &CGF, PrePostActionTy &Action) {
  6826. auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  6827. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  6828. };
  6829. // Codegen that selects whether to generate the privatization code or not.
  6830. auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
  6831. &InnermostCodeGen](CodeGenFunction &CGF,
  6832. PrePostActionTy &Action) {
  6833. RegionCodeGenTy RCG(InnermostCodeGen);
  6834. PrivatizeDevicePointers = false;
  6835. // Call the pre-action to change the status of PrivatizeDevicePointers if
  6836. // needed.
  6837. Action.Enter(CGF);
  6838. if (PrivatizeDevicePointers) {
  6839. OMPPrivateScope PrivateScope(CGF);
  6840. // Emit all instances of the use_device_ptr clause.
  6841. for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
  6842. CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
  6843. Info.CaptureDeviceAddrMap);
  6844. for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
  6845. CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope,
  6846. Info.CaptureDeviceAddrMap);
  6847. (void)PrivateScope.Privatize();
  6848. RCG(CGF);
  6849. } else {
  6850. OMPLexicalScope Scope(CGF, S, OMPD_unknown);
  6851. RCG(CGF);
  6852. }
  6853. };
  6854. // Forward the provided action to the privatization codegen.
  6855. RegionCodeGenTy PrivRCG(PrivCodeGen);
  6856. PrivRCG.setAction(Action);
  6857. // Notwithstanding the body of the region is emitted as inlined directive,
  6858. // we don't use an inline scope as changes in the references inside the
  6859. // region are expected to be visible outside, so we do not privative them.
  6860. OMPLexicalScope Scope(CGF, S);
  6861. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
  6862. PrivRCG);
  6863. };
  6864. RegionCodeGenTy RCG(CodeGen);
  6865. // If we don't have target devices, don't bother emitting the data mapping
  6866. // code.
  6867. if (CGM.getLangOpts().OMPTargetTriples.empty()) {
  6868. RCG(*this);
  6869. return;
  6870. }
  6871. // Check if we have any if clause associated with the directive.
  6872. const Expr *IfCond = nullptr;
  6873. if (const auto *C = S.getSingleClause<OMPIfClause>())
  6874. IfCond = C->getCondition();
  6875. // Check if we have any device clause associated with the directive.
  6876. const Expr *Device = nullptr;
  6877. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  6878. Device = C->getDevice();
  6879. // Set the action to signal privatization of device pointers.
  6880. RCG.setAction(PrivAction);
  6881. // Emit region code.
  6882. CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
  6883. Info);
  6884. }
  6885. void CodeGenFunction::EmitOMPTargetEnterDataDirective(
  6886. const OMPTargetEnterDataDirective &S) {
  6887. // If we don't have target devices, don't bother emitting the data mapping
  6888. // code.
  6889. if (CGM.getLangOpts().OMPTargetTriples.empty())
  6890. return;
  6891. // Check if we have any if clause associated with the directive.
  6892. const Expr *IfCond = nullptr;
  6893. if (const auto *C = S.getSingleClause<OMPIfClause>())
  6894. IfCond = C->getCondition();
  6895. // Check if we have any device clause associated with the directive.
  6896. const Expr *Device = nullptr;
  6897. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  6898. Device = C->getDevice();
  6899. OMPLexicalScope Scope(*this, S, OMPD_task);
  6900. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  6901. }
  6902. void CodeGenFunction::EmitOMPTargetExitDataDirective(
  6903. const OMPTargetExitDataDirective &S) {
  6904. // If we don't have target devices, don't bother emitting the data mapping
  6905. // code.
  6906. if (CGM.getLangOpts().OMPTargetTriples.empty())
  6907. return;
  6908. // Check if we have any if clause associated with the directive.
  6909. const Expr *IfCond = nullptr;
  6910. if (const auto *C = S.getSingleClause<OMPIfClause>())
  6911. IfCond = C->getCondition();
  6912. // Check if we have any device clause associated with the directive.
  6913. const Expr *Device = nullptr;
  6914. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  6915. Device = C->getDevice();
  6916. OMPLexicalScope Scope(*this, S, OMPD_task);
  6917. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  6918. }
  6919. static void emitTargetParallelRegion(CodeGenFunction &CGF,
  6920. const OMPTargetParallelDirective &S,
  6921. PrePostActionTy &Action) {
  6922. // Get the captured statement associated with the 'parallel' region.
  6923. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  6924. Action.Enter(CGF);
  6925. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6926. Action.Enter(CGF);
  6927. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  6928. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  6929. CGF.EmitOMPPrivateClause(S, PrivateScope);
  6930. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  6931. (void)PrivateScope.Privatize();
  6932. if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
  6933. CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
  6934. // TODO: Add support for clauses.
  6935. CGF.EmitStmt(CS->getCapturedStmt());
  6936. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  6937. };
  6938. emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
  6939. emitEmptyBoundParameters);
  6940. emitPostUpdateForReductionClause(CGF, S,
  6941. [](CodeGenFunction &) { return nullptr; });
  6942. }
  6943. void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  6944. CodeGenModule &CGM, StringRef ParentName,
  6945. const OMPTargetParallelDirective &S) {
  6946. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6947. emitTargetParallelRegion(CGF, S, Action);
  6948. };
  6949. llvm::Function *Fn;
  6950. llvm::Constant *Addr;
  6951. // Emit target region as a standalone region.
  6952. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6953. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6954. assert(Fn && Addr && "Target device function emission failed.");
  6955. }
  6956. void CodeGenFunction::EmitOMPTargetParallelDirective(
  6957. const OMPTargetParallelDirective &S) {
  6958. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6959. emitTargetParallelRegion(CGF, S, Action);
  6960. };
  6961. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6962. }
  6963. static void emitTargetParallelForRegion(CodeGenFunction &CGF,
  6964. const OMPTargetParallelForDirective &S,
  6965. PrePostActionTy &Action) {
  6966. Action.Enter(CGF);
  6967. // Emit directive as a combined directive that consists of two implicit
  6968. // directives: 'parallel' with 'for' directive.
  6969. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6970. Action.Enter(CGF);
  6971. CodeGenFunction::OMPCancelStackRAII CancelRegion(
  6972. CGF, OMPD_target_parallel_for, S.hasCancel());
  6973. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  6974. emitDispatchForLoopBounds);
  6975. };
  6976. emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
  6977. emitEmptyBoundParameters);
  6978. }
  6979. void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
  6980. CodeGenModule &CGM, StringRef ParentName,
  6981. const OMPTargetParallelForDirective &S) {
  6982. // Emit SPMD target parallel for region as a standalone region.
  6983. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6984. emitTargetParallelForRegion(CGF, S, Action);
  6985. };
  6986. llvm::Function *Fn;
  6987. llvm::Constant *Addr;
  6988. // Emit target region as a standalone region.
  6989. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  6990. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  6991. assert(Fn && Addr && "Target device function emission failed.");
  6992. }
  6993. void CodeGenFunction::EmitOMPTargetParallelForDirective(
  6994. const OMPTargetParallelForDirective &S) {
  6995. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  6996. emitTargetParallelForRegion(CGF, S, Action);
  6997. };
  6998. emitCommonOMPTargetDirective(*this, S, CodeGen);
  6999. }
  7000. static void
  7001. emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
  7002. const OMPTargetParallelForSimdDirective &S,
  7003. PrePostActionTy &Action) {
  7004. Action.Enter(CGF);
  7005. // Emit directive as a combined directive that consists of two implicit
  7006. // directives: 'parallel' with 'for' directive.
  7007. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7008. Action.Enter(CGF);
  7009. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  7010. emitDispatchForLoopBounds);
  7011. };
  7012. emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
  7013. emitEmptyBoundParameters);
  7014. }
  7015. void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
  7016. CodeGenModule &CGM, StringRef ParentName,
  7017. const OMPTargetParallelForSimdDirective &S) {
  7018. // Emit SPMD target parallel for region as a standalone region.
  7019. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7020. emitTargetParallelForSimdRegion(CGF, S, Action);
  7021. };
  7022. llvm::Function *Fn;
  7023. llvm::Constant *Addr;
  7024. // Emit target region as a standalone region.
  7025. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  7026. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  7027. assert(Fn && Addr && "Target device function emission failed.");
  7028. }
  7029. void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
  7030. const OMPTargetParallelForSimdDirective &S) {
  7031. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7032. emitTargetParallelForSimdRegion(CGF, S, Action);
  7033. };
  7034. emitCommonOMPTargetDirective(*this, S, CodeGen);
  7035. }
  7036. /// Emit a helper variable and return corresponding lvalue.
  7037. static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
  7038. const ImplicitParamDecl *PVD,
  7039. CodeGenFunction::OMPPrivateScope &Privates) {
  7040. const auto *VDecl = cast<VarDecl>(Helper->getDecl());
  7041. Privates.addPrivate(VDecl, CGF.GetAddrOfLocalVar(PVD));
  7042. }
  7043. void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
  7044. assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
  7045. // Emit outlined function for task construct.
  7046. const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
  7047. Address CapturedStruct = Address::invalid();
  7048. {
  7049. OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
  7050. CapturedStruct = GenerateCapturedStmtArgument(*CS);
  7051. }
  7052. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  7053. const Expr *IfCond = nullptr;
  7054. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  7055. if (C->getNameModifier() == OMPD_unknown ||
  7056. C->getNameModifier() == OMPD_taskloop) {
  7057. IfCond = C->getCondition();
  7058. break;
  7059. }
  7060. }
  7061. OMPTaskDataTy Data;
  7062. // Check if taskloop must be emitted without taskgroup.
  7063. Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
  7064. // TODO: Check if we should emit tied or untied task.
  7065. Data.Tied = true;
  7066. // Set scheduling for taskloop
  7067. if (const auto *Clause = S.getSingleClause<OMPGrainsizeClause>()) {
  7068. // grainsize clause
  7069. Data.Schedule.setInt(/*IntVal=*/false);
  7070. Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
  7071. } else if (const auto *Clause = S.getSingleClause<OMPNumTasksClause>()) {
  7072. // num_tasks clause
  7073. Data.Schedule.setInt(/*IntVal=*/true);
  7074. Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
  7075. }
  7076. auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
  7077. // if (PreCond) {
  7078. // for (IV in 0..LastIteration) BODY;
  7079. // <Final counter/linear vars updates>;
  7080. // }
  7081. //
  7082. // Emit: if (PreCond) - begin.
  7083. // If the condition constant folds and can be elided, avoid emitting the
  7084. // whole loop.
  7085. bool CondConstant;
  7086. llvm::BasicBlock *ContBlock = nullptr;
  7087. OMPLoopScope PreInitScope(CGF, S);
  7088. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  7089. if (!CondConstant)
  7090. return;
  7091. } else {
  7092. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
  7093. ContBlock = CGF.createBasicBlock("taskloop.if.end");
  7094. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  7095. CGF.getProfileCount(&S));
  7096. CGF.EmitBlock(ThenBlock);
  7097. CGF.incrementProfileCounter(&S);
  7098. }
  7099. (void)CGF.EmitOMPLinearClauseInit(S);
  7100. OMPPrivateScope LoopScope(CGF);
  7101. // Emit helper vars inits.
  7102. enum { LowerBound = 5, UpperBound, Stride, LastIter };
  7103. auto *I = CS->getCapturedDecl()->param_begin();
  7104. auto *LBP = std::next(I, LowerBound);
  7105. auto *UBP = std::next(I, UpperBound);
  7106. auto *STP = std::next(I, Stride);
  7107. auto *LIP = std::next(I, LastIter);
  7108. mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
  7109. LoopScope);
  7110. mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
  7111. LoopScope);
  7112. mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
  7113. mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
  7114. LoopScope);
  7115. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  7116. CGF.EmitOMPLinearClause(S, LoopScope);
  7117. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  7118. (void)LoopScope.Privatize();
  7119. // Emit the loop iteration variable.
  7120. const Expr *IVExpr = S.getIterationVariable();
  7121. const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  7122. CGF.EmitVarDecl(*IVDecl);
  7123. CGF.EmitIgnoredExpr(S.getInit());
  7124. // Emit the iterations count variable.
  7125. // If it is not a variable, Sema decided to calculate iterations count on
  7126. // each iteration (e.g., it is foldable into a constant).
  7127. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  7128. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  7129. // Emit calculation of the iterations count.
  7130. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  7131. }
  7132. {
  7133. OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
  7134. emitCommonSimdLoop(
  7135. CGF, S,
  7136. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  7137. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  7138. CGF.EmitOMPSimdInit(S);
  7139. },
  7140. [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
  7141. CGF.EmitOMPInnerLoop(
  7142. S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
  7143. [&S](CodeGenFunction &CGF) {
  7144. emitOMPLoopBodyWithStopPoint(CGF, S,
  7145. CodeGenFunction::JumpDest());
  7146. },
  7147. [](CodeGenFunction &) {});
  7148. });
  7149. }
  7150. // Emit: if (PreCond) - end.
  7151. if (ContBlock) {
  7152. CGF.EmitBranch(ContBlock);
  7153. CGF.EmitBlock(ContBlock, true);
  7154. }
  7155. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  7156. if (HasLastprivateClause) {
  7157. CGF.EmitOMPLastprivateClauseFinal(
  7158. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  7159. CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
  7160. CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
  7161. (*LIP)->getType(), S.getBeginLoc())));
  7162. }
  7163. LoopScope.restoreMap();
  7164. CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
  7165. return CGF.Builder.CreateIsNotNull(
  7166. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
  7167. (*LIP)->getType(), S.getBeginLoc()));
  7168. });
  7169. };
  7170. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  7171. IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
  7172. const OMPTaskDataTy &Data) {
  7173. auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
  7174. &Data](CodeGenFunction &CGF, PrePostActionTy &) {
  7175. OMPLoopScope PreInitScope(CGF, S);
  7176. CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
  7177. OutlinedFn, SharedsTy,
  7178. CapturedStruct, IfCond, Data);
  7179. };
  7180. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
  7181. CodeGen);
  7182. };
  7183. if (Data.Nogroup) {
  7184. EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
  7185. } else {
  7186. CGM.getOpenMPRuntime().emitTaskgroupRegion(
  7187. *this,
  7188. [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
  7189. PrePostActionTy &Action) {
  7190. Action.Enter(CGF);
  7191. CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
  7192. Data);
  7193. },
  7194. S.getBeginLoc());
  7195. }
  7196. }
  7197. void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
  7198. auto LPCRegion =
  7199. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7200. EmitOMPTaskLoopBasedDirective(S);
  7201. }
  7202. void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
  7203. const OMPTaskLoopSimdDirective &S) {
  7204. auto LPCRegion =
  7205. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7206. OMPLexicalScope Scope(*this, S);
  7207. EmitOMPTaskLoopBasedDirective(S);
  7208. }
  7209. void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
  7210. const OMPMasterTaskLoopDirective &S) {
  7211. auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7212. Action.Enter(CGF);
  7213. EmitOMPTaskLoopBasedDirective(S);
  7214. };
  7215. auto LPCRegion =
  7216. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7217. OMPLexicalScope Scope(*this, S, std::nullopt, /*EmitPreInitStmt=*/false);
  7218. CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
  7219. }
  7220. void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
  7221. const OMPMasterTaskLoopSimdDirective &S) {
  7222. auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7223. Action.Enter(CGF);
  7224. EmitOMPTaskLoopBasedDirective(S);
  7225. };
  7226. auto LPCRegion =
  7227. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7228. OMPLexicalScope Scope(*this, S);
  7229. CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
  7230. }
  7231. void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
  7232. const OMPParallelMasterTaskLoopDirective &S) {
  7233. auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7234. auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
  7235. PrePostActionTy &Action) {
  7236. Action.Enter(CGF);
  7237. CGF.EmitOMPTaskLoopBasedDirective(S);
  7238. };
  7239. OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
  7240. CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
  7241. S.getBeginLoc());
  7242. };
  7243. auto LPCRegion =
  7244. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7245. emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
  7246. emitEmptyBoundParameters);
  7247. }
  7248. void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
  7249. const OMPParallelMasterTaskLoopSimdDirective &S) {
  7250. auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7251. auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
  7252. PrePostActionTy &Action) {
  7253. Action.Enter(CGF);
  7254. CGF.EmitOMPTaskLoopBasedDirective(S);
  7255. };
  7256. OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
  7257. CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
  7258. S.getBeginLoc());
  7259. };
  7260. auto LPCRegion =
  7261. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
  7262. emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
  7263. emitEmptyBoundParameters);
  7264. }
  7265. // Generate the instructions for '#pragma omp target update' directive.
  7266. void CodeGenFunction::EmitOMPTargetUpdateDirective(
  7267. const OMPTargetUpdateDirective &S) {
  7268. // If we don't have target devices, don't bother emitting the data mapping
  7269. // code.
  7270. if (CGM.getLangOpts().OMPTargetTriples.empty())
  7271. return;
  7272. // Check if we have any if clause associated with the directive.
  7273. const Expr *IfCond = nullptr;
  7274. if (const auto *C = S.getSingleClause<OMPIfClause>())
  7275. IfCond = C->getCondition();
  7276. // Check if we have any device clause associated with the directive.
  7277. const Expr *Device = nullptr;
  7278. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  7279. Device = C->getDevice();
  7280. OMPLexicalScope Scope(*this, S, OMPD_task);
  7281. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  7282. }
  7283. void CodeGenFunction::EmitOMPGenericLoopDirective(
  7284. const OMPGenericLoopDirective &S) {
  7285. // Unimplemented, just inline the underlying statement for now.
  7286. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7287. // Emit the loop iteration variable.
  7288. const Stmt *CS =
  7289. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
  7290. const auto *ForS = dyn_cast<ForStmt>(CS);
  7291. if (ForS && !isa<DeclStmt>(ForS->getInit())) {
  7292. OMPPrivateScope LoopScope(CGF);
  7293. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  7294. (void)LoopScope.Privatize();
  7295. CGF.EmitStmt(CS);
  7296. LoopScope.restoreMap();
  7297. } else {
  7298. CGF.EmitStmt(CS);
  7299. }
  7300. };
  7301. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  7302. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_loop, CodeGen);
  7303. }
  7304. void CodeGenFunction::EmitSimpleOMPExecutableDirective(
  7305. const OMPExecutableDirective &D) {
  7306. if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) {
  7307. EmitOMPScanDirective(*SD);
  7308. return;
  7309. }
  7310. if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
  7311. return;
  7312. auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
  7313. OMPPrivateScope GlobalsScope(CGF);
  7314. if (isOpenMPTaskingDirective(D.getDirectiveKind())) {
  7315. // Capture global firstprivates to avoid crash.
  7316. for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
  7317. for (const Expr *Ref : C->varlists()) {
  7318. const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
  7319. if (!DRE)
  7320. continue;
  7321. const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  7322. if (!VD || VD->hasLocalStorage())
  7323. continue;
  7324. if (!CGF.LocalDeclMap.count(VD)) {
  7325. LValue GlobLVal = CGF.EmitLValue(Ref);
  7326. GlobalsScope.addPrivate(VD, GlobLVal.getAddress(CGF));
  7327. }
  7328. }
  7329. }
  7330. }
  7331. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  7332. (void)GlobalsScope.Privatize();
  7333. ParentLoopDirectiveForScanRegion ScanRegion(CGF, D);
  7334. emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
  7335. } else {
  7336. if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
  7337. for (const Expr *E : LD->counters()) {
  7338. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  7339. if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
  7340. LValue GlobLVal = CGF.EmitLValue(E);
  7341. GlobalsScope.addPrivate(VD, GlobLVal.getAddress(CGF));
  7342. }
  7343. if (isa<OMPCapturedExprDecl>(VD)) {
  7344. // Emit only those that were not explicitly referenced in clauses.
  7345. if (!CGF.LocalDeclMap.count(VD))
  7346. CGF.EmitVarDecl(*VD);
  7347. }
  7348. }
  7349. for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
  7350. if (!C->getNumForLoops())
  7351. continue;
  7352. for (unsigned I = LD->getLoopsNumber(),
  7353. E = C->getLoopNumIterations().size();
  7354. I < E; ++I) {
  7355. if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
  7356. cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
  7357. // Emit only those that were not explicitly referenced in clauses.
  7358. if (!CGF.LocalDeclMap.count(VD))
  7359. CGF.EmitVarDecl(*VD);
  7360. }
  7361. }
  7362. }
  7363. }
  7364. (void)GlobalsScope.Privatize();
  7365. CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
  7366. }
  7367. };
  7368. if (D.getDirectiveKind() == OMPD_atomic ||
  7369. D.getDirectiveKind() == OMPD_critical ||
  7370. D.getDirectiveKind() == OMPD_section ||
  7371. D.getDirectiveKind() == OMPD_master ||
  7372. D.getDirectiveKind() == OMPD_masked) {
  7373. EmitStmt(D.getAssociatedStmt());
  7374. } else {
  7375. auto LPCRegion =
  7376. CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
  7377. OMPSimdLexicalScope Scope(*this, D);
  7378. CGM.getOpenMPRuntime().emitInlinedDirective(
  7379. *this,
  7380. isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
  7381. : D.getDirectiveKind(),
  7382. CodeGen);
  7383. }
  7384. // Check for outer lastprivate conditional update.
  7385. checkForLastprivateConditionalUpdate(*this, D);
  7386. }