SemaOpenMP.cpp 646 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements semantic analysis for OpenMP directives and
  10. /// clauses.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/AST/TypeOrdering.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static const Expr *checkMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy {
  54. public:
  55. struct DSAVarData {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. const Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  63. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  64. SourceLocation ImplicitDSALoc)
  65. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  66. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  67. };
  68. using OperatorOffsetTy =
  69. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  70. using DoacrossDependMapTy =
  71. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  72. private:
  73. struct DSAInfo {
  74. OpenMPClauseKind Attributes = OMPC_unknown;
  75. /// Pointer to a reference expression and a flag which shows that the
  76. /// variable is marked as lastprivate(true) or not (false).
  77. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  78. DeclRefExpr *PrivateCopy = nullptr;
  79. };
  80. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  81. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  82. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  83. using LoopControlVariablesMapTy =
  84. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  85. /// Struct that associates a component with the clause kind where they are
  86. /// found.
  87. struct MappedExprComponentTy {
  88. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  89. OpenMPClauseKind Kind = OMPC_unknown;
  90. };
  91. using MappedExprComponentsTy =
  92. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  93. using CriticalsWithHintsTy =
  94. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  95. struct ReductionData {
  96. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  97. SourceRange ReductionRange;
  98. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  99. ReductionData() = default;
  100. void set(BinaryOperatorKind BO, SourceRange RR) {
  101. ReductionRange = RR;
  102. ReductionOp = BO;
  103. }
  104. void set(const Expr *RefExpr, SourceRange RR) {
  105. ReductionRange = RR;
  106. ReductionOp = RefExpr;
  107. }
  108. };
  109. using DeclReductionMapTy =
  110. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  111. struct SharingMapTy {
  112. DeclSAMapTy SharingMap;
  113. DeclReductionMapTy ReductionMap;
  114. AlignedMapTy AlignedMap;
  115. MappedExprComponentsTy MappedExprComponents;
  116. LoopControlVariablesMapTy LCVMap;
  117. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  118. SourceLocation DefaultAttrLoc;
  119. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  120. SourceLocation DefaultMapAttrLoc;
  121. OpenMPDirectiveKind Directive = OMPD_unknown;
  122. DeclarationNameInfo DirectiveName;
  123. Scope *CurScope = nullptr;
  124. SourceLocation ConstructLoc;
  125. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  126. /// get the data (loop counters etc.) about enclosing loop-based construct.
  127. /// This data is required during codegen.
  128. DoacrossDependMapTy DoacrossDepends;
  129. /// First argument (Expr *) contains optional argument of the
  130. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  131. /// clause, false otherwise.
  132. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  133. unsigned AssociatedLoops = 1;
  134. bool HasMutipleLoops = false;
  135. const Decl *PossiblyLoopCounter = nullptr;
  136. bool NowaitRegion = false;
  137. bool CancelRegion = false;
  138. bool LoopStart = false;
  139. bool BodyComplete = false;
  140. SourceLocation InnerTeamsRegionLoc;
  141. /// Reference to the taskgroup task_reduction reference expression.
  142. Expr *TaskgroupReductionRef = nullptr;
  143. llvm::DenseSet<QualType> MappedClassesQualTypes;
  144. /// List of globals marked as declare target link in this target region
  145. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  146. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  147. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  148. Scope *CurScope, SourceLocation Loc)
  149. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  150. ConstructLoc(Loc) {}
  151. SharingMapTy() = default;
  152. };
  153. using StackTy = SmallVector<SharingMapTy, 4>;
  154. /// Stack of used declaration and their data-sharing attributes.
  155. DeclSAMapTy Threadprivates;
  156. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  157. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  158. /// true, if check for DSA must be from parent directive, false, if
  159. /// from current directive.
  160. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  161. Sema &SemaRef;
  162. bool ForceCapturing = false;
  163. /// true if all the variables in the target executable directives must be
  164. /// captured by reference.
  165. bool ForceCaptureByReferenceInTargetExecutable = false;
  166. CriticalsWithHintsTy Criticals;
  167. unsigned IgnoredStackElements = 0;
  168. /// Iterators over the stack iterate in order from innermost to outermost
  169. /// directive.
  170. using const_iterator = StackTy::const_reverse_iterator;
  171. const_iterator begin() const {
  172. return Stack.empty() ? const_iterator()
  173. : Stack.back().first.rbegin() + IgnoredStackElements;
  174. }
  175. const_iterator end() const {
  176. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  177. }
  178. using iterator = StackTy::reverse_iterator;
  179. iterator begin() {
  180. return Stack.empty() ? iterator()
  181. : Stack.back().first.rbegin() + IgnoredStackElements;
  182. }
  183. iterator end() {
  184. return Stack.empty() ? iterator() : Stack.back().first.rend();
  185. }
  186. // Convenience operations to get at the elements of the stack.
  187. bool isStackEmpty() const {
  188. return Stack.empty() ||
  189. Stack.back().second != CurrentNonCapturingFunctionScope ||
  190. Stack.back().first.size() <= IgnoredStackElements;
  191. }
  192. size_t getStackSize() const {
  193. return isStackEmpty() ? 0
  194. : Stack.back().first.size() - IgnoredStackElements;
  195. }
  196. SharingMapTy *getTopOfStackOrNull() {
  197. size_t Size = getStackSize();
  198. if (Size == 0)
  199. return nullptr;
  200. return &Stack.back().first[Size - 1];
  201. }
  202. const SharingMapTy *getTopOfStackOrNull() const {
  203. return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
  204. }
  205. SharingMapTy &getTopOfStack() {
  206. assert(!isStackEmpty() && "no current directive");
  207. return *getTopOfStackOrNull();
  208. }
  209. const SharingMapTy &getTopOfStack() const {
  210. return const_cast<DSAStackTy&>(*this).getTopOfStack();
  211. }
  212. SharingMapTy *getSecondOnStackOrNull() {
  213. size_t Size = getStackSize();
  214. if (Size <= 1)
  215. return nullptr;
  216. return &Stack.back().first[Size - 2];
  217. }
  218. const SharingMapTy *getSecondOnStackOrNull() const {
  219. return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
  220. }
  221. /// Get the stack element at a certain level (previously returned by
  222. /// \c getNestingLevel).
  223. ///
  224. /// Note that nesting levels count from outermost to innermost, and this is
  225. /// the reverse of our iteration order where new inner levels are pushed at
  226. /// the front of the stack.
  227. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  228. assert(Level < getStackSize() && "no such stack element");
  229. return Stack.back().first[Level];
  230. }
  231. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  232. return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
  233. }
  234. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  235. /// Checks if the variable is a local for OpenMP region.
  236. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  237. /// Vector of previously declared requires directives
  238. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  239. /// omp_allocator_handle_t type.
  240. QualType OMPAllocatorHandleT;
  241. /// Expression for the predefined allocators.
  242. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  243. nullptr};
  244. /// Vector of previously encountered target directives
  245. SmallVector<SourceLocation, 2> TargetLocations;
  246. public:
  247. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  248. /// Sets omp_allocator_handle_t type.
  249. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  250. /// Gets omp_allocator_handle_t type.
  251. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  252. /// Sets the given default allocator.
  253. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  254. Expr *Allocator) {
  255. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  256. }
  257. /// Returns the specified default allocator.
  258. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  259. return OMPPredefinedAllocators[AllocatorKind];
  260. }
  261. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  262. OpenMPClauseKind getClauseParsingMode() const {
  263. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  264. return ClauseKindMode;
  265. }
  266. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  267. bool isBodyComplete() const {
  268. const SharingMapTy *Top = getTopOfStackOrNull();
  269. return Top && Top->BodyComplete;
  270. }
  271. void setBodyComplete() {
  272. getTopOfStack().BodyComplete = true;
  273. }
  274. bool isForceVarCapturing() const { return ForceCapturing; }
  275. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  276. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  277. ForceCaptureByReferenceInTargetExecutable = V;
  278. }
  279. bool isForceCaptureByReferenceInTargetExecutable() const {
  280. return ForceCaptureByReferenceInTargetExecutable;
  281. }
  282. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  283. Scope *CurScope, SourceLocation Loc) {
  284. assert(!IgnoredStackElements &&
  285. "cannot change stack while ignoring elements");
  286. if (Stack.empty() ||
  287. Stack.back().second != CurrentNonCapturingFunctionScope)
  288. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  289. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  290. Stack.back().first.back().DefaultAttrLoc = Loc;
  291. }
  292. void pop() {
  293. assert(!IgnoredStackElements &&
  294. "cannot change stack while ignoring elements");
  295. assert(!Stack.back().first.empty() &&
  296. "Data-sharing attributes stack is empty!");
  297. Stack.back().first.pop_back();
  298. }
  299. /// RAII object to temporarily leave the scope of a directive when we want to
  300. /// logically operate in its parent.
  301. class ParentDirectiveScope {
  302. DSAStackTy &Self;
  303. bool Active;
  304. public:
  305. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  306. : Self(Self), Active(false) {
  307. if (Activate)
  308. enable();
  309. }
  310. ~ParentDirectiveScope() { disable(); }
  311. void disable() {
  312. if (Active) {
  313. --Self.IgnoredStackElements;
  314. Active = false;
  315. }
  316. }
  317. void enable() {
  318. if (!Active) {
  319. ++Self.IgnoredStackElements;
  320. Active = true;
  321. }
  322. }
  323. };
  324. /// Marks that we're started loop parsing.
  325. void loopInit() {
  326. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  327. "Expected loop-based directive.");
  328. getTopOfStack().LoopStart = true;
  329. }
  330. /// Start capturing of the variables in the loop context.
  331. void loopStart() {
  332. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  333. "Expected loop-based directive.");
  334. getTopOfStack().LoopStart = false;
  335. }
  336. /// true, if variables are captured, false otherwise.
  337. bool isLoopStarted() const {
  338. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  339. "Expected loop-based directive.");
  340. return !getTopOfStack().LoopStart;
  341. }
  342. /// Marks (or clears) declaration as possibly loop counter.
  343. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  344. getTopOfStack().PossiblyLoopCounter =
  345. D ? D->getCanonicalDecl() : D;
  346. }
  347. /// Gets the possible loop counter decl.
  348. const Decl *getPossiblyLoopCunter() const {
  349. return getTopOfStack().PossiblyLoopCounter;
  350. }
  351. /// Start new OpenMP region stack in new non-capturing function.
  352. void pushFunction() {
  353. assert(!IgnoredStackElements &&
  354. "cannot change stack while ignoring elements");
  355. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  356. assert(!isa<CapturingScopeInfo>(CurFnScope));
  357. CurrentNonCapturingFunctionScope = CurFnScope;
  358. }
  359. /// Pop region stack for non-capturing function.
  360. void popFunction(const FunctionScopeInfo *OldFSI) {
  361. assert(!IgnoredStackElements &&
  362. "cannot change stack while ignoring elements");
  363. if (!Stack.empty() && Stack.back().second == OldFSI) {
  364. assert(Stack.back().first.empty());
  365. Stack.pop_back();
  366. }
  367. CurrentNonCapturingFunctionScope = nullptr;
  368. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  369. if (!isa<CapturingScopeInfo>(FSI)) {
  370. CurrentNonCapturingFunctionScope = FSI;
  371. break;
  372. }
  373. }
  374. }
  375. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  376. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  377. }
  378. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  379. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  380. auto I = Criticals.find(Name.getAsString());
  381. if (I != Criticals.end())
  382. return I->second;
  383. return std::make_pair(nullptr, llvm::APSInt());
  384. }
  385. /// If 'aligned' declaration for given variable \a D was not seen yet,
  386. /// add it and return NULL; otherwise return previous occurrence's expression
  387. /// for diagnostics.
  388. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  389. /// Register specified variable as loop control variable.
  390. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  391. /// Check if the specified variable is a loop control variable for
  392. /// current region.
  393. /// \return The index of the loop control variable in the list of associated
  394. /// for-loops (from outer to inner).
  395. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  396. /// Check if the specified variable is a loop control variable for
  397. /// parent region.
  398. /// \return The index of the loop control variable in the list of associated
  399. /// for-loops (from outer to inner).
  400. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  401. /// Get the loop control variable for the I-th loop (or nullptr) in
  402. /// parent directive.
  403. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  404. /// Adds explicit data sharing attribute to the specified declaration.
  405. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  406. DeclRefExpr *PrivateCopy = nullptr);
  407. /// Adds additional information for the reduction items with the reduction id
  408. /// represented as an operator.
  409. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  410. BinaryOperatorKind BOK);
  411. /// Adds additional information for the reduction items with the reduction id
  412. /// represented as reduction identifier.
  413. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  414. const Expr *ReductionRef);
  415. /// Returns the location and reduction operation from the innermost parent
  416. /// region for the given \p D.
  417. const DSAVarData
  418. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  419. BinaryOperatorKind &BOK,
  420. Expr *&TaskgroupDescriptor) const;
  421. /// Returns the location and reduction operation from the innermost parent
  422. /// region for the given \p D.
  423. const DSAVarData
  424. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  425. const Expr *&ReductionRef,
  426. Expr *&TaskgroupDescriptor) const;
  427. /// Return reduction reference expression for the current taskgroup.
  428. Expr *getTaskgroupReductionRef() const {
  429. assert(getTopOfStack().Directive == OMPD_taskgroup &&
  430. "taskgroup reference expression requested for non taskgroup "
  431. "directive.");
  432. return getTopOfStack().TaskgroupReductionRef;
  433. }
  434. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  435. /// descriptor variable at the \p Level of OpenMP regions.
  436. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  437. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  438. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  439. ->getDecl() == VD;
  440. }
  441. /// Returns data sharing attributes from top of the stack for the
  442. /// specified declaration.
  443. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  444. /// Returns data-sharing attributes for the specified declaration.
  445. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  446. /// Checks if the specified variables has data-sharing attributes which
  447. /// match specified \a CPred predicate in any directive which matches \a DPred
  448. /// predicate.
  449. const DSAVarData
  450. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  451. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  452. bool FromParent) const;
  453. /// Checks if the specified variables has data-sharing attributes which
  454. /// match specified \a CPred predicate in any innermost directive which
  455. /// matches \a DPred predicate.
  456. const DSAVarData
  457. hasInnermostDSA(ValueDecl *D,
  458. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  459. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  460. bool FromParent) const;
  461. /// Checks if the specified variables has explicit data-sharing
  462. /// attributes which match specified \a CPred predicate at the specified
  463. /// OpenMP region.
  464. bool hasExplicitDSA(const ValueDecl *D,
  465. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  466. unsigned Level, bool NotLastprivate = false) const;
  467. /// Returns true if the directive at level \Level matches in the
  468. /// specified \a DPred predicate.
  469. bool hasExplicitDirective(
  470. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  471. unsigned Level) const;
  472. /// Finds a directive which matches specified \a DPred predicate.
  473. bool hasDirective(
  474. const llvm::function_ref<bool(
  475. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  476. DPred,
  477. bool FromParent) const;
  478. /// Returns currently analyzed directive.
  479. OpenMPDirectiveKind getCurrentDirective() const {
  480. const SharingMapTy *Top = getTopOfStackOrNull();
  481. return Top ? Top->Directive : OMPD_unknown;
  482. }
  483. /// Returns directive kind at specified level.
  484. OpenMPDirectiveKind getDirective(unsigned Level) const {
  485. assert(!isStackEmpty() && "No directive at specified level.");
  486. return getStackElemAtLevel(Level).Directive;
  487. }
  488. /// Returns the capture region at the specified level.
  489. OpenMPDirectiveKind getCaptureRegion(unsigned Level,
  490. unsigned OpenMPCaptureLevel) const {
  491. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  492. getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
  493. return CaptureRegions[OpenMPCaptureLevel];
  494. }
  495. /// Returns parent directive.
  496. OpenMPDirectiveKind getParentDirective() const {
  497. const SharingMapTy *Parent = getSecondOnStackOrNull();
  498. return Parent ? Parent->Directive : OMPD_unknown;
  499. }
  500. /// Add requires decl to internal vector
  501. void addRequiresDecl(OMPRequiresDecl *RD) {
  502. RequiresDecls.push_back(RD);
  503. }
  504. /// Checks if the defined 'requires' directive has specified type of clause.
  505. template <typename ClauseType>
  506. bool hasRequiresDeclWithClause() {
  507. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  508. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  509. return isa<ClauseType>(C);
  510. });
  511. });
  512. }
  513. /// Checks for a duplicate clause amongst previously declared requires
  514. /// directives
  515. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  516. bool IsDuplicate = false;
  517. for (OMPClause *CNew : ClauseList) {
  518. for (const OMPRequiresDecl *D : RequiresDecls) {
  519. for (const OMPClause *CPrev : D->clauselists()) {
  520. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  521. SemaRef.Diag(CNew->getBeginLoc(),
  522. diag::err_omp_requires_clause_redeclaration)
  523. << getOpenMPClauseName(CNew->getClauseKind());
  524. SemaRef.Diag(CPrev->getBeginLoc(),
  525. diag::note_omp_requires_previous_clause)
  526. << getOpenMPClauseName(CPrev->getClauseKind());
  527. IsDuplicate = true;
  528. }
  529. }
  530. }
  531. }
  532. return IsDuplicate;
  533. }
  534. /// Add location of previously encountered target to internal vector
  535. void addTargetDirLocation(SourceLocation LocStart) {
  536. TargetLocations.push_back(LocStart);
  537. }
  538. // Return previously encountered target region locations.
  539. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  540. return TargetLocations;
  541. }
  542. /// Set default data sharing attribute to none.
  543. void setDefaultDSANone(SourceLocation Loc) {
  544. getTopOfStack().DefaultAttr = DSA_none;
  545. getTopOfStack().DefaultAttrLoc = Loc;
  546. }
  547. /// Set default data sharing attribute to shared.
  548. void setDefaultDSAShared(SourceLocation Loc) {
  549. getTopOfStack().DefaultAttr = DSA_shared;
  550. getTopOfStack().DefaultAttrLoc = Loc;
  551. }
  552. /// Set default data mapping attribute to 'tofrom:scalar'.
  553. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  554. getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
  555. getTopOfStack().DefaultMapAttrLoc = Loc;
  556. }
  557. DefaultDataSharingAttributes getDefaultDSA() const {
  558. return isStackEmpty() ? DSA_unspecified
  559. : getTopOfStack().DefaultAttr;
  560. }
  561. SourceLocation getDefaultDSALocation() const {
  562. return isStackEmpty() ? SourceLocation()
  563. : getTopOfStack().DefaultAttrLoc;
  564. }
  565. DefaultMapAttributes getDefaultDMA() const {
  566. return isStackEmpty() ? DMA_unspecified
  567. : getTopOfStack().DefaultMapAttr;
  568. }
  569. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  570. return getStackElemAtLevel(Level).DefaultMapAttr;
  571. }
  572. SourceLocation getDefaultDMALocation() const {
  573. return isStackEmpty() ? SourceLocation()
  574. : getTopOfStack().DefaultMapAttrLoc;
  575. }
  576. /// Checks if the specified variable is a threadprivate.
  577. bool isThreadPrivate(VarDecl *D) {
  578. const DSAVarData DVar = getTopDSA(D, false);
  579. return isOpenMPThreadPrivate(DVar.CKind);
  580. }
  581. /// Marks current region as ordered (it has an 'ordered' clause).
  582. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  583. OMPOrderedClause *Clause) {
  584. if (IsOrdered)
  585. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  586. else
  587. getTopOfStack().OrderedRegion.reset();
  588. }
  589. /// Returns true, if region is ordered (has associated 'ordered' clause),
  590. /// false - otherwise.
  591. bool isOrderedRegion() const {
  592. if (const SharingMapTy *Top = getTopOfStackOrNull())
  593. return Top->OrderedRegion.hasValue();
  594. return false;
  595. }
  596. /// Returns optional parameter for the ordered region.
  597. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  598. if (const SharingMapTy *Top = getTopOfStackOrNull())
  599. if (Top->OrderedRegion.hasValue())
  600. return Top->OrderedRegion.getValue();
  601. return std::make_pair(nullptr, nullptr);
  602. }
  603. /// Returns true, if parent region is ordered (has associated
  604. /// 'ordered' clause), false - otherwise.
  605. bool isParentOrderedRegion() const {
  606. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  607. return Parent->OrderedRegion.hasValue();
  608. return false;
  609. }
  610. /// Returns optional parameter for the ordered region.
  611. std::pair<const Expr *, OMPOrderedClause *>
  612. getParentOrderedRegionParam() const {
  613. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  614. if (Parent->OrderedRegion.hasValue())
  615. return Parent->OrderedRegion.getValue();
  616. return std::make_pair(nullptr, nullptr);
  617. }
  618. /// Marks current region as nowait (it has a 'nowait' clause).
  619. void setNowaitRegion(bool IsNowait = true) {
  620. getTopOfStack().NowaitRegion = IsNowait;
  621. }
  622. /// Returns true, if parent region is nowait (has associated
  623. /// 'nowait' clause), false - otherwise.
  624. bool isParentNowaitRegion() const {
  625. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  626. return Parent->NowaitRegion;
  627. return false;
  628. }
  629. /// Marks parent region as cancel region.
  630. void setParentCancelRegion(bool Cancel = true) {
  631. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  632. Parent->CancelRegion |= Cancel;
  633. }
  634. /// Return true if current region has inner cancel construct.
  635. bool isCancelRegion() const {
  636. const SharingMapTy *Top = getTopOfStackOrNull();
  637. return Top ? Top->CancelRegion : false;
  638. }
  639. /// Set collapse value for the region.
  640. void setAssociatedLoops(unsigned Val) {
  641. getTopOfStack().AssociatedLoops = Val;
  642. if (Val > 1)
  643. getTopOfStack().HasMutipleLoops = true;
  644. }
  645. /// Return collapse value for region.
  646. unsigned getAssociatedLoops() const {
  647. const SharingMapTy *Top = getTopOfStackOrNull();
  648. return Top ? Top->AssociatedLoops : 0;
  649. }
  650. /// Returns true if the construct is associated with multiple loops.
  651. bool hasMutipleLoops() const {
  652. const SharingMapTy *Top = getTopOfStackOrNull();
  653. return Top ? Top->HasMutipleLoops : false;
  654. }
  655. /// Marks current target region as one with closely nested teams
  656. /// region.
  657. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  658. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  659. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  660. }
  661. /// Returns true, if current region has closely nested teams region.
  662. bool hasInnerTeamsRegion() const {
  663. return getInnerTeamsRegionLoc().isValid();
  664. }
  665. /// Returns location of the nested teams region (if any).
  666. SourceLocation getInnerTeamsRegionLoc() const {
  667. const SharingMapTy *Top = getTopOfStackOrNull();
  668. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  669. }
  670. Scope *getCurScope() const {
  671. const SharingMapTy *Top = getTopOfStackOrNull();
  672. return Top ? Top->CurScope : nullptr;
  673. }
  674. SourceLocation getConstructLoc() const {
  675. const SharingMapTy *Top = getTopOfStackOrNull();
  676. return Top ? Top->ConstructLoc : SourceLocation();
  677. }
  678. /// Do the check specified in \a Check to all component lists and return true
  679. /// if any issue is found.
  680. bool checkMappableExprComponentListsForDecl(
  681. const ValueDecl *VD, bool CurrentRegionOnly,
  682. const llvm::function_ref<
  683. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  684. OpenMPClauseKind)>
  685. Check) const {
  686. if (isStackEmpty())
  687. return false;
  688. auto SI = begin();
  689. auto SE = end();
  690. if (SI == SE)
  691. return false;
  692. if (CurrentRegionOnly)
  693. SE = std::next(SI);
  694. else
  695. std::advance(SI, 1);
  696. for (; SI != SE; ++SI) {
  697. auto MI = SI->MappedExprComponents.find(VD);
  698. if (MI != SI->MappedExprComponents.end())
  699. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  700. MI->second.Components)
  701. if (Check(L, MI->second.Kind))
  702. return true;
  703. }
  704. return false;
  705. }
  706. /// Do the check specified in \a Check to all component lists at a given level
  707. /// and return true if any issue is found.
  708. bool checkMappableExprComponentListsForDeclAtLevel(
  709. const ValueDecl *VD, unsigned Level,
  710. const llvm::function_ref<
  711. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  712. OpenMPClauseKind)>
  713. Check) const {
  714. if (getStackSize() <= Level)
  715. return false;
  716. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  717. auto MI = StackElem.MappedExprComponents.find(VD);
  718. if (MI != StackElem.MappedExprComponents.end())
  719. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  720. MI->second.Components)
  721. if (Check(L, MI->second.Kind))
  722. return true;
  723. return false;
  724. }
  725. /// Create a new mappable expression component list associated with a given
  726. /// declaration and initialize it with the provided list of components.
  727. void addMappableExpressionComponents(
  728. const ValueDecl *VD,
  729. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  730. OpenMPClauseKind WhereFoundClauseKind) {
  731. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  732. // Create new entry and append the new components there.
  733. MEC.Components.resize(MEC.Components.size() + 1);
  734. MEC.Components.back().append(Components.begin(), Components.end());
  735. MEC.Kind = WhereFoundClauseKind;
  736. }
  737. unsigned getNestingLevel() const {
  738. assert(!isStackEmpty());
  739. return getStackSize() - 1;
  740. }
  741. void addDoacrossDependClause(OMPDependClause *C,
  742. const OperatorOffsetTy &OpsOffs) {
  743. SharingMapTy *Parent = getSecondOnStackOrNull();
  744. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  745. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  746. }
  747. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  748. getDoacrossDependClauses() const {
  749. const SharingMapTy &StackElem = getTopOfStack();
  750. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  751. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  752. return llvm::make_range(Ref.begin(), Ref.end());
  753. }
  754. return llvm::make_range(StackElem.DoacrossDepends.end(),
  755. StackElem.DoacrossDepends.end());
  756. }
  757. // Store types of classes which have been explicitly mapped
  758. void addMappedClassesQualTypes(QualType QT) {
  759. SharingMapTy &StackElem = getTopOfStack();
  760. StackElem.MappedClassesQualTypes.insert(QT);
  761. }
  762. // Return set of mapped classes types
  763. bool isClassPreviouslyMapped(QualType QT) const {
  764. const SharingMapTy &StackElem = getTopOfStack();
  765. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  766. }
  767. /// Adds global declare target to the parent target region.
  768. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  769. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  770. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  771. "Expected declare target link global.");
  772. for (auto &Elem : *this) {
  773. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  774. Elem.DeclareTargetLinkVarDecls.push_back(E);
  775. return;
  776. }
  777. }
  778. }
  779. /// Returns the list of globals with declare target link if current directive
  780. /// is target.
  781. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  782. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  783. "Expected target executable directive.");
  784. return getTopOfStack().DeclareTargetLinkVarDecls;
  785. }
  786. };
  787. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  788. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  789. }
  790. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  791. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  792. DKind == OMPD_unknown;
  793. }
  794. } // namespace
  795. static const Expr *getExprAsWritten(const Expr *E) {
  796. if (const auto *FE = dyn_cast<FullExpr>(E))
  797. E = FE->getSubExpr();
  798. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  799. E = MTE->GetTemporaryExpr();
  800. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  801. E = Binder->getSubExpr();
  802. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  803. E = ICE->getSubExprAsWritten();
  804. return E->IgnoreParens();
  805. }
  806. static Expr *getExprAsWritten(Expr *E) {
  807. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  808. }
  809. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  810. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  811. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  812. D = ME->getMemberDecl();
  813. const auto *VD = dyn_cast<VarDecl>(D);
  814. const auto *FD = dyn_cast<FieldDecl>(D);
  815. if (VD != nullptr) {
  816. VD = VD->getCanonicalDecl();
  817. D = VD;
  818. } else {
  819. assert(FD);
  820. FD = FD->getCanonicalDecl();
  821. D = FD;
  822. }
  823. return D;
  824. }
  825. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  826. return const_cast<ValueDecl *>(
  827. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  828. }
  829. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  830. ValueDecl *D) const {
  831. D = getCanonicalDecl(D);
  832. auto *VD = dyn_cast<VarDecl>(D);
  833. const auto *FD = dyn_cast<FieldDecl>(D);
  834. DSAVarData DVar;
  835. if (Iter == end()) {
  836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  837. // in a region but not in construct]
  838. // File-scope or namespace-scope variables referenced in called routines
  839. // in the region are shared unless they appear in a threadprivate
  840. // directive.
  841. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  842. DVar.CKind = OMPC_shared;
  843. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  844. // in a region but not in construct]
  845. // Variables with static storage duration that are declared in called
  846. // routines in the region are shared.
  847. if (VD && VD->hasGlobalStorage())
  848. DVar.CKind = OMPC_shared;
  849. // Non-static data members are shared by default.
  850. if (FD)
  851. DVar.CKind = OMPC_shared;
  852. return DVar;
  853. }
  854. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  855. // in a Construct, C/C++, predetermined, p.1]
  856. // Variables with automatic storage duration that are declared in a scope
  857. // inside the construct are private.
  858. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  859. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  860. DVar.CKind = OMPC_private;
  861. return DVar;
  862. }
  863. DVar.DKind = Iter->Directive;
  864. // Explicitly specified attributes and local variables with predetermined
  865. // attributes.
  866. if (Iter->SharingMap.count(D)) {
  867. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  868. DVar.RefExpr = Data.RefExpr.getPointer();
  869. DVar.PrivateCopy = Data.PrivateCopy;
  870. DVar.CKind = Data.Attributes;
  871. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  872. return DVar;
  873. }
  874. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  875. // in a Construct, C/C++, implicitly determined, p.1]
  876. // In a parallel or task construct, the data-sharing attributes of these
  877. // variables are determined by the default clause, if present.
  878. switch (Iter->DefaultAttr) {
  879. case DSA_shared:
  880. DVar.CKind = OMPC_shared;
  881. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  882. return DVar;
  883. case DSA_none:
  884. return DVar;
  885. case DSA_unspecified:
  886. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  887. // in a Construct, implicitly determined, p.2]
  888. // In a parallel construct, if no default clause is present, these
  889. // variables are shared.
  890. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  891. if (isOpenMPParallelDirective(DVar.DKind) ||
  892. isOpenMPTeamsDirective(DVar.DKind)) {
  893. DVar.CKind = OMPC_shared;
  894. return DVar;
  895. }
  896. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  897. // in a Construct, implicitly determined, p.4]
  898. // In a task construct, if no default clause is present, a variable that in
  899. // the enclosing context is determined to be shared by all implicit tasks
  900. // bound to the current team is shared.
  901. if (isOpenMPTaskingDirective(DVar.DKind)) {
  902. DSAVarData DVarTemp;
  903. const_iterator I = Iter, E = end();
  904. do {
  905. ++I;
  906. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  907. // Referenced in a Construct, implicitly determined, p.6]
  908. // In a task construct, if no default clause is present, a variable
  909. // whose data-sharing attribute is not determined by the rules above is
  910. // firstprivate.
  911. DVarTemp = getDSA(I, D);
  912. if (DVarTemp.CKind != OMPC_shared) {
  913. DVar.RefExpr = nullptr;
  914. DVar.CKind = OMPC_firstprivate;
  915. return DVar;
  916. }
  917. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  918. DVar.CKind =
  919. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  920. return DVar;
  921. }
  922. }
  923. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  924. // in a Construct, implicitly determined, p.3]
  925. // For constructs other than task, if no default clause is present, these
  926. // variables inherit their data-sharing attributes from the enclosing
  927. // context.
  928. return getDSA(++Iter, D);
  929. }
  930. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  931. const Expr *NewDE) {
  932. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  933. D = getCanonicalDecl(D);
  934. SharingMapTy &StackElem = getTopOfStack();
  935. auto It = StackElem.AlignedMap.find(D);
  936. if (It == StackElem.AlignedMap.end()) {
  937. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  938. StackElem.AlignedMap[D] = NewDE;
  939. return nullptr;
  940. }
  941. assert(It->second && "Unexpected nullptr expr in the aligned map");
  942. return It->second;
  943. }
  944. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  945. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  946. D = getCanonicalDecl(D);
  947. SharingMapTy &StackElem = getTopOfStack();
  948. StackElem.LCVMap.try_emplace(
  949. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  950. }
  951. const DSAStackTy::LCDeclInfo
  952. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  953. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  954. D = getCanonicalDecl(D);
  955. const SharingMapTy &StackElem = getTopOfStack();
  956. auto It = StackElem.LCVMap.find(D);
  957. if (It != StackElem.LCVMap.end())
  958. return It->second;
  959. return {0, nullptr};
  960. }
  961. const DSAStackTy::LCDeclInfo
  962. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  963. const SharingMapTy *Parent = getSecondOnStackOrNull();
  964. assert(Parent && "Data-sharing attributes stack is empty");
  965. D = getCanonicalDecl(D);
  966. auto It = Parent->LCVMap.find(D);
  967. if (It != Parent->LCVMap.end())
  968. return It->second;
  969. return {0, nullptr};
  970. }
  971. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  972. const SharingMapTy *Parent = getSecondOnStackOrNull();
  973. assert(Parent && "Data-sharing attributes stack is empty");
  974. if (Parent->LCVMap.size() < I)
  975. return nullptr;
  976. for (const auto &Pair : Parent->LCVMap)
  977. if (Pair.second.first == I)
  978. return Pair.first;
  979. return nullptr;
  980. }
  981. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  982. DeclRefExpr *PrivateCopy) {
  983. D = getCanonicalDecl(D);
  984. if (A == OMPC_threadprivate) {
  985. DSAInfo &Data = Threadprivates[D];
  986. Data.Attributes = A;
  987. Data.RefExpr.setPointer(E);
  988. Data.PrivateCopy = nullptr;
  989. } else {
  990. DSAInfo &Data = getTopOfStack().SharingMap[D];
  991. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  992. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  993. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  994. (isLoopControlVariable(D).first && A == OMPC_private));
  995. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  996. Data.RefExpr.setInt(/*IntVal=*/true);
  997. return;
  998. }
  999. const bool IsLastprivate =
  1000. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1001. Data.Attributes = A;
  1002. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1003. Data.PrivateCopy = PrivateCopy;
  1004. if (PrivateCopy) {
  1005. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1006. Data.Attributes = A;
  1007. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1008. Data.PrivateCopy = nullptr;
  1009. }
  1010. }
  1011. }
  1012. /// Build a variable declaration for OpenMP loop iteration variable.
  1013. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1014. StringRef Name, const AttrVec *Attrs = nullptr,
  1015. DeclRefExpr *OrigRef = nullptr) {
  1016. DeclContext *DC = SemaRef.CurContext;
  1017. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1018. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1019. auto *Decl =
  1020. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1021. if (Attrs) {
  1022. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1023. I != E; ++I)
  1024. Decl->addAttr(*I);
  1025. }
  1026. Decl->setImplicit();
  1027. if (OrigRef) {
  1028. Decl->addAttr(
  1029. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1030. }
  1031. return Decl;
  1032. }
  1033. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1034. SourceLocation Loc,
  1035. bool RefersToCapture = false) {
  1036. D->setReferenced();
  1037. D->markUsed(S.Context);
  1038. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1039. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1040. VK_LValue);
  1041. }
  1042. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1043. BinaryOperatorKind BOK) {
  1044. D = getCanonicalDecl(D);
  1045. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1046. assert(
  1047. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1048. "Additional reduction info may be specified only for reduction items.");
  1049. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1050. assert(ReductionData.ReductionRange.isInvalid() &&
  1051. getTopOfStack().Directive == OMPD_taskgroup &&
  1052. "Additional reduction info may be specified only once for reduction "
  1053. "items.");
  1054. ReductionData.set(BOK, SR);
  1055. Expr *&TaskgroupReductionRef =
  1056. getTopOfStack().TaskgroupReductionRef;
  1057. if (!TaskgroupReductionRef) {
  1058. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1059. SemaRef.Context.VoidPtrTy, ".task_red.");
  1060. TaskgroupReductionRef =
  1061. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1062. }
  1063. }
  1064. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1065. const Expr *ReductionRef) {
  1066. D = getCanonicalDecl(D);
  1067. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1068. assert(
  1069. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1070. "Additional reduction info may be specified only for reduction items.");
  1071. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1072. assert(ReductionData.ReductionRange.isInvalid() &&
  1073. getTopOfStack().Directive == OMPD_taskgroup &&
  1074. "Additional reduction info may be specified only once for reduction "
  1075. "items.");
  1076. ReductionData.set(ReductionRef, SR);
  1077. Expr *&TaskgroupReductionRef =
  1078. getTopOfStack().TaskgroupReductionRef;
  1079. if (!TaskgroupReductionRef) {
  1080. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1081. SemaRef.Context.VoidPtrTy, ".task_red.");
  1082. TaskgroupReductionRef =
  1083. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1084. }
  1085. }
  1086. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1087. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1088. Expr *&TaskgroupDescriptor) const {
  1089. D = getCanonicalDecl(D);
  1090. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1091. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1092. const DSAInfo &Data = I->SharingMap.lookup(D);
  1093. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1094. continue;
  1095. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1096. if (!ReductionData.ReductionOp ||
  1097. ReductionData.ReductionOp.is<const Expr *>())
  1098. return DSAVarData();
  1099. SR = ReductionData.ReductionRange;
  1100. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1101. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1102. "expression for the descriptor is not "
  1103. "set.");
  1104. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1105. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1106. Data.PrivateCopy, I->DefaultAttrLoc);
  1107. }
  1108. return DSAVarData();
  1109. }
  1110. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1111. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1112. Expr *&TaskgroupDescriptor) const {
  1113. D = getCanonicalDecl(D);
  1114. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1115. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1116. const DSAInfo &Data = I->SharingMap.lookup(D);
  1117. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1118. continue;
  1119. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1120. if (!ReductionData.ReductionOp ||
  1121. !ReductionData.ReductionOp.is<const Expr *>())
  1122. return DSAVarData();
  1123. SR = ReductionData.ReductionRange;
  1124. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1125. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1126. "expression for the descriptor is not "
  1127. "set.");
  1128. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1129. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1130. Data.PrivateCopy, I->DefaultAttrLoc);
  1131. }
  1132. return DSAVarData();
  1133. }
  1134. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1135. D = D->getCanonicalDecl();
  1136. for (const_iterator E = end(); I != E; ++I) {
  1137. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1138. isOpenMPTargetExecutionDirective(I->Directive)) {
  1139. Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1140. Scope *CurScope = getCurScope();
  1141. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1142. CurScope = CurScope->getParent();
  1143. return CurScope != TopScope;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1149. bool AcceptIfMutable = true,
  1150. bool *IsClassType = nullptr) {
  1151. ASTContext &Context = SemaRef.getASTContext();
  1152. Type = Type.getNonReferenceType().getCanonicalType();
  1153. bool IsConstant = Type.isConstant(Context);
  1154. Type = Context.getBaseElementType(Type);
  1155. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1156. ? Type->getAsCXXRecordDecl()
  1157. : nullptr;
  1158. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1159. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1160. RD = CTD->getTemplatedDecl();
  1161. if (IsClassType)
  1162. *IsClassType = RD;
  1163. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1164. RD->hasDefinition() && RD->hasMutableFields());
  1165. }
  1166. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1167. QualType Type, OpenMPClauseKind CKind,
  1168. SourceLocation ELoc,
  1169. bool AcceptIfMutable = true,
  1170. bool ListItemNotVar = false) {
  1171. ASTContext &Context = SemaRef.getASTContext();
  1172. bool IsClassType;
  1173. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1174. unsigned Diag = ListItemNotVar
  1175. ? diag::err_omp_const_list_item
  1176. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1177. : diag::err_omp_const_variable;
  1178. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1179. if (!ListItemNotVar && D) {
  1180. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1181. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1182. VarDecl::DeclarationOnly;
  1183. SemaRef.Diag(D->getLocation(),
  1184. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1185. << D;
  1186. }
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1192. bool FromParent) {
  1193. D = getCanonicalDecl(D);
  1194. DSAVarData DVar;
  1195. auto *VD = dyn_cast<VarDecl>(D);
  1196. auto TI = Threadprivates.find(D);
  1197. if (TI != Threadprivates.end()) {
  1198. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1199. DVar.CKind = OMPC_threadprivate;
  1200. return DVar;
  1201. }
  1202. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1203. DVar.RefExpr = buildDeclRefExpr(
  1204. SemaRef, VD, D->getType().getNonReferenceType(),
  1205. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1206. DVar.CKind = OMPC_threadprivate;
  1207. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1208. return DVar;
  1209. }
  1210. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1211. // in a Construct, C/C++, predetermined, p.1]
  1212. // Variables appearing in threadprivate directives are threadprivate.
  1213. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1214. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1215. SemaRef.getLangOpts().OpenMPUseTLS &&
  1216. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1217. (VD && VD->getStorageClass() == SC_Register &&
  1218. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1219. DVar.RefExpr = buildDeclRefExpr(
  1220. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1221. DVar.CKind = OMPC_threadprivate;
  1222. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1223. return DVar;
  1224. }
  1225. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1226. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1227. !isLoopControlVariable(D).first) {
  1228. const_iterator IterTarget =
  1229. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1230. return isOpenMPTargetExecutionDirective(Data.Directive);
  1231. });
  1232. if (IterTarget != end()) {
  1233. const_iterator ParentIterTarget = IterTarget + 1;
  1234. for (const_iterator Iter = begin();
  1235. Iter != ParentIterTarget; ++Iter) {
  1236. if (isOpenMPLocal(VD, Iter)) {
  1237. DVar.RefExpr =
  1238. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1239. D->getLocation());
  1240. DVar.CKind = OMPC_threadprivate;
  1241. return DVar;
  1242. }
  1243. }
  1244. if (!isClauseParsingMode() || IterTarget != begin()) {
  1245. auto DSAIter = IterTarget->SharingMap.find(D);
  1246. if (DSAIter != IterTarget->SharingMap.end() &&
  1247. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1248. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1249. DVar.CKind = OMPC_threadprivate;
  1250. return DVar;
  1251. }
  1252. const_iterator End = end();
  1253. if (!SemaRef.isOpenMPCapturedByRef(
  1254. D, std::distance(ParentIterTarget, End),
  1255. /*OpenMPCaptureLevel=*/0)) {
  1256. DVar.RefExpr =
  1257. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1258. IterTarget->ConstructLoc);
  1259. DVar.CKind = OMPC_threadprivate;
  1260. return DVar;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. if (isStackEmpty())
  1266. // Not in OpenMP execution region and top scope was already checked.
  1267. return DVar;
  1268. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1269. // in a Construct, C/C++, predetermined, p.4]
  1270. // Static data members are shared.
  1271. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1272. // in a Construct, C/C++, predetermined, p.7]
  1273. // Variables with static storage duration that are declared in a scope
  1274. // inside the construct are shared.
  1275. if (VD && VD->isStaticDataMember()) {
  1276. // Check for explicitly specified attributes.
  1277. const_iterator I = begin();
  1278. const_iterator EndI = end();
  1279. if (FromParent && I != EndI)
  1280. ++I;
  1281. auto It = I->SharingMap.find(D);
  1282. if (It != I->SharingMap.end()) {
  1283. const DSAInfo &Data = It->getSecond();
  1284. DVar.RefExpr = Data.RefExpr.getPointer();
  1285. DVar.PrivateCopy = Data.PrivateCopy;
  1286. DVar.CKind = Data.Attributes;
  1287. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1288. DVar.DKind = I->Directive;
  1289. return DVar;
  1290. }
  1291. DVar.CKind = OMPC_shared;
  1292. return DVar;
  1293. }
  1294. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1295. // The predetermined shared attribute for const-qualified types having no
  1296. // mutable members was removed after OpenMP 3.1.
  1297. if (SemaRef.LangOpts.OpenMP <= 31) {
  1298. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1299. // in a Construct, C/C++, predetermined, p.6]
  1300. // Variables with const qualified type having no mutable member are
  1301. // shared.
  1302. if (isConstNotMutableType(SemaRef, D->getType())) {
  1303. // Variables with const-qualified type having no mutable member may be
  1304. // listed in a firstprivate clause, even if they are static data members.
  1305. DSAVarData DVarTemp = hasInnermostDSA(
  1306. D,
  1307. [](OpenMPClauseKind C) {
  1308. return C == OMPC_firstprivate || C == OMPC_shared;
  1309. },
  1310. MatchesAlways, FromParent);
  1311. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1312. return DVarTemp;
  1313. DVar.CKind = OMPC_shared;
  1314. return DVar;
  1315. }
  1316. }
  1317. // Explicitly specified attributes and local variables with predetermined
  1318. // attributes.
  1319. const_iterator I = begin();
  1320. const_iterator EndI = end();
  1321. if (FromParent && I != EndI)
  1322. ++I;
  1323. auto It = I->SharingMap.find(D);
  1324. if (It != I->SharingMap.end()) {
  1325. const DSAInfo &Data = It->getSecond();
  1326. DVar.RefExpr = Data.RefExpr.getPointer();
  1327. DVar.PrivateCopy = Data.PrivateCopy;
  1328. DVar.CKind = Data.Attributes;
  1329. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1330. DVar.DKind = I->Directive;
  1331. }
  1332. return DVar;
  1333. }
  1334. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1335. bool FromParent) const {
  1336. if (isStackEmpty()) {
  1337. const_iterator I;
  1338. return getDSA(I, D);
  1339. }
  1340. D = getCanonicalDecl(D);
  1341. const_iterator StartI = begin();
  1342. const_iterator EndI = end();
  1343. if (FromParent && StartI != EndI)
  1344. ++StartI;
  1345. return getDSA(StartI, D);
  1346. }
  1347. const DSAStackTy::DSAVarData
  1348. DSAStackTy::hasDSA(ValueDecl *D,
  1349. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1350. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1351. bool FromParent) const {
  1352. if (isStackEmpty())
  1353. return {};
  1354. D = getCanonicalDecl(D);
  1355. const_iterator I = begin();
  1356. const_iterator EndI = end();
  1357. if (FromParent && I != EndI)
  1358. ++I;
  1359. for (; I != EndI; ++I) {
  1360. if (!DPred(I->Directive) &&
  1361. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1362. continue;
  1363. const_iterator NewI = I;
  1364. DSAVarData DVar = getDSA(NewI, D);
  1365. if (I == NewI && CPred(DVar.CKind))
  1366. return DVar;
  1367. }
  1368. return {};
  1369. }
  1370. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1371. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1372. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1373. bool FromParent) const {
  1374. if (isStackEmpty())
  1375. return {};
  1376. D = getCanonicalDecl(D);
  1377. const_iterator StartI = begin();
  1378. const_iterator EndI = end();
  1379. if (FromParent && StartI != EndI)
  1380. ++StartI;
  1381. if (StartI == EndI || !DPred(StartI->Directive))
  1382. return {};
  1383. const_iterator NewI = StartI;
  1384. DSAVarData DVar = getDSA(NewI, D);
  1385. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1386. }
  1387. bool DSAStackTy::hasExplicitDSA(
  1388. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1389. unsigned Level, bool NotLastprivate) const {
  1390. if (getStackSize() <= Level)
  1391. return false;
  1392. D = getCanonicalDecl(D);
  1393. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1394. auto I = StackElem.SharingMap.find(D);
  1395. if (I != StackElem.SharingMap.end() &&
  1396. I->getSecond().RefExpr.getPointer() &&
  1397. CPred(I->getSecond().Attributes) &&
  1398. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1399. return true;
  1400. // Check predetermined rules for the loop control variables.
  1401. auto LI = StackElem.LCVMap.find(D);
  1402. if (LI != StackElem.LCVMap.end())
  1403. return CPred(OMPC_private);
  1404. return false;
  1405. }
  1406. bool DSAStackTy::hasExplicitDirective(
  1407. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1408. unsigned Level) const {
  1409. if (getStackSize() <= Level)
  1410. return false;
  1411. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1412. return DPred(StackElem.Directive);
  1413. }
  1414. bool DSAStackTy::hasDirective(
  1415. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1416. const DeclarationNameInfo &, SourceLocation)>
  1417. DPred,
  1418. bool FromParent) const {
  1419. // We look only in the enclosing region.
  1420. size_t Skip = FromParent ? 2 : 1;
  1421. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1422. I != E; ++I) {
  1423. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1424. return true;
  1425. }
  1426. return false;
  1427. }
  1428. void Sema::InitDataSharingAttributesStack() {
  1429. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1430. }
  1431. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1432. void Sema::pushOpenMPFunctionRegion() {
  1433. DSAStack->pushFunction();
  1434. }
  1435. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1436. DSAStack->popFunction(OldFSI);
  1437. }
  1438. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1439. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1440. "Expected OpenMP device compilation.");
  1441. return !S.isInOpenMPTargetExecutionDirective() &&
  1442. !S.isInOpenMPDeclareTargetContext();
  1443. }
  1444. namespace {
  1445. /// Status of the function emission on the host/device.
  1446. enum class FunctionEmissionStatus {
  1447. Emitted,
  1448. Discarded,
  1449. Unknown,
  1450. };
  1451. } // anonymous namespace
  1452. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1453. unsigned DiagID) {
  1454. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1455. "Expected OpenMP device compilation.");
  1456. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1457. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1458. switch (FES) {
  1459. case FunctionEmissionStatus::Emitted:
  1460. Kind = DeviceDiagBuilder::K_Immediate;
  1461. break;
  1462. case FunctionEmissionStatus::Unknown:
  1463. Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
  1464. : DeviceDiagBuilder::K_Immediate;
  1465. break;
  1466. case FunctionEmissionStatus::TemplateDiscarded:
  1467. case FunctionEmissionStatus::OMPDiscarded:
  1468. Kind = DeviceDiagBuilder::K_Nop;
  1469. break;
  1470. case FunctionEmissionStatus::CUDADiscarded:
  1471. llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
  1472. break;
  1473. }
  1474. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1475. }
  1476. Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1477. unsigned DiagID) {
  1478. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1479. "Expected OpenMP host compilation.");
  1480. FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
  1481. DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
  1482. switch (FES) {
  1483. case FunctionEmissionStatus::Emitted:
  1484. Kind = DeviceDiagBuilder::K_Immediate;
  1485. break;
  1486. case FunctionEmissionStatus::Unknown:
  1487. Kind = DeviceDiagBuilder::K_Deferred;
  1488. break;
  1489. case FunctionEmissionStatus::TemplateDiscarded:
  1490. case FunctionEmissionStatus::OMPDiscarded:
  1491. case FunctionEmissionStatus::CUDADiscarded:
  1492. Kind = DeviceDiagBuilder::K_Nop;
  1493. break;
  1494. }
  1495. return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
  1496. }
  1497. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
  1498. bool CheckForDelayedContext) {
  1499. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1500. "Expected OpenMP device compilation.");
  1501. assert(Callee && "Callee may not be null.");
  1502. Callee = Callee->getMostRecentDecl();
  1503. FunctionDecl *Caller = getCurFunctionDecl();
  1504. // host only function are not available on the device.
  1505. if (Caller) {
  1506. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1507. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1508. assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1509. CalleeS != FunctionEmissionStatus::CUDADiscarded &&
  1510. "CUDADiscarded unexpected in OpenMP device function check");
  1511. if ((CallerS == FunctionEmissionStatus::Emitted ||
  1512. (!isOpenMPDeviceDelayedContext(*this) &&
  1513. CallerS == FunctionEmissionStatus::Unknown)) &&
  1514. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1515. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1516. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1517. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  1518. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1519. diag::note_omp_marked_device_type_here)
  1520. << HostDevTy;
  1521. return;
  1522. }
  1523. }
  1524. // If the caller is known-emitted, mark the callee as known-emitted.
  1525. // Otherwise, mark the call in our call graph so we can traverse it later.
  1526. if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
  1527. (!Caller && !CheckForDelayedContext) ||
  1528. (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1529. markKnownEmitted(*this, Caller, Callee, Loc,
  1530. [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
  1531. return CheckForDelayedContext &&
  1532. S.getEmissionStatus(FD) ==
  1533. FunctionEmissionStatus::Emitted;
  1534. });
  1535. else if (Caller)
  1536. DeviceCallGraph[Caller].insert({Callee, Loc});
  1537. }
  1538. void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
  1539. bool CheckCaller) {
  1540. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1541. "Expected OpenMP host compilation.");
  1542. assert(Callee && "Callee may not be null.");
  1543. Callee = Callee->getMostRecentDecl();
  1544. FunctionDecl *Caller = getCurFunctionDecl();
  1545. // device only function are not available on the host.
  1546. if (Caller) {
  1547. FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
  1548. FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
  1549. assert(
  1550. (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
  1551. CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
  1552. "CUDADiscarded unexpected in OpenMP host function check");
  1553. if (CallerS == FunctionEmissionStatus::Emitted &&
  1554. CalleeS == FunctionEmissionStatus::OMPDiscarded) {
  1555. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1556. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1557. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  1558. Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1559. diag::note_omp_marked_device_type_here)
  1560. << NoHostDevTy;
  1561. return;
  1562. }
  1563. }
  1564. // If the caller is known-emitted, mark the callee as known-emitted.
  1565. // Otherwise, mark the call in our call graph so we can traverse it later.
  1566. if (!shouldIgnoreInHostDeviceCheck(Callee)) {
  1567. if ((!CheckCaller && !Caller) ||
  1568. (Caller &&
  1569. getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
  1570. markKnownEmitted(
  1571. *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
  1572. return CheckCaller &&
  1573. S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
  1574. });
  1575. else if (Caller)
  1576. DeviceCallGraph[Caller].insert({Callee, Loc});
  1577. }
  1578. }
  1579. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1580. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1581. "OpenMP device compilation mode is expected.");
  1582. QualType Ty = E->getType();
  1583. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1584. ((Ty->isFloat128Type() ||
  1585. (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
  1586. !Context.getTargetInfo().hasFloat128Type()) ||
  1587. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1588. !Context.getTargetInfo().hasInt128Type()))
  1589. targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
  1590. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1591. << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
  1592. }
  1593. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1594. unsigned OpenMPCaptureLevel) const {
  1595. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1596. ASTContext &Ctx = getASTContext();
  1597. bool IsByRef = true;
  1598. // Find the directive that is associated with the provided scope.
  1599. D = cast<ValueDecl>(D->getCanonicalDecl());
  1600. QualType Ty = D->getType();
  1601. bool IsVariableUsedInMapClause = false;
  1602. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1603. // This table summarizes how a given variable should be passed to the device
  1604. // given its type and the clauses where it appears. This table is based on
  1605. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1606. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1607. //
  1608. // =========================================================================
  1609. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1610. // | |(tofrom:scalar)| | pvt | | | |
  1611. // =========================================================================
  1612. // | scl | | | | - | | bycopy|
  1613. // | scl | | - | x | - | - | bycopy|
  1614. // | scl | | x | - | - | - | null |
  1615. // | scl | x | | | - | | byref |
  1616. // | scl | x | - | x | - | - | bycopy|
  1617. // | scl | x | x | - | - | - | null |
  1618. // | scl | | - | - | - | x | byref |
  1619. // | scl | x | - | - | - | x | byref |
  1620. //
  1621. // | agg | n.a. | | | - | | byref |
  1622. // | agg | n.a. | - | x | - | - | byref |
  1623. // | agg | n.a. | x | - | - | - | null |
  1624. // | agg | n.a. | - | - | - | x | byref |
  1625. // | agg | n.a. | - | - | - | x[] | byref |
  1626. //
  1627. // | ptr | n.a. | | | - | | bycopy|
  1628. // | ptr | n.a. | - | x | - | - | bycopy|
  1629. // | ptr | n.a. | x | - | - | - | null |
  1630. // | ptr | n.a. | - | - | - | x | byref |
  1631. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1632. // | ptr | n.a. | - | - | x | | bycopy|
  1633. // | ptr | n.a. | - | - | x | x | bycopy|
  1634. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1635. // =========================================================================
  1636. // Legend:
  1637. // scl - scalar
  1638. // ptr - pointer
  1639. // agg - aggregate
  1640. // x - applies
  1641. // - - invalid in this combination
  1642. // [] - mapped with an array section
  1643. // byref - should be mapped by reference
  1644. // byval - should be mapped by value
  1645. // null - initialize a local variable to null on the device
  1646. //
  1647. // Observations:
  1648. // - All scalar declarations that show up in a map clause have to be passed
  1649. // by reference, because they may have been mapped in the enclosing data
  1650. // environment.
  1651. // - If the scalar value does not fit the size of uintptr, it has to be
  1652. // passed by reference, regardless the result in the table above.
  1653. // - For pointers mapped by value that have either an implicit map or an
  1654. // array section, the runtime library may pass the NULL value to the
  1655. // device instead of the value passed to it by the compiler.
  1656. if (Ty->isReferenceType())
  1657. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1658. // Locate map clauses and see if the variable being captured is referred to
  1659. // in any of those clauses. Here we only care about variables, not fields,
  1660. // because fields are part of aggregates.
  1661. bool IsVariableAssociatedWithSection = false;
  1662. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1663. D, Level,
  1664. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1665. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1666. MapExprComponents,
  1667. OpenMPClauseKind WhereFoundClauseKind) {
  1668. // Only the map clause information influences how a variable is
  1669. // captured. E.g. is_device_ptr does not require changing the default
  1670. // behavior.
  1671. if (WhereFoundClauseKind != OMPC_map)
  1672. return false;
  1673. auto EI = MapExprComponents.rbegin();
  1674. auto EE = MapExprComponents.rend();
  1675. assert(EI != EE && "Invalid map expression!");
  1676. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1677. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1678. ++EI;
  1679. if (EI == EE)
  1680. return false;
  1681. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1682. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1683. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1684. IsVariableAssociatedWithSection = true;
  1685. // There is nothing more we need to know about this variable.
  1686. return true;
  1687. }
  1688. // Keep looking for more map info.
  1689. return false;
  1690. });
  1691. if (IsVariableUsedInMapClause) {
  1692. // If variable is identified in a map clause it is always captured by
  1693. // reference except if it is a pointer that is dereferenced somehow.
  1694. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1695. } else {
  1696. // By default, all the data that has a scalar type is mapped by copy
  1697. // (except for reduction variables).
  1698. IsByRef =
  1699. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1700. !Ty->isAnyPointerType()) ||
  1701. !Ty->isScalarType() ||
  1702. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1703. DSAStack->hasExplicitDSA(
  1704. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1705. }
  1706. }
  1707. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1708. IsByRef =
  1709. ((IsVariableUsedInMapClause &&
  1710. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  1711. OMPD_target) ||
  1712. !DSAStack->hasExplicitDSA(
  1713. D,
  1714. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1715. Level, /*NotLastprivate=*/true)) &&
  1716. // If the variable is artificial and must be captured by value - try to
  1717. // capture by value.
  1718. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1719. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1720. }
  1721. // When passing data by copy, we need to make sure it fits the uintptr size
  1722. // and alignment, because the runtime library only deals with uintptr types.
  1723. // If it does not fit the uintptr size, we need to pass the data by reference
  1724. // instead.
  1725. if (!IsByRef &&
  1726. (Ctx.getTypeSizeInChars(Ty) >
  1727. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1728. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1729. IsByRef = true;
  1730. }
  1731. return IsByRef;
  1732. }
  1733. unsigned Sema::getOpenMPNestingLevel() const {
  1734. assert(getLangOpts().OpenMP);
  1735. return DSAStack->getNestingLevel();
  1736. }
  1737. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1738. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1739. !DSAStack->isClauseParsingMode()) ||
  1740. DSAStack->hasDirective(
  1741. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1742. SourceLocation) -> bool {
  1743. return isOpenMPTargetExecutionDirective(K);
  1744. },
  1745. false);
  1746. }
  1747. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  1748. unsigned StopAt) {
  1749. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1750. D = getCanonicalDecl(D);
  1751. // If we want to determine whether the variable should be captured from the
  1752. // perspective of the current capturing scope, and we've already left all the
  1753. // capturing scopes of the top directive on the stack, check from the
  1754. // perspective of its parent directive (if any) instead.
  1755. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  1756. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  1757. // If we are attempting to capture a global variable in a directive with
  1758. // 'target' we return true so that this global is also mapped to the device.
  1759. //
  1760. auto *VD = dyn_cast<VarDecl>(D);
  1761. if (VD && !VD->hasLocalStorage() &&
  1762. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1763. if (isInOpenMPDeclareTargetContext()) {
  1764. // Try to mark variable as declare target if it is used in capturing
  1765. // regions.
  1766. if (LangOpts.OpenMP <= 45 &&
  1767. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1768. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1769. return nullptr;
  1770. } else if (isInOpenMPTargetExecutionDirective()) {
  1771. // If the declaration is enclosed in a 'declare target' directive,
  1772. // then it should not be captured.
  1773. //
  1774. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1775. return nullptr;
  1776. return VD;
  1777. }
  1778. }
  1779. if (CheckScopeInfo) {
  1780. bool OpenMPFound = false;
  1781. for (unsigned I = StopAt + 1; I > 0; --I) {
  1782. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  1783. if(!isa<CapturingScopeInfo>(FSI))
  1784. return nullptr;
  1785. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  1786. if (RSI->CapRegionKind == CR_OpenMP) {
  1787. OpenMPFound = true;
  1788. break;
  1789. }
  1790. }
  1791. if (!OpenMPFound)
  1792. return nullptr;
  1793. }
  1794. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1795. (!DSAStack->isClauseParsingMode() ||
  1796. DSAStack->getParentDirective() != OMPD_unknown)) {
  1797. auto &&Info = DSAStack->isLoopControlVariable(D);
  1798. if (Info.first ||
  1799. (VD && VD->hasLocalStorage() &&
  1800. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1801. (VD && DSAStack->isForceVarCapturing()))
  1802. return VD ? VD : Info.second;
  1803. DSAStackTy::DSAVarData DVarPrivate =
  1804. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1805. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1806. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1807. // Threadprivate variables must not be captured.
  1808. if (isOpenMPThreadPrivate(DVarPrivate.CKind))
  1809. return nullptr;
  1810. // The variable is not private or it is the variable in the directive with
  1811. // default(none) clause and not used in any clause.
  1812. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1813. [](OpenMPDirectiveKind) { return true; },
  1814. DSAStack->isClauseParsingMode());
  1815. if (DVarPrivate.CKind != OMPC_unknown ||
  1816. (VD && DSAStack->getDefaultDSA() == DSA_none))
  1817. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1818. }
  1819. return nullptr;
  1820. }
  1821. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1822. unsigned Level) const {
  1823. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1824. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1825. FunctionScopesIndex -= Regions.size();
  1826. }
  1827. void Sema::startOpenMPLoop() {
  1828. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1829. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1830. DSAStack->loopInit();
  1831. }
  1832. void Sema::startOpenMPCXXRangeFor() {
  1833. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1834. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1835. DSAStack->resetPossibleLoopCounter();
  1836. DSAStack->loopStart();
  1837. }
  1838. }
  1839. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1840. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1841. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1842. if (DSAStack->getAssociatedLoops() > 0 &&
  1843. !DSAStack->isLoopStarted()) {
  1844. DSAStack->resetPossibleLoopCounter(D);
  1845. DSAStack->loopStart();
  1846. return true;
  1847. }
  1848. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1849. DSAStack->isLoopControlVariable(D).first) &&
  1850. !DSAStack->hasExplicitDSA(
  1851. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1852. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1853. return true;
  1854. }
  1855. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1856. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  1857. DSAStack->isForceVarCapturing() &&
  1858. !DSAStack->hasExplicitDSA(
  1859. D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
  1860. return true;
  1861. }
  1862. return DSAStack->hasExplicitDSA(
  1863. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1864. (DSAStack->isClauseParsingMode() &&
  1865. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1866. // Consider taskgroup reduction descriptor variable a private to avoid
  1867. // possible capture in the region.
  1868. (DSAStack->hasExplicitDirective(
  1869. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1870. Level) &&
  1871. DSAStack->isTaskgroupReductionRef(D, Level));
  1872. }
  1873. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1874. unsigned Level) {
  1875. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1876. D = getCanonicalDecl(D);
  1877. OpenMPClauseKind OMPC = OMPC_unknown;
  1878. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1879. const unsigned NewLevel = I - 1;
  1880. if (DSAStack->hasExplicitDSA(D,
  1881. [&OMPC](const OpenMPClauseKind K) {
  1882. if (isOpenMPPrivate(K)) {
  1883. OMPC = K;
  1884. return true;
  1885. }
  1886. return false;
  1887. },
  1888. NewLevel))
  1889. break;
  1890. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1891. D, NewLevel,
  1892. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1893. OpenMPClauseKind) { return true; })) {
  1894. OMPC = OMPC_map;
  1895. break;
  1896. }
  1897. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1898. NewLevel)) {
  1899. OMPC = OMPC_map;
  1900. if (D->getType()->isScalarType() &&
  1901. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1902. DefaultMapAttributes::DMA_tofrom_scalar)
  1903. OMPC = OMPC_firstprivate;
  1904. break;
  1905. }
  1906. }
  1907. if (OMPC != OMPC_unknown)
  1908. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1909. }
  1910. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1911. unsigned Level) const {
  1912. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1913. // Return true if the current level is no longer enclosed in a target region.
  1914. const auto *VD = dyn_cast<VarDecl>(D);
  1915. return VD && !VD->hasLocalStorage() &&
  1916. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1917. Level);
  1918. }
  1919. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1920. void Sema::finalizeOpenMPDelayedAnalysis() {
  1921. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  1922. // Diagnose implicit declare target functions and their callees.
  1923. for (const auto &CallerCallees : DeviceCallGraph) {
  1924. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1925. OMPDeclareTargetDeclAttr::getDeviceType(
  1926. CallerCallees.getFirst()->getMostRecentDecl());
  1927. // Ignore host functions during device analyzis.
  1928. if (LangOpts.OpenMPIsDevice && DevTy &&
  1929. *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  1930. continue;
  1931. // Ignore nohost functions during host analyzis.
  1932. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1933. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  1934. continue;
  1935. for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
  1936. &Callee : CallerCallees.getSecond()) {
  1937. const FunctionDecl *FD = Callee.first->getMostRecentDecl();
  1938. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  1939. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  1940. if (LangOpts.OpenMPIsDevice && DevTy &&
  1941. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  1942. // Diagnose host function called during device codegen.
  1943. StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
  1944. OMPC_device_type, OMPC_DEVICE_TYPE_host);
  1945. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1946. << HostDevTy << 0;
  1947. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1948. diag::note_omp_marked_device_type_here)
  1949. << HostDevTy;
  1950. continue;
  1951. }
  1952. if (!LangOpts.OpenMPIsDevice && DevTy &&
  1953. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  1954. // Diagnose nohost function called during host codegen.
  1955. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  1956. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  1957. Diag(Callee.second, diag::err_omp_wrong_device_function_call)
  1958. << NoHostDevTy << 1;
  1959. Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
  1960. diag::note_omp_marked_device_type_here)
  1961. << NoHostDevTy;
  1962. continue;
  1963. }
  1964. }
  1965. }
  1966. }
  1967. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1968. const DeclarationNameInfo &DirName,
  1969. Scope *CurScope, SourceLocation Loc) {
  1970. DSAStack->push(DKind, DirName, CurScope, Loc);
  1971. PushExpressionEvaluationContext(
  1972. ExpressionEvaluationContext::PotentiallyEvaluated);
  1973. }
  1974. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1975. DSAStack->setClauseParsingMode(K);
  1976. }
  1977. void Sema::EndOpenMPClause() {
  1978. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1979. }
  1980. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1981. ArrayRef<OMPClause *> Clauses);
  1982. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1983. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1984. // A variable of class type (or array thereof) that appears in a lastprivate
  1985. // clause requires an accessible, unambiguous default constructor for the
  1986. // class type, unless the list item is also specified in a firstprivate
  1987. // clause.
  1988. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1989. for (OMPClause *C : D->clauses()) {
  1990. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1991. SmallVector<Expr *, 8> PrivateCopies;
  1992. for (Expr *DE : Clause->varlists()) {
  1993. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1994. PrivateCopies.push_back(nullptr);
  1995. continue;
  1996. }
  1997. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1998. auto *VD = cast<VarDecl>(DRE->getDecl());
  1999. QualType Type = VD->getType().getNonReferenceType();
  2000. const DSAStackTy::DSAVarData DVar =
  2001. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2002. if (DVar.CKind == OMPC_lastprivate) {
  2003. // Generate helper private variable and initialize it with the
  2004. // default value. The address of the original variable is replaced
  2005. // by the address of the new private variable in CodeGen. This new
  2006. // variable is not added to IdResolver, so the code in the OpenMP
  2007. // region uses original variable for proper diagnostics.
  2008. VarDecl *VDPrivate = buildVarDecl(
  2009. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2010. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2011. ActOnUninitializedDecl(VDPrivate);
  2012. if (VDPrivate->isInvalidDecl()) {
  2013. PrivateCopies.push_back(nullptr);
  2014. continue;
  2015. }
  2016. PrivateCopies.push_back(buildDeclRefExpr(
  2017. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2018. } else {
  2019. // The variable is also a firstprivate, so initialization sequence
  2020. // for private copy is generated already.
  2021. PrivateCopies.push_back(nullptr);
  2022. }
  2023. }
  2024. Clause->setPrivateCopies(PrivateCopies);
  2025. }
  2026. }
  2027. // Check allocate clauses.
  2028. if (!CurContext->isDependentContext())
  2029. checkAllocateClauses(*this, DSAStack, D->clauses());
  2030. }
  2031. DSAStack->pop();
  2032. DiscardCleanupsInEvaluationContext();
  2033. PopExpressionEvaluationContext();
  2034. }
  2035. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2036. Expr *NumIterations, Sema &SemaRef,
  2037. Scope *S, DSAStackTy *Stack);
  2038. namespace {
  2039. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2040. private:
  2041. Sema &SemaRef;
  2042. public:
  2043. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2044. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2045. NamedDecl *ND = Candidate.getCorrectionDecl();
  2046. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2047. return VD->hasGlobalStorage() &&
  2048. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2049. SemaRef.getCurScope());
  2050. }
  2051. return false;
  2052. }
  2053. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2054. return std::make_unique<VarDeclFilterCCC>(*this);
  2055. }
  2056. };
  2057. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2058. private:
  2059. Sema &SemaRef;
  2060. public:
  2061. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2062. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2063. NamedDecl *ND = Candidate.getCorrectionDecl();
  2064. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2065. isa<FunctionDecl>(ND))) {
  2066. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2067. SemaRef.getCurScope());
  2068. }
  2069. return false;
  2070. }
  2071. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2072. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2073. }
  2074. };
  2075. } // namespace
  2076. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2077. CXXScopeSpec &ScopeSpec,
  2078. const DeclarationNameInfo &Id,
  2079. OpenMPDirectiveKind Kind) {
  2080. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2081. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2082. if (Lookup.isAmbiguous())
  2083. return ExprError();
  2084. VarDecl *VD;
  2085. if (!Lookup.isSingleResult()) {
  2086. VarDeclFilterCCC CCC(*this);
  2087. if (TypoCorrection Corrected =
  2088. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2089. CTK_ErrorRecovery)) {
  2090. diagnoseTypo(Corrected,
  2091. PDiag(Lookup.empty()
  2092. ? diag::err_undeclared_var_use_suggest
  2093. : diag::err_omp_expected_var_arg_suggest)
  2094. << Id.getName());
  2095. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2096. } else {
  2097. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2098. : diag::err_omp_expected_var_arg)
  2099. << Id.getName();
  2100. return ExprError();
  2101. }
  2102. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2103. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2104. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2105. return ExprError();
  2106. }
  2107. Lookup.suppressDiagnostics();
  2108. // OpenMP [2.9.2, Syntax, C/C++]
  2109. // Variables must be file-scope, namespace-scope, or static block-scope.
  2110. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2111. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2112. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2113. bool IsDecl =
  2114. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2115. Diag(VD->getLocation(),
  2116. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2117. << VD;
  2118. return ExprError();
  2119. }
  2120. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2121. NamedDecl *ND = CanonicalVD;
  2122. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2123. // A threadprivate directive for file-scope variables must appear outside
  2124. // any definition or declaration.
  2125. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2126. !getCurLexicalContext()->isTranslationUnit()) {
  2127. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2128. << getOpenMPDirectiveName(Kind) << VD;
  2129. bool IsDecl =
  2130. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2131. Diag(VD->getLocation(),
  2132. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2133. << VD;
  2134. return ExprError();
  2135. }
  2136. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2137. // A threadprivate directive for static class member variables must appear
  2138. // in the class definition, in the same scope in which the member
  2139. // variables are declared.
  2140. if (CanonicalVD->isStaticDataMember() &&
  2141. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2142. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2143. << getOpenMPDirectiveName(Kind) << VD;
  2144. bool IsDecl =
  2145. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2146. Diag(VD->getLocation(),
  2147. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2148. << VD;
  2149. return ExprError();
  2150. }
  2151. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2152. // A threadprivate directive for namespace-scope variables must appear
  2153. // outside any definition or declaration other than the namespace
  2154. // definition itself.
  2155. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2156. (!getCurLexicalContext()->isFileContext() ||
  2157. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2158. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2159. << getOpenMPDirectiveName(Kind) << VD;
  2160. bool IsDecl =
  2161. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2162. Diag(VD->getLocation(),
  2163. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2164. << VD;
  2165. return ExprError();
  2166. }
  2167. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2168. // A threadprivate directive for static block-scope variables must appear
  2169. // in the scope of the variable and not in a nested scope.
  2170. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2171. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2172. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2173. << getOpenMPDirectiveName(Kind) << VD;
  2174. bool IsDecl =
  2175. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2176. Diag(VD->getLocation(),
  2177. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2178. << VD;
  2179. return ExprError();
  2180. }
  2181. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2182. // A threadprivate directive must lexically precede all references to any
  2183. // of the variables in its list.
  2184. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2185. !DSAStack->isThreadPrivate(VD)) {
  2186. Diag(Id.getLoc(), diag::err_omp_var_used)
  2187. << getOpenMPDirectiveName(Kind) << VD;
  2188. return ExprError();
  2189. }
  2190. QualType ExprType = VD->getType().getNonReferenceType();
  2191. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2192. SourceLocation(), VD,
  2193. /*RefersToEnclosingVariableOrCapture=*/false,
  2194. Id.getLoc(), ExprType, VK_LValue);
  2195. }
  2196. Sema::DeclGroupPtrTy
  2197. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2198. ArrayRef<Expr *> VarList) {
  2199. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2200. CurContext->addDecl(D);
  2201. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2202. }
  2203. return nullptr;
  2204. }
  2205. namespace {
  2206. class LocalVarRefChecker final
  2207. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2208. Sema &SemaRef;
  2209. public:
  2210. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2211. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2212. if (VD->hasLocalStorage()) {
  2213. SemaRef.Diag(E->getBeginLoc(),
  2214. diag::err_omp_local_var_in_threadprivate_init)
  2215. << E->getSourceRange();
  2216. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2217. << VD << VD->getSourceRange();
  2218. return true;
  2219. }
  2220. }
  2221. return false;
  2222. }
  2223. bool VisitStmt(const Stmt *S) {
  2224. for (const Stmt *Child : S->children()) {
  2225. if (Child && Visit(Child))
  2226. return true;
  2227. }
  2228. return false;
  2229. }
  2230. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2231. };
  2232. } // namespace
  2233. OMPThreadPrivateDecl *
  2234. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2235. SmallVector<Expr *, 8> Vars;
  2236. for (Expr *RefExpr : VarList) {
  2237. auto *DE = cast<DeclRefExpr>(RefExpr);
  2238. auto *VD = cast<VarDecl>(DE->getDecl());
  2239. SourceLocation ILoc = DE->getExprLoc();
  2240. // Mark variable as used.
  2241. VD->setReferenced();
  2242. VD->markUsed(Context);
  2243. QualType QType = VD->getType();
  2244. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2245. // It will be analyzed later.
  2246. Vars.push_back(DE);
  2247. continue;
  2248. }
  2249. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2250. // A threadprivate variable must not have an incomplete type.
  2251. if (RequireCompleteType(ILoc, VD->getType(),
  2252. diag::err_omp_threadprivate_incomplete_type)) {
  2253. continue;
  2254. }
  2255. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2256. // A threadprivate variable must not have a reference type.
  2257. if (VD->getType()->isReferenceType()) {
  2258. Diag(ILoc, diag::err_omp_ref_type_arg)
  2259. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2260. bool IsDecl =
  2261. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2262. Diag(VD->getLocation(),
  2263. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2264. << VD;
  2265. continue;
  2266. }
  2267. // Check if this is a TLS variable. If TLS is not being supported, produce
  2268. // the corresponding diagnostic.
  2269. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2270. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2271. getLangOpts().OpenMPUseTLS &&
  2272. getASTContext().getTargetInfo().isTLSSupported())) ||
  2273. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2274. !VD->isLocalVarDecl())) {
  2275. Diag(ILoc, diag::err_omp_var_thread_local)
  2276. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2277. bool IsDecl =
  2278. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2279. Diag(VD->getLocation(),
  2280. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2281. << VD;
  2282. continue;
  2283. }
  2284. // Check if initial value of threadprivate variable reference variable with
  2285. // local storage (it is not supported by runtime).
  2286. if (const Expr *Init = VD->getAnyInitializer()) {
  2287. LocalVarRefChecker Checker(*this);
  2288. if (Checker.Visit(Init))
  2289. continue;
  2290. }
  2291. Vars.push_back(RefExpr);
  2292. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2293. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2294. Context, SourceRange(Loc, Loc)));
  2295. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2296. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2297. }
  2298. OMPThreadPrivateDecl *D = nullptr;
  2299. if (!Vars.empty()) {
  2300. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2301. Vars);
  2302. D->setAccess(AS_public);
  2303. }
  2304. return D;
  2305. }
  2306. static OMPAllocateDeclAttr::AllocatorTypeTy
  2307. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2308. if (!Allocator)
  2309. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2310. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2311. Allocator->isInstantiationDependent() ||
  2312. Allocator->containsUnexpandedParameterPack())
  2313. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2314. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2315. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2316. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2317. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2318. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2319. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2320. llvm::FoldingSetNodeID AEId, DAEId;
  2321. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2322. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2323. if (AEId == DAEId) {
  2324. AllocatorKindRes = AllocatorKind;
  2325. break;
  2326. }
  2327. }
  2328. return AllocatorKindRes;
  2329. }
  2330. static bool checkPreviousOMPAllocateAttribute(
  2331. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2332. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2333. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2334. return false;
  2335. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2336. Expr *PrevAllocator = A->getAllocator();
  2337. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2338. getAllocatorKind(S, Stack, PrevAllocator);
  2339. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2340. if (AllocatorsMatch &&
  2341. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2342. Allocator && PrevAllocator) {
  2343. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2344. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2345. llvm::FoldingSetNodeID AEId, PAEId;
  2346. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2347. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2348. AllocatorsMatch = AEId == PAEId;
  2349. }
  2350. if (!AllocatorsMatch) {
  2351. SmallString<256> AllocatorBuffer;
  2352. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2353. if (Allocator)
  2354. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2355. SmallString<256> PrevAllocatorBuffer;
  2356. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2357. if (PrevAllocator)
  2358. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2359. S.getPrintingPolicy());
  2360. SourceLocation AllocatorLoc =
  2361. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2362. SourceRange AllocatorRange =
  2363. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2364. SourceLocation PrevAllocatorLoc =
  2365. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2366. SourceRange PrevAllocatorRange =
  2367. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2368. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2369. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2370. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2371. << AllocatorRange;
  2372. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2373. << PrevAllocatorRange;
  2374. return true;
  2375. }
  2376. return false;
  2377. }
  2378. static void
  2379. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2380. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2381. Expr *Allocator, SourceRange SR) {
  2382. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2383. return;
  2384. if (Allocator &&
  2385. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2386. Allocator->isInstantiationDependent() ||
  2387. Allocator->containsUnexpandedParameterPack()))
  2388. return;
  2389. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2390. Allocator, SR);
  2391. VD->addAttr(A);
  2392. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2393. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2394. }
  2395. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2396. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2397. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2398. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2399. Expr *Allocator = nullptr;
  2400. if (Clauses.empty()) {
  2401. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2402. // allocate directives that appear in a target region must specify an
  2403. // allocator clause unless a requires directive with the dynamic_allocators
  2404. // clause is present in the same compilation unit.
  2405. if (LangOpts.OpenMPIsDevice &&
  2406. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2407. targetDiag(Loc, diag::err_expected_allocator_clause);
  2408. } else {
  2409. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2410. }
  2411. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2412. getAllocatorKind(*this, DSAStack, Allocator);
  2413. SmallVector<Expr *, 8> Vars;
  2414. for (Expr *RefExpr : VarList) {
  2415. auto *DE = cast<DeclRefExpr>(RefExpr);
  2416. auto *VD = cast<VarDecl>(DE->getDecl());
  2417. // Check if this is a TLS variable or global register.
  2418. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2419. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2420. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2421. !VD->isLocalVarDecl()))
  2422. continue;
  2423. // If the used several times in the allocate directive, the same allocator
  2424. // must be used.
  2425. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2426. AllocatorKind, Allocator))
  2427. continue;
  2428. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2429. // If a list item has a static storage type, the allocator expression in the
  2430. // allocator clause must be a constant expression that evaluates to one of
  2431. // the predefined memory allocator values.
  2432. if (Allocator && VD->hasGlobalStorage()) {
  2433. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2434. Diag(Allocator->getExprLoc(),
  2435. diag::err_omp_expected_predefined_allocator)
  2436. << Allocator->getSourceRange();
  2437. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2438. VarDecl::DeclarationOnly;
  2439. Diag(VD->getLocation(),
  2440. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2441. << VD;
  2442. continue;
  2443. }
  2444. }
  2445. Vars.push_back(RefExpr);
  2446. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2447. DE->getSourceRange());
  2448. }
  2449. if (Vars.empty())
  2450. return nullptr;
  2451. if (!Owner)
  2452. Owner = getCurLexicalContext();
  2453. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2454. D->setAccess(AS_public);
  2455. Owner->addDecl(D);
  2456. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2457. }
  2458. Sema::DeclGroupPtrTy
  2459. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2460. ArrayRef<OMPClause *> ClauseList) {
  2461. OMPRequiresDecl *D = nullptr;
  2462. if (!CurContext->isFileContext()) {
  2463. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2464. } else {
  2465. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2466. if (D) {
  2467. CurContext->addDecl(D);
  2468. DSAStack->addRequiresDecl(D);
  2469. }
  2470. }
  2471. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2472. }
  2473. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2474. ArrayRef<OMPClause *> ClauseList) {
  2475. /// For target specific clauses, the requires directive cannot be
  2476. /// specified after the handling of any of the target regions in the
  2477. /// current compilation unit.
  2478. ArrayRef<SourceLocation> TargetLocations =
  2479. DSAStack->getEncounteredTargetLocs();
  2480. if (!TargetLocations.empty()) {
  2481. for (const OMPClause *CNew : ClauseList) {
  2482. // Check if any of the requires clauses affect target regions.
  2483. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  2484. isa<OMPUnifiedAddressClause>(CNew) ||
  2485. isa<OMPReverseOffloadClause>(CNew) ||
  2486. isa<OMPDynamicAllocatorsClause>(CNew)) {
  2487. Diag(Loc, diag::err_omp_target_before_requires)
  2488. << getOpenMPClauseName(CNew->getClauseKind());
  2489. for (SourceLocation TargetLoc : TargetLocations) {
  2490. Diag(TargetLoc, diag::note_omp_requires_encountered_target);
  2491. }
  2492. }
  2493. }
  2494. }
  2495. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2496. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2497. ClauseList);
  2498. return nullptr;
  2499. }
  2500. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2501. const ValueDecl *D,
  2502. const DSAStackTy::DSAVarData &DVar,
  2503. bool IsLoopIterVar = false) {
  2504. if (DVar.RefExpr) {
  2505. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2506. << getOpenMPClauseName(DVar.CKind);
  2507. return;
  2508. }
  2509. enum {
  2510. PDSA_StaticMemberShared,
  2511. PDSA_StaticLocalVarShared,
  2512. PDSA_LoopIterVarPrivate,
  2513. PDSA_LoopIterVarLinear,
  2514. PDSA_LoopIterVarLastprivate,
  2515. PDSA_ConstVarShared,
  2516. PDSA_GlobalVarShared,
  2517. PDSA_TaskVarFirstprivate,
  2518. PDSA_LocalVarPrivate,
  2519. PDSA_Implicit
  2520. } Reason = PDSA_Implicit;
  2521. bool ReportHint = false;
  2522. auto ReportLoc = D->getLocation();
  2523. auto *VD = dyn_cast<VarDecl>(D);
  2524. if (IsLoopIterVar) {
  2525. if (DVar.CKind == OMPC_private)
  2526. Reason = PDSA_LoopIterVarPrivate;
  2527. else if (DVar.CKind == OMPC_lastprivate)
  2528. Reason = PDSA_LoopIterVarLastprivate;
  2529. else
  2530. Reason = PDSA_LoopIterVarLinear;
  2531. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2532. DVar.CKind == OMPC_firstprivate) {
  2533. Reason = PDSA_TaskVarFirstprivate;
  2534. ReportLoc = DVar.ImplicitDSALoc;
  2535. } else if (VD && VD->isStaticLocal())
  2536. Reason = PDSA_StaticLocalVarShared;
  2537. else if (VD && VD->isStaticDataMember())
  2538. Reason = PDSA_StaticMemberShared;
  2539. else if (VD && VD->isFileVarDecl())
  2540. Reason = PDSA_GlobalVarShared;
  2541. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2542. Reason = PDSA_ConstVarShared;
  2543. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2544. ReportHint = true;
  2545. Reason = PDSA_LocalVarPrivate;
  2546. }
  2547. if (Reason != PDSA_Implicit) {
  2548. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2549. << Reason << ReportHint
  2550. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2551. } else if (DVar.ImplicitDSALoc.isValid()) {
  2552. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2553. << getOpenMPClauseName(DVar.CKind);
  2554. }
  2555. }
  2556. namespace {
  2557. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2558. DSAStackTy *Stack;
  2559. Sema &SemaRef;
  2560. bool ErrorFound = false;
  2561. CapturedStmt *CS = nullptr;
  2562. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2563. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2564. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2565. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2566. void VisitSubCaptures(OMPExecutableDirective *S) {
  2567. // Check implicitly captured variables.
  2568. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2569. return;
  2570. visitSubCaptures(S->getInnermostCapturedStmt());
  2571. }
  2572. public:
  2573. void VisitDeclRefExpr(DeclRefExpr *E) {
  2574. if (E->isTypeDependent() || E->isValueDependent() ||
  2575. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2576. return;
  2577. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2578. // Check the datasharing rules for the expressions in the clauses.
  2579. if (!CS) {
  2580. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  2581. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  2582. Visit(CED->getInit());
  2583. return;
  2584. }
  2585. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  2586. // Do not analyze internal variables and do not enclose them into
  2587. // implicit clauses.
  2588. return;
  2589. VD = VD->getCanonicalDecl();
  2590. // Skip internally declared variables.
  2591. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
  2592. return;
  2593. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2594. // Check if the variable has explicit DSA set and stop analysis if it so.
  2595. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2596. return;
  2597. // Skip internally declared static variables.
  2598. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2599. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2600. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  2601. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  2602. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2603. return;
  2604. SourceLocation ELoc = E->getExprLoc();
  2605. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2606. // The default(none) clause requires that each variable that is referenced
  2607. // in the construct, and does not have a predetermined data-sharing
  2608. // attribute, must have its data-sharing attribute explicitly determined
  2609. // by being listed in a data-sharing attribute clause.
  2610. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2611. isImplicitOrExplicitTaskingRegion(DKind) &&
  2612. VarsWithInheritedDSA.count(VD) == 0) {
  2613. VarsWithInheritedDSA[VD] = E;
  2614. return;
  2615. }
  2616. if (isOpenMPTargetExecutionDirective(DKind) &&
  2617. !Stack->isLoopControlVariable(VD).first) {
  2618. if (!Stack->checkMappableExprComponentListsForDecl(
  2619. VD, /*CurrentRegionOnly=*/true,
  2620. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2621. StackComponents,
  2622. OpenMPClauseKind) {
  2623. // Variable is used if it has been marked as an array, array
  2624. // section or the variable iself.
  2625. return StackComponents.size() == 1 ||
  2626. std::all_of(
  2627. std::next(StackComponents.rbegin()),
  2628. StackComponents.rend(),
  2629. [](const OMPClauseMappableExprCommon::
  2630. MappableComponent &MC) {
  2631. return MC.getAssociatedDeclaration() ==
  2632. nullptr &&
  2633. (isa<OMPArraySectionExpr>(
  2634. MC.getAssociatedExpression()) ||
  2635. isa<ArraySubscriptExpr>(
  2636. MC.getAssociatedExpression()));
  2637. });
  2638. })) {
  2639. bool IsFirstprivate = false;
  2640. // By default lambdas are captured as firstprivates.
  2641. if (const auto *RD =
  2642. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2643. IsFirstprivate = RD->isLambda();
  2644. IsFirstprivate =
  2645. IsFirstprivate ||
  2646. (VD->getType().getNonReferenceType()->isScalarType() &&
  2647. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2648. if (IsFirstprivate)
  2649. ImplicitFirstprivate.emplace_back(E);
  2650. else
  2651. ImplicitMap.emplace_back(E);
  2652. return;
  2653. }
  2654. }
  2655. // OpenMP [2.9.3.6, Restrictions, p.2]
  2656. // A list item that appears in a reduction clause of the innermost
  2657. // enclosing worksharing or parallel construct may not be accessed in an
  2658. // explicit task.
  2659. DVar = Stack->hasInnermostDSA(
  2660. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2661. [](OpenMPDirectiveKind K) {
  2662. return isOpenMPParallelDirective(K) ||
  2663. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2664. },
  2665. /*FromParent=*/true);
  2666. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2667. ErrorFound = true;
  2668. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2669. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2670. return;
  2671. }
  2672. // Define implicit data-sharing attributes for task.
  2673. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2674. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2675. !Stack->isLoopControlVariable(VD).first) {
  2676. ImplicitFirstprivate.push_back(E);
  2677. return;
  2678. }
  2679. // Store implicitly used globals with declare target link for parent
  2680. // target.
  2681. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2682. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2683. Stack->addToParentTargetRegionLinkGlobals(E);
  2684. return;
  2685. }
  2686. }
  2687. }
  2688. void VisitMemberExpr(MemberExpr *E) {
  2689. if (E->isTypeDependent() || E->isValueDependent() ||
  2690. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2691. return;
  2692. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2693. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2694. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2695. if (!FD)
  2696. return;
  2697. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2698. // Check if the variable has explicit DSA set and stop analysis if it
  2699. // so.
  2700. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2701. return;
  2702. if (isOpenMPTargetExecutionDirective(DKind) &&
  2703. !Stack->isLoopControlVariable(FD).first &&
  2704. !Stack->checkMappableExprComponentListsForDecl(
  2705. FD, /*CurrentRegionOnly=*/true,
  2706. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2707. StackComponents,
  2708. OpenMPClauseKind) {
  2709. return isa<CXXThisExpr>(
  2710. cast<MemberExpr>(
  2711. StackComponents.back().getAssociatedExpression())
  2712. ->getBase()
  2713. ->IgnoreParens());
  2714. })) {
  2715. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2716. // A bit-field cannot appear in a map clause.
  2717. //
  2718. if (FD->isBitField())
  2719. return;
  2720. // Check to see if the member expression is referencing a class that
  2721. // has already been explicitly mapped
  2722. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2723. return;
  2724. ImplicitMap.emplace_back(E);
  2725. return;
  2726. }
  2727. SourceLocation ELoc = E->getExprLoc();
  2728. // OpenMP [2.9.3.6, Restrictions, p.2]
  2729. // A list item that appears in a reduction clause of the innermost
  2730. // enclosing worksharing or parallel construct may not be accessed in
  2731. // an explicit task.
  2732. DVar = Stack->hasInnermostDSA(
  2733. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2734. [](OpenMPDirectiveKind K) {
  2735. return isOpenMPParallelDirective(K) ||
  2736. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2737. },
  2738. /*FromParent=*/true);
  2739. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2740. ErrorFound = true;
  2741. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2742. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2743. return;
  2744. }
  2745. // Define implicit data-sharing attributes for task.
  2746. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2747. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2748. !Stack->isLoopControlVariable(FD).first) {
  2749. // Check if there is a captured expression for the current field in the
  2750. // region. Do not mark it as firstprivate unless there is no captured
  2751. // expression.
  2752. // TODO: try to make it firstprivate.
  2753. if (DVar.CKind != OMPC_unknown)
  2754. ImplicitFirstprivate.push_back(E);
  2755. }
  2756. return;
  2757. }
  2758. if (isOpenMPTargetExecutionDirective(DKind)) {
  2759. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2760. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2761. /*NoDiagnose=*/true))
  2762. return;
  2763. const auto *VD = cast<ValueDecl>(
  2764. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2765. if (!Stack->checkMappableExprComponentListsForDecl(
  2766. VD, /*CurrentRegionOnly=*/true,
  2767. [&CurComponents](
  2768. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2769. StackComponents,
  2770. OpenMPClauseKind) {
  2771. auto CCI = CurComponents.rbegin();
  2772. auto CCE = CurComponents.rend();
  2773. for (const auto &SC : llvm::reverse(StackComponents)) {
  2774. // Do both expressions have the same kind?
  2775. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2776. SC.getAssociatedExpression()->getStmtClass())
  2777. if (!(isa<OMPArraySectionExpr>(
  2778. SC.getAssociatedExpression()) &&
  2779. isa<ArraySubscriptExpr>(
  2780. CCI->getAssociatedExpression())))
  2781. return false;
  2782. const Decl *CCD = CCI->getAssociatedDeclaration();
  2783. const Decl *SCD = SC.getAssociatedDeclaration();
  2784. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2785. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2786. if (SCD != CCD)
  2787. return false;
  2788. std::advance(CCI, 1);
  2789. if (CCI == CCE)
  2790. break;
  2791. }
  2792. return true;
  2793. })) {
  2794. Visit(E->getBase());
  2795. }
  2796. } else {
  2797. Visit(E->getBase());
  2798. }
  2799. }
  2800. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2801. for (OMPClause *C : S->clauses()) {
  2802. // Skip analysis of arguments of implicitly defined firstprivate clause
  2803. // for task|target directives.
  2804. // Skip analysis of arguments of implicitly defined map clause for target
  2805. // directives.
  2806. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2807. C->isImplicit())) {
  2808. for (Stmt *CC : C->children()) {
  2809. if (CC)
  2810. Visit(CC);
  2811. }
  2812. }
  2813. }
  2814. // Check implicitly captured variables.
  2815. VisitSubCaptures(S);
  2816. }
  2817. void VisitStmt(Stmt *S) {
  2818. for (Stmt *C : S->children()) {
  2819. if (C) {
  2820. // Check implicitly captured variables in the task-based directives to
  2821. // check if they must be firstprivatized.
  2822. Visit(C);
  2823. }
  2824. }
  2825. }
  2826. void visitSubCaptures(CapturedStmt *S) {
  2827. for (const CapturedStmt::Capture &Cap : S->captures()) {
  2828. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  2829. continue;
  2830. VarDecl *VD = Cap.getCapturedVar();
  2831. // Do not try to map the variable if it or its sub-component was mapped
  2832. // already.
  2833. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2834. Stack->checkMappableExprComponentListsForDecl(
  2835. VD, /*CurrentRegionOnly=*/true,
  2836. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2837. OpenMPClauseKind) { return true; }))
  2838. continue;
  2839. DeclRefExpr *DRE = buildDeclRefExpr(
  2840. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2841. Cap.getLocation(), /*RefersToCapture=*/true);
  2842. Visit(DRE);
  2843. }
  2844. }
  2845. bool isErrorFound() const { return ErrorFound; }
  2846. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2847. return ImplicitFirstprivate;
  2848. }
  2849. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2850. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2851. return VarsWithInheritedDSA;
  2852. }
  2853. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2854. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2855. // Process declare target link variables for the target directives.
  2856. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2857. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2858. Visit(E);
  2859. }
  2860. }
  2861. };
  2862. } // namespace
  2863. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2864. switch (DKind) {
  2865. case OMPD_parallel:
  2866. case OMPD_parallel_for:
  2867. case OMPD_parallel_for_simd:
  2868. case OMPD_parallel_sections:
  2869. case OMPD_teams:
  2870. case OMPD_teams_distribute:
  2871. case OMPD_teams_distribute_simd: {
  2872. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2873. QualType KmpInt32PtrTy =
  2874. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2875. Sema::CapturedParamNameType Params[] = {
  2876. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2877. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2878. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2879. };
  2880. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2881. Params);
  2882. break;
  2883. }
  2884. case OMPD_target_teams:
  2885. case OMPD_target_parallel:
  2886. case OMPD_target_parallel_for:
  2887. case OMPD_target_parallel_for_simd:
  2888. case OMPD_target_teams_distribute:
  2889. case OMPD_target_teams_distribute_simd: {
  2890. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2891. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2892. QualType KmpInt32PtrTy =
  2893. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2894. QualType Args[] = {VoidPtrTy};
  2895. FunctionProtoType::ExtProtoInfo EPI;
  2896. EPI.Variadic = true;
  2897. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2898. Sema::CapturedParamNameType Params[] = {
  2899. std::make_pair(".global_tid.", KmpInt32Ty),
  2900. std::make_pair(".part_id.", KmpInt32PtrTy),
  2901. std::make_pair(".privates.", VoidPtrTy),
  2902. std::make_pair(
  2903. ".copy_fn.",
  2904. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2905. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2906. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2907. };
  2908. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2909. Params, /*OpenMPCaptureLevel=*/0);
  2910. // Mark this captured region as inlined, because we don't use outlined
  2911. // function directly.
  2912. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2913. AlwaysInlineAttr::CreateImplicit(
  2914. Context, {}, AttributeCommonInfo::AS_Keyword,
  2915. AlwaysInlineAttr::Keyword_forceinline));
  2916. Sema::CapturedParamNameType ParamsTarget[] = {
  2917. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2918. };
  2919. // Start a captured region for 'target' with no implicit parameters.
  2920. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2921. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  2922. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2923. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2924. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2925. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2926. };
  2927. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2928. // the same implicit parameters.
  2929. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2930. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  2931. break;
  2932. }
  2933. case OMPD_target:
  2934. case OMPD_target_simd: {
  2935. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2936. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2937. QualType KmpInt32PtrTy =
  2938. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2939. QualType Args[] = {VoidPtrTy};
  2940. FunctionProtoType::ExtProtoInfo EPI;
  2941. EPI.Variadic = true;
  2942. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2943. Sema::CapturedParamNameType Params[] = {
  2944. std::make_pair(".global_tid.", KmpInt32Ty),
  2945. std::make_pair(".part_id.", KmpInt32PtrTy),
  2946. std::make_pair(".privates.", VoidPtrTy),
  2947. std::make_pair(
  2948. ".copy_fn.",
  2949. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2950. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2951. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2952. };
  2953. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2954. Params, /*OpenMPCaptureLevel=*/0);
  2955. // Mark this captured region as inlined, because we don't use outlined
  2956. // function directly.
  2957. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2958. AlwaysInlineAttr::CreateImplicit(
  2959. Context, {}, AttributeCommonInfo::AS_Keyword,
  2960. AlwaysInlineAttr::Keyword_forceinline));
  2961. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2962. std::make_pair(StringRef(), QualType()),
  2963. /*OpenMPCaptureLevel=*/1);
  2964. break;
  2965. }
  2966. case OMPD_simd:
  2967. case OMPD_for:
  2968. case OMPD_for_simd:
  2969. case OMPD_sections:
  2970. case OMPD_section:
  2971. case OMPD_single:
  2972. case OMPD_master:
  2973. case OMPD_critical:
  2974. case OMPD_taskgroup:
  2975. case OMPD_distribute:
  2976. case OMPD_distribute_simd:
  2977. case OMPD_ordered:
  2978. case OMPD_atomic:
  2979. case OMPD_target_data: {
  2980. Sema::CapturedParamNameType Params[] = {
  2981. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2982. };
  2983. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2984. Params);
  2985. break;
  2986. }
  2987. case OMPD_task: {
  2988. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2989. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2990. QualType KmpInt32PtrTy =
  2991. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2992. QualType Args[] = {VoidPtrTy};
  2993. FunctionProtoType::ExtProtoInfo EPI;
  2994. EPI.Variadic = true;
  2995. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2996. Sema::CapturedParamNameType Params[] = {
  2997. std::make_pair(".global_tid.", KmpInt32Ty),
  2998. std::make_pair(".part_id.", KmpInt32PtrTy),
  2999. std::make_pair(".privates.", VoidPtrTy),
  3000. std::make_pair(
  3001. ".copy_fn.",
  3002. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3003. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3004. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3005. };
  3006. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3007. Params);
  3008. // Mark this captured region as inlined, because we don't use outlined
  3009. // function directly.
  3010. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3011. AlwaysInlineAttr::CreateImplicit(
  3012. Context, {}, AttributeCommonInfo::AS_Keyword,
  3013. AlwaysInlineAttr::Keyword_forceinline));
  3014. break;
  3015. }
  3016. case OMPD_taskloop:
  3017. case OMPD_taskloop_simd:
  3018. case OMPD_master_taskloop: {
  3019. QualType KmpInt32Ty =
  3020. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  3021. .withConst();
  3022. QualType KmpUInt64Ty =
  3023. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  3024. .withConst();
  3025. QualType KmpInt64Ty =
  3026. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  3027. .withConst();
  3028. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3029. QualType KmpInt32PtrTy =
  3030. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3031. QualType Args[] = {VoidPtrTy};
  3032. FunctionProtoType::ExtProtoInfo EPI;
  3033. EPI.Variadic = true;
  3034. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3035. Sema::CapturedParamNameType Params[] = {
  3036. std::make_pair(".global_tid.", KmpInt32Ty),
  3037. std::make_pair(".part_id.", KmpInt32PtrTy),
  3038. std::make_pair(".privates.", VoidPtrTy),
  3039. std::make_pair(
  3040. ".copy_fn.",
  3041. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3042. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3043. std::make_pair(".lb.", KmpUInt64Ty),
  3044. std::make_pair(".ub.", KmpUInt64Ty),
  3045. std::make_pair(".st.", KmpInt64Ty),
  3046. std::make_pair(".liter.", KmpInt32Ty),
  3047. std::make_pair(".reductions.", VoidPtrTy),
  3048. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3049. };
  3050. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3051. Params);
  3052. // Mark this captured region as inlined, because we don't use outlined
  3053. // function directly.
  3054. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3055. AlwaysInlineAttr::CreateImplicit(
  3056. Context, {}, AttributeCommonInfo::AS_Keyword,
  3057. AlwaysInlineAttr::Keyword_forceinline));
  3058. break;
  3059. }
  3060. case OMPD_distribute_parallel_for_simd:
  3061. case OMPD_distribute_parallel_for: {
  3062. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3063. QualType KmpInt32PtrTy =
  3064. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3065. Sema::CapturedParamNameType Params[] = {
  3066. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3067. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3068. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3069. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3070. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3071. };
  3072. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3073. Params);
  3074. break;
  3075. }
  3076. case OMPD_target_teams_distribute_parallel_for:
  3077. case OMPD_target_teams_distribute_parallel_for_simd: {
  3078. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3079. QualType KmpInt32PtrTy =
  3080. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3081. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3082. QualType Args[] = {VoidPtrTy};
  3083. FunctionProtoType::ExtProtoInfo EPI;
  3084. EPI.Variadic = true;
  3085. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3086. Sema::CapturedParamNameType Params[] = {
  3087. std::make_pair(".global_tid.", KmpInt32Ty),
  3088. std::make_pair(".part_id.", KmpInt32PtrTy),
  3089. std::make_pair(".privates.", VoidPtrTy),
  3090. std::make_pair(
  3091. ".copy_fn.",
  3092. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3093. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3094. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3095. };
  3096. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3097. Params, /*OpenMPCaptureLevel=*/0);
  3098. // Mark this captured region as inlined, because we don't use outlined
  3099. // function directly.
  3100. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3101. AlwaysInlineAttr::CreateImplicit(
  3102. Context, {}, AttributeCommonInfo::AS_Keyword,
  3103. AlwaysInlineAttr::Keyword_forceinline));
  3104. Sema::CapturedParamNameType ParamsTarget[] = {
  3105. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3106. };
  3107. // Start a captured region for 'target' with no implicit parameters.
  3108. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3109. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3110. Sema::CapturedParamNameType ParamsTeams[] = {
  3111. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3112. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3113. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3114. };
  3115. // Start a captured region for 'target' with no implicit parameters.
  3116. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3117. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  3118. Sema::CapturedParamNameType ParamsParallel[] = {
  3119. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3120. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3121. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3122. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3123. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3124. };
  3125. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3126. // the same implicit parameters.
  3127. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3128. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  3129. break;
  3130. }
  3131. case OMPD_teams_distribute_parallel_for:
  3132. case OMPD_teams_distribute_parallel_for_simd: {
  3133. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3134. QualType KmpInt32PtrTy =
  3135. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3136. Sema::CapturedParamNameType ParamsTeams[] = {
  3137. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3138. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3139. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3140. };
  3141. // Start a captured region for 'target' with no implicit parameters.
  3142. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3143. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  3144. Sema::CapturedParamNameType ParamsParallel[] = {
  3145. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3146. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3147. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  3148. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  3149. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3150. };
  3151. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3152. // the same implicit parameters.
  3153. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3154. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  3155. break;
  3156. }
  3157. case OMPD_target_update:
  3158. case OMPD_target_enter_data:
  3159. case OMPD_target_exit_data: {
  3160. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3161. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3162. QualType KmpInt32PtrTy =
  3163. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3164. QualType Args[] = {VoidPtrTy};
  3165. FunctionProtoType::ExtProtoInfo EPI;
  3166. EPI.Variadic = true;
  3167. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3168. Sema::CapturedParamNameType Params[] = {
  3169. std::make_pair(".global_tid.", KmpInt32Ty),
  3170. std::make_pair(".part_id.", KmpInt32PtrTy),
  3171. std::make_pair(".privates.", VoidPtrTy),
  3172. std::make_pair(
  3173. ".copy_fn.",
  3174. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3175. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3176. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3177. };
  3178. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3179. Params);
  3180. // Mark this captured region as inlined, because we don't use outlined
  3181. // function directly.
  3182. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3183. AlwaysInlineAttr::CreateImplicit(
  3184. Context, {}, AttributeCommonInfo::AS_Keyword,
  3185. AlwaysInlineAttr::Keyword_forceinline));
  3186. break;
  3187. }
  3188. case OMPD_threadprivate:
  3189. case OMPD_allocate:
  3190. case OMPD_taskyield:
  3191. case OMPD_barrier:
  3192. case OMPD_taskwait:
  3193. case OMPD_cancellation_point:
  3194. case OMPD_cancel:
  3195. case OMPD_flush:
  3196. case OMPD_declare_reduction:
  3197. case OMPD_declare_mapper:
  3198. case OMPD_declare_simd:
  3199. case OMPD_declare_target:
  3200. case OMPD_end_declare_target:
  3201. case OMPD_requires:
  3202. case OMPD_declare_variant:
  3203. llvm_unreachable("OpenMP Directive is not allowed");
  3204. case OMPD_unknown:
  3205. llvm_unreachable("Unknown OpenMP directive");
  3206. }
  3207. }
  3208. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  3209. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3210. getOpenMPCaptureRegions(CaptureRegions, DKind);
  3211. return CaptureRegions.size();
  3212. }
  3213. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  3214. Expr *CaptureExpr, bool WithInit,
  3215. bool AsExpression) {
  3216. assert(CaptureExpr);
  3217. ASTContext &C = S.getASTContext();
  3218. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  3219. QualType Ty = Init->getType();
  3220. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  3221. if (S.getLangOpts().CPlusPlus) {
  3222. Ty = C.getLValueReferenceType(Ty);
  3223. } else {
  3224. Ty = C.getPointerType(Ty);
  3225. ExprResult Res =
  3226. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  3227. if (!Res.isUsable())
  3228. return nullptr;
  3229. Init = Res.get();
  3230. }
  3231. WithInit = true;
  3232. }
  3233. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  3234. CaptureExpr->getBeginLoc());
  3235. if (!WithInit)
  3236. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  3237. S.CurContext->addHiddenDecl(CED);
  3238. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  3239. return CED;
  3240. }
  3241. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  3242. bool WithInit) {
  3243. OMPCapturedExprDecl *CD;
  3244. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  3245. CD = cast<OMPCapturedExprDecl>(VD);
  3246. else
  3247. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  3248. /*AsExpression=*/false);
  3249. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3250. CaptureExpr->getExprLoc());
  3251. }
  3252. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  3253. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  3254. if (!Ref) {
  3255. OMPCapturedExprDecl *CD = buildCaptureDecl(
  3256. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  3257. /*WithInit=*/true, /*AsExpression=*/true);
  3258. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  3259. CaptureExpr->getExprLoc());
  3260. }
  3261. ExprResult Res = Ref;
  3262. if (!S.getLangOpts().CPlusPlus &&
  3263. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  3264. Ref->getType()->isPointerType()) {
  3265. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  3266. if (!Res.isUsable())
  3267. return ExprError();
  3268. }
  3269. return S.DefaultLvalueConversion(Res.get());
  3270. }
  3271. namespace {
  3272. // OpenMP directives parsed in this section are represented as a
  3273. // CapturedStatement with an associated statement. If a syntax error
  3274. // is detected during the parsing of the associated statement, the
  3275. // compiler must abort processing and close the CapturedStatement.
  3276. //
  3277. // Combined directives such as 'target parallel' have more than one
  3278. // nested CapturedStatements. This RAII ensures that we unwind out
  3279. // of all the nested CapturedStatements when an error is found.
  3280. class CaptureRegionUnwinderRAII {
  3281. private:
  3282. Sema &S;
  3283. bool &ErrorFound;
  3284. OpenMPDirectiveKind DKind = OMPD_unknown;
  3285. public:
  3286. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3287. OpenMPDirectiveKind DKind)
  3288. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3289. ~CaptureRegionUnwinderRAII() {
  3290. if (ErrorFound) {
  3291. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3292. while (--ThisCaptureLevel >= 0)
  3293. S.ActOnCapturedRegionError();
  3294. }
  3295. }
  3296. };
  3297. } // namespace
  3298. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  3299. // Capture variables captured by reference in lambdas for target-based
  3300. // directives.
  3301. if (!CurContext->isDependentContext() &&
  3302. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  3303. isOpenMPTargetDataManagementDirective(
  3304. DSAStack->getCurrentDirective()))) {
  3305. QualType Type = V->getType();
  3306. if (const auto *RD = Type.getCanonicalType()
  3307. .getNonReferenceType()
  3308. ->getAsCXXRecordDecl()) {
  3309. bool SavedForceCaptureByReferenceInTargetExecutable =
  3310. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  3311. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3312. /*V=*/true);
  3313. if (RD->isLambda()) {
  3314. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  3315. FieldDecl *ThisCapture;
  3316. RD->getCaptureFields(Captures, ThisCapture);
  3317. for (const LambdaCapture &LC : RD->captures()) {
  3318. if (LC.getCaptureKind() == LCK_ByRef) {
  3319. VarDecl *VD = LC.getCapturedVar();
  3320. DeclContext *VDC = VD->getDeclContext();
  3321. if (!VDC->Encloses(CurContext))
  3322. continue;
  3323. MarkVariableReferenced(LC.getLocation(), VD);
  3324. } else if (LC.getCaptureKind() == LCK_This) {
  3325. QualType ThisTy = getCurrentThisType();
  3326. if (!ThisTy.isNull() &&
  3327. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  3328. CheckCXXThisCapture(LC.getLocation());
  3329. }
  3330. }
  3331. }
  3332. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  3333. SavedForceCaptureByReferenceInTargetExecutable);
  3334. }
  3335. }
  3336. }
  3337. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3338. ArrayRef<OMPClause *> Clauses) {
  3339. bool ErrorFound = false;
  3340. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3341. *this, ErrorFound, DSAStack->getCurrentDirective());
  3342. if (!S.isUsable()) {
  3343. ErrorFound = true;
  3344. return StmtError();
  3345. }
  3346. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3347. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3348. OMPOrderedClause *OC = nullptr;
  3349. OMPScheduleClause *SC = nullptr;
  3350. SmallVector<const OMPLinearClause *, 4> LCs;
  3351. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3352. // This is required for proper codegen.
  3353. for (OMPClause *Clause : Clauses) {
  3354. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3355. Clause->getClauseKind() == OMPC_in_reduction) {
  3356. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3357. // with the corresponding in_reduction items.
  3358. auto *IRC = cast<OMPInReductionClause>(Clause);
  3359. for (Expr *E : IRC->taskgroup_descriptors())
  3360. if (E)
  3361. MarkDeclarationsReferencedInExpr(E);
  3362. }
  3363. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3364. Clause->getClauseKind() == OMPC_copyprivate ||
  3365. (getLangOpts().OpenMPUseTLS &&
  3366. getASTContext().getTargetInfo().isTLSSupported() &&
  3367. Clause->getClauseKind() == OMPC_copyin)) {
  3368. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3369. // Mark all variables in private list clauses as used in inner region.
  3370. for (Stmt *VarRef : Clause->children()) {
  3371. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3372. MarkDeclarationsReferencedInExpr(E);
  3373. }
  3374. }
  3375. DSAStack->setForceVarCapturing(/*V=*/false);
  3376. } else if (CaptureRegions.size() > 1 ||
  3377. CaptureRegions.back() != OMPD_unknown) {
  3378. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3379. PICs.push_back(C);
  3380. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3381. if (Expr *E = C->getPostUpdateExpr())
  3382. MarkDeclarationsReferencedInExpr(E);
  3383. }
  3384. }
  3385. if (Clause->getClauseKind() == OMPC_schedule)
  3386. SC = cast<OMPScheduleClause>(Clause);
  3387. else if (Clause->getClauseKind() == OMPC_ordered)
  3388. OC = cast<OMPOrderedClause>(Clause);
  3389. else if (Clause->getClauseKind() == OMPC_linear)
  3390. LCs.push_back(cast<OMPLinearClause>(Clause));
  3391. }
  3392. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3393. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3394. // specified.
  3395. if (SC &&
  3396. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3397. SC->getSecondScheduleModifier() ==
  3398. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3399. OC) {
  3400. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3401. ? SC->getFirstScheduleModifierLoc()
  3402. : SC->getSecondScheduleModifierLoc(),
  3403. diag::err_omp_schedule_nonmonotonic_ordered)
  3404. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3405. ErrorFound = true;
  3406. }
  3407. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3408. for (const OMPLinearClause *C : LCs) {
  3409. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3410. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3411. }
  3412. ErrorFound = true;
  3413. }
  3414. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3415. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3416. OC->getNumForLoops()) {
  3417. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3418. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3419. ErrorFound = true;
  3420. }
  3421. if (ErrorFound) {
  3422. return StmtError();
  3423. }
  3424. StmtResult SR = S;
  3425. unsigned CompletedRegions = 0;
  3426. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3427. // Mark all variables in private list clauses as used in inner region.
  3428. // Required for proper codegen of combined directives.
  3429. // TODO: add processing for other clauses.
  3430. if (ThisCaptureRegion != OMPD_unknown) {
  3431. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3432. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3433. // Find the particular capture region for the clause if the
  3434. // directive is a combined one with multiple capture regions.
  3435. // If the directive is not a combined one, the capture region
  3436. // associated with the clause is OMPD_unknown and is generated
  3437. // only once.
  3438. if (CaptureRegion == ThisCaptureRegion ||
  3439. CaptureRegion == OMPD_unknown) {
  3440. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3441. for (Decl *D : DS->decls())
  3442. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3443. }
  3444. }
  3445. }
  3446. }
  3447. if (++CompletedRegions == CaptureRegions.size())
  3448. DSAStack->setBodyComplete();
  3449. SR = ActOnCapturedRegionEnd(SR.get());
  3450. }
  3451. return SR;
  3452. }
  3453. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3454. OpenMPDirectiveKind CancelRegion,
  3455. SourceLocation StartLoc) {
  3456. // CancelRegion is only needed for cancel and cancellation_point.
  3457. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3458. return false;
  3459. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3460. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3461. return false;
  3462. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3463. << getOpenMPDirectiveName(CancelRegion);
  3464. return true;
  3465. }
  3466. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3467. OpenMPDirectiveKind CurrentRegion,
  3468. const DeclarationNameInfo &CurrentName,
  3469. OpenMPDirectiveKind CancelRegion,
  3470. SourceLocation StartLoc) {
  3471. if (Stack->getCurScope()) {
  3472. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3473. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3474. bool NestingProhibited = false;
  3475. bool CloseNesting = true;
  3476. bool OrphanSeen = false;
  3477. enum {
  3478. NoRecommend,
  3479. ShouldBeInParallelRegion,
  3480. ShouldBeInOrderedRegion,
  3481. ShouldBeInTargetRegion,
  3482. ShouldBeInTeamsRegion
  3483. } Recommend = NoRecommend;
  3484. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3485. // OpenMP [2.16, Nesting of Regions]
  3486. // OpenMP constructs may not be nested inside a simd region.
  3487. // OpenMP [2.8.1,simd Construct, Restrictions]
  3488. // An ordered construct with the simd clause is the only OpenMP
  3489. // construct that can appear in the simd region.
  3490. // Allowing a SIMD construct nested in another SIMD construct is an
  3491. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3492. // message.
  3493. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3494. ? diag::err_omp_prohibited_region_simd
  3495. : diag::warn_omp_nesting_simd);
  3496. return CurrentRegion != OMPD_simd;
  3497. }
  3498. if (ParentRegion == OMPD_atomic) {
  3499. // OpenMP [2.16, Nesting of Regions]
  3500. // OpenMP constructs may not be nested inside an atomic region.
  3501. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3502. return true;
  3503. }
  3504. if (CurrentRegion == OMPD_section) {
  3505. // OpenMP [2.7.2, sections Construct, Restrictions]
  3506. // Orphaned section directives are prohibited. That is, the section
  3507. // directives must appear within the sections construct and must not be
  3508. // encountered elsewhere in the sections region.
  3509. if (ParentRegion != OMPD_sections &&
  3510. ParentRegion != OMPD_parallel_sections) {
  3511. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3512. << (ParentRegion != OMPD_unknown)
  3513. << getOpenMPDirectiveName(ParentRegion);
  3514. return true;
  3515. }
  3516. return false;
  3517. }
  3518. // Allow some constructs (except teams and cancellation constructs) to be
  3519. // orphaned (they could be used in functions, called from OpenMP regions
  3520. // with the required preconditions).
  3521. if (ParentRegion == OMPD_unknown &&
  3522. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3523. CurrentRegion != OMPD_cancellation_point &&
  3524. CurrentRegion != OMPD_cancel)
  3525. return false;
  3526. if (CurrentRegion == OMPD_cancellation_point ||
  3527. CurrentRegion == OMPD_cancel) {
  3528. // OpenMP [2.16, Nesting of Regions]
  3529. // A cancellation point construct for which construct-type-clause is
  3530. // taskgroup must be nested inside a task construct. A cancellation
  3531. // point construct for which construct-type-clause is not taskgroup must
  3532. // be closely nested inside an OpenMP construct that matches the type
  3533. // specified in construct-type-clause.
  3534. // A cancel construct for which construct-type-clause is taskgroup must be
  3535. // nested inside a task construct. A cancel construct for which
  3536. // construct-type-clause is not taskgroup must be closely nested inside an
  3537. // OpenMP construct that matches the type specified in
  3538. // construct-type-clause.
  3539. NestingProhibited =
  3540. !((CancelRegion == OMPD_parallel &&
  3541. (ParentRegion == OMPD_parallel ||
  3542. ParentRegion == OMPD_target_parallel)) ||
  3543. (CancelRegion == OMPD_for &&
  3544. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3545. ParentRegion == OMPD_target_parallel_for ||
  3546. ParentRegion == OMPD_distribute_parallel_for ||
  3547. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3548. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3549. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3550. (CancelRegion == OMPD_sections &&
  3551. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3552. ParentRegion == OMPD_parallel_sections)));
  3553. OrphanSeen = ParentRegion == OMPD_unknown;
  3554. } else if (CurrentRegion == OMPD_master) {
  3555. // OpenMP [2.16, Nesting of Regions]
  3556. // A master region may not be closely nested inside a worksharing,
  3557. // atomic, or explicit task region.
  3558. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3559. isOpenMPTaskingDirective(ParentRegion);
  3560. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3561. // OpenMP [2.16, Nesting of Regions]
  3562. // A critical region may not be nested (closely or otherwise) inside a
  3563. // critical region with the same name. Note that this restriction is not
  3564. // sufficient to prevent deadlock.
  3565. SourceLocation PreviousCriticalLoc;
  3566. bool DeadLock = Stack->hasDirective(
  3567. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3568. const DeclarationNameInfo &DNI,
  3569. SourceLocation Loc) {
  3570. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3571. PreviousCriticalLoc = Loc;
  3572. return true;
  3573. }
  3574. return false;
  3575. },
  3576. false /* skip top directive */);
  3577. if (DeadLock) {
  3578. SemaRef.Diag(StartLoc,
  3579. diag::err_omp_prohibited_region_critical_same_name)
  3580. << CurrentName.getName();
  3581. if (PreviousCriticalLoc.isValid())
  3582. SemaRef.Diag(PreviousCriticalLoc,
  3583. diag::note_omp_previous_critical_region);
  3584. return true;
  3585. }
  3586. } else if (CurrentRegion == OMPD_barrier) {
  3587. // OpenMP [2.16, Nesting of Regions]
  3588. // A barrier region may not be closely nested inside a worksharing,
  3589. // explicit task, critical, ordered, atomic, or master region.
  3590. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3591. isOpenMPTaskingDirective(ParentRegion) ||
  3592. ParentRegion == OMPD_master ||
  3593. ParentRegion == OMPD_critical ||
  3594. ParentRegion == OMPD_ordered;
  3595. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3596. !isOpenMPParallelDirective(CurrentRegion) &&
  3597. !isOpenMPTeamsDirective(CurrentRegion)) {
  3598. // OpenMP [2.16, Nesting of Regions]
  3599. // A worksharing region may not be closely nested inside a worksharing,
  3600. // explicit task, critical, ordered, atomic, or master region.
  3601. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3602. isOpenMPTaskingDirective(ParentRegion) ||
  3603. ParentRegion == OMPD_master ||
  3604. ParentRegion == OMPD_critical ||
  3605. ParentRegion == OMPD_ordered;
  3606. Recommend = ShouldBeInParallelRegion;
  3607. } else if (CurrentRegion == OMPD_ordered) {
  3608. // OpenMP [2.16, Nesting of Regions]
  3609. // An ordered region may not be closely nested inside a critical,
  3610. // atomic, or explicit task region.
  3611. // An ordered region must be closely nested inside a loop region (or
  3612. // parallel loop region) with an ordered clause.
  3613. // OpenMP [2.8.1,simd Construct, Restrictions]
  3614. // An ordered construct with the simd clause is the only OpenMP construct
  3615. // that can appear in the simd region.
  3616. NestingProhibited = ParentRegion == OMPD_critical ||
  3617. isOpenMPTaskingDirective(ParentRegion) ||
  3618. !(isOpenMPSimdDirective(ParentRegion) ||
  3619. Stack->isParentOrderedRegion());
  3620. Recommend = ShouldBeInOrderedRegion;
  3621. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3622. // OpenMP [2.16, Nesting of Regions]
  3623. // If specified, a teams construct must be contained within a target
  3624. // construct.
  3625. NestingProhibited =
  3626. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  3627. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  3628. ParentRegion != OMPD_target);
  3629. OrphanSeen = ParentRegion == OMPD_unknown;
  3630. Recommend = ShouldBeInTargetRegion;
  3631. }
  3632. if (!NestingProhibited &&
  3633. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3634. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3635. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3636. // OpenMP [2.16, Nesting of Regions]
  3637. // distribute, parallel, parallel sections, parallel workshare, and the
  3638. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3639. // constructs that can be closely nested in the teams region.
  3640. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3641. !isOpenMPDistributeDirective(CurrentRegion);
  3642. Recommend = ShouldBeInParallelRegion;
  3643. }
  3644. if (!NestingProhibited &&
  3645. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3646. // OpenMP 4.5 [2.17 Nesting of Regions]
  3647. // The region associated with the distribute construct must be strictly
  3648. // nested inside a teams region
  3649. NestingProhibited =
  3650. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3651. Recommend = ShouldBeInTeamsRegion;
  3652. }
  3653. if (!NestingProhibited &&
  3654. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3655. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3656. // OpenMP 4.5 [2.17 Nesting of Regions]
  3657. // If a target, target update, target data, target enter data, or
  3658. // target exit data construct is encountered during execution of a
  3659. // target region, the behavior is unspecified.
  3660. NestingProhibited = Stack->hasDirective(
  3661. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3662. SourceLocation) {
  3663. if (isOpenMPTargetExecutionDirective(K)) {
  3664. OffendingRegion = K;
  3665. return true;
  3666. }
  3667. return false;
  3668. },
  3669. false /* don't skip top directive */);
  3670. CloseNesting = false;
  3671. }
  3672. if (NestingProhibited) {
  3673. if (OrphanSeen) {
  3674. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3675. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3676. } else {
  3677. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3678. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3679. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3680. }
  3681. return true;
  3682. }
  3683. }
  3684. return false;
  3685. }
  3686. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3687. ArrayRef<OMPClause *> Clauses,
  3688. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3689. bool ErrorFound = false;
  3690. unsigned NamedModifiersNumber = 0;
  3691. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3692. OMPD_unknown + 1);
  3693. SmallVector<SourceLocation, 4> NameModifierLoc;
  3694. for (const OMPClause *C : Clauses) {
  3695. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3696. // At most one if clause without a directive-name-modifier can appear on
  3697. // the directive.
  3698. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3699. if (FoundNameModifiers[CurNM]) {
  3700. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3701. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3702. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3703. ErrorFound = true;
  3704. } else if (CurNM != OMPD_unknown) {
  3705. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3706. ++NamedModifiersNumber;
  3707. }
  3708. FoundNameModifiers[CurNM] = IC;
  3709. if (CurNM == OMPD_unknown)
  3710. continue;
  3711. // Check if the specified name modifier is allowed for the current
  3712. // directive.
  3713. // At most one if clause with the particular directive-name-modifier can
  3714. // appear on the directive.
  3715. bool MatchFound = false;
  3716. for (auto NM : AllowedNameModifiers) {
  3717. if (CurNM == NM) {
  3718. MatchFound = true;
  3719. break;
  3720. }
  3721. }
  3722. if (!MatchFound) {
  3723. S.Diag(IC->getNameModifierLoc(),
  3724. diag::err_omp_wrong_if_directive_name_modifier)
  3725. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3726. ErrorFound = true;
  3727. }
  3728. }
  3729. }
  3730. // If any if clause on the directive includes a directive-name-modifier then
  3731. // all if clauses on the directive must include a directive-name-modifier.
  3732. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3733. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3734. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3735. diag::err_omp_no_more_if_clause);
  3736. } else {
  3737. std::string Values;
  3738. std::string Sep(", ");
  3739. unsigned AllowedCnt = 0;
  3740. unsigned TotalAllowedNum =
  3741. AllowedNameModifiers.size() - NamedModifiersNumber;
  3742. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3743. ++Cnt) {
  3744. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3745. if (!FoundNameModifiers[NM]) {
  3746. Values += "'";
  3747. Values += getOpenMPDirectiveName(NM);
  3748. Values += "'";
  3749. if (AllowedCnt + 2 == TotalAllowedNum)
  3750. Values += " or ";
  3751. else if (AllowedCnt + 1 != TotalAllowedNum)
  3752. Values += Sep;
  3753. ++AllowedCnt;
  3754. }
  3755. }
  3756. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3757. diag::err_omp_unnamed_if_clause)
  3758. << (TotalAllowedNum > 1) << Values;
  3759. }
  3760. for (SourceLocation Loc : NameModifierLoc) {
  3761. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3762. }
  3763. ErrorFound = true;
  3764. }
  3765. return ErrorFound;
  3766. }
  3767. static std::pair<ValueDecl *, bool>
  3768. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3769. SourceRange &ERange, bool AllowArraySection = false) {
  3770. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3771. RefExpr->containsUnexpandedParameterPack())
  3772. return std::make_pair(nullptr, true);
  3773. // OpenMP [3.1, C/C++]
  3774. // A list item is a variable name.
  3775. // OpenMP [2.9.3.3, Restrictions, p.1]
  3776. // A variable that is part of another variable (as an array or
  3777. // structure element) cannot appear in a private clause.
  3778. RefExpr = RefExpr->IgnoreParens();
  3779. enum {
  3780. NoArrayExpr = -1,
  3781. ArraySubscript = 0,
  3782. OMPArraySection = 1
  3783. } IsArrayExpr = NoArrayExpr;
  3784. if (AllowArraySection) {
  3785. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3786. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3787. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3788. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3789. RefExpr = Base;
  3790. IsArrayExpr = ArraySubscript;
  3791. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3792. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3793. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3794. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3795. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3796. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3797. RefExpr = Base;
  3798. IsArrayExpr = OMPArraySection;
  3799. }
  3800. }
  3801. ELoc = RefExpr->getExprLoc();
  3802. ERange = RefExpr->getSourceRange();
  3803. RefExpr = RefExpr->IgnoreParenImpCasts();
  3804. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3805. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3806. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3807. (S.getCurrentThisType().isNull() || !ME ||
  3808. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3809. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3810. if (IsArrayExpr != NoArrayExpr) {
  3811. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3812. << ERange;
  3813. } else {
  3814. S.Diag(ELoc,
  3815. AllowArraySection
  3816. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3817. : diag::err_omp_expected_var_name_member_expr)
  3818. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3819. }
  3820. return std::make_pair(nullptr, false);
  3821. }
  3822. return std::make_pair(
  3823. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3824. }
  3825. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3826. ArrayRef<OMPClause *> Clauses) {
  3827. assert(!S.CurContext->isDependentContext() &&
  3828. "Expected non-dependent context.");
  3829. auto AllocateRange =
  3830. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3831. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3832. DeclToCopy;
  3833. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3834. return isOpenMPPrivate(C->getClauseKind());
  3835. });
  3836. for (OMPClause *Cl : PrivateRange) {
  3837. MutableArrayRef<Expr *>::iterator I, It, Et;
  3838. if (Cl->getClauseKind() == OMPC_private) {
  3839. auto *PC = cast<OMPPrivateClause>(Cl);
  3840. I = PC->private_copies().begin();
  3841. It = PC->varlist_begin();
  3842. Et = PC->varlist_end();
  3843. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3844. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3845. I = PC->private_copies().begin();
  3846. It = PC->varlist_begin();
  3847. Et = PC->varlist_end();
  3848. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3849. auto *PC = cast<OMPLastprivateClause>(Cl);
  3850. I = PC->private_copies().begin();
  3851. It = PC->varlist_begin();
  3852. Et = PC->varlist_end();
  3853. } else if (Cl->getClauseKind() == OMPC_linear) {
  3854. auto *PC = cast<OMPLinearClause>(Cl);
  3855. I = PC->privates().begin();
  3856. It = PC->varlist_begin();
  3857. Et = PC->varlist_end();
  3858. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3859. auto *PC = cast<OMPReductionClause>(Cl);
  3860. I = PC->privates().begin();
  3861. It = PC->varlist_begin();
  3862. Et = PC->varlist_end();
  3863. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3864. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3865. I = PC->privates().begin();
  3866. It = PC->varlist_begin();
  3867. Et = PC->varlist_end();
  3868. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3869. auto *PC = cast<OMPInReductionClause>(Cl);
  3870. I = PC->privates().begin();
  3871. It = PC->varlist_begin();
  3872. Et = PC->varlist_end();
  3873. } else {
  3874. llvm_unreachable("Expected private clause.");
  3875. }
  3876. for (Expr *E : llvm::make_range(It, Et)) {
  3877. if (!*I) {
  3878. ++I;
  3879. continue;
  3880. }
  3881. SourceLocation ELoc;
  3882. SourceRange ERange;
  3883. Expr *SimpleRefExpr = E;
  3884. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3885. /*AllowArraySection=*/true);
  3886. DeclToCopy.try_emplace(Res.first,
  3887. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3888. ++I;
  3889. }
  3890. }
  3891. for (OMPClause *C : AllocateRange) {
  3892. auto *AC = cast<OMPAllocateClause>(C);
  3893. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3894. getAllocatorKind(S, Stack, AC->getAllocator());
  3895. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3896. // For task, taskloop or target directives, allocation requests to memory
  3897. // allocators with the trait access set to thread result in unspecified
  3898. // behavior.
  3899. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3900. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3901. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3902. S.Diag(AC->getAllocator()->getExprLoc(),
  3903. diag::warn_omp_allocate_thread_on_task_target_directive)
  3904. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3905. }
  3906. for (Expr *E : AC->varlists()) {
  3907. SourceLocation ELoc;
  3908. SourceRange ERange;
  3909. Expr *SimpleRefExpr = E;
  3910. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3911. ValueDecl *VD = Res.first;
  3912. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3913. if (!isOpenMPPrivate(Data.CKind)) {
  3914. S.Diag(E->getExprLoc(),
  3915. diag::err_omp_expected_private_copy_for_allocate);
  3916. continue;
  3917. }
  3918. VarDecl *PrivateVD = DeclToCopy[VD];
  3919. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3920. AllocatorKind, AC->getAllocator()))
  3921. continue;
  3922. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3923. E->getSourceRange());
  3924. }
  3925. }
  3926. }
  3927. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3928. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3929. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3930. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3931. StmtResult Res = StmtError();
  3932. // First check CancelRegion which is then used in checkNestingOfRegions.
  3933. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3934. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3935. StartLoc))
  3936. return StmtError();
  3937. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3938. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3939. bool ErrorFound = false;
  3940. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3941. if (AStmt && !CurContext->isDependentContext()) {
  3942. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3943. // Check default data sharing attributes for referenced variables.
  3944. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3945. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3946. Stmt *S = AStmt;
  3947. while (--ThisCaptureLevel >= 0)
  3948. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3949. DSAChecker.Visit(S);
  3950. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  3951. !isOpenMPTaskingDirective(Kind)) {
  3952. // Visit subcaptures to generate implicit clauses for captured vars.
  3953. auto *CS = cast<CapturedStmt>(AStmt);
  3954. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3955. getOpenMPCaptureRegions(CaptureRegions, Kind);
  3956. // Ignore outer tasking regions for target directives.
  3957. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  3958. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  3959. DSAChecker.visitSubCaptures(CS);
  3960. }
  3961. if (DSAChecker.isErrorFound())
  3962. return StmtError();
  3963. // Generate list of implicitly defined firstprivate variables.
  3964. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3965. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3966. DSAChecker.getImplicitFirstprivate().begin(),
  3967. DSAChecker.getImplicitFirstprivate().end());
  3968. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3969. DSAChecker.getImplicitMap().end());
  3970. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3971. for (OMPClause *C : Clauses) {
  3972. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3973. for (Expr *E : IRC->taskgroup_descriptors())
  3974. if (E)
  3975. ImplicitFirstprivates.emplace_back(E);
  3976. }
  3977. }
  3978. if (!ImplicitFirstprivates.empty()) {
  3979. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3980. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3981. SourceLocation())) {
  3982. ClausesWithImplicit.push_back(Implicit);
  3983. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3984. ImplicitFirstprivates.size();
  3985. } else {
  3986. ErrorFound = true;
  3987. }
  3988. }
  3989. if (!ImplicitMaps.empty()) {
  3990. CXXScopeSpec MapperIdScopeSpec;
  3991. DeclarationNameInfo MapperId;
  3992. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3993. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3994. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3995. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3996. ClausesWithImplicit.emplace_back(Implicit);
  3997. ErrorFound |=
  3998. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3999. } else {
  4000. ErrorFound = true;
  4001. }
  4002. }
  4003. }
  4004. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  4005. switch (Kind) {
  4006. case OMPD_parallel:
  4007. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  4008. EndLoc);
  4009. AllowedNameModifiers.push_back(OMPD_parallel);
  4010. break;
  4011. case OMPD_simd:
  4012. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4013. VarsWithInheritedDSA);
  4014. break;
  4015. case OMPD_for:
  4016. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  4017. VarsWithInheritedDSA);
  4018. break;
  4019. case OMPD_for_simd:
  4020. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4021. EndLoc, VarsWithInheritedDSA);
  4022. break;
  4023. case OMPD_sections:
  4024. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4025. EndLoc);
  4026. break;
  4027. case OMPD_section:
  4028. assert(ClausesWithImplicit.empty() &&
  4029. "No clauses are allowed for 'omp section' directive");
  4030. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  4031. break;
  4032. case OMPD_single:
  4033. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  4034. EndLoc);
  4035. break;
  4036. case OMPD_master:
  4037. assert(ClausesWithImplicit.empty() &&
  4038. "No clauses are allowed for 'omp master' directive");
  4039. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  4040. break;
  4041. case OMPD_critical:
  4042. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  4043. StartLoc, EndLoc);
  4044. break;
  4045. case OMPD_parallel_for:
  4046. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  4047. EndLoc, VarsWithInheritedDSA);
  4048. AllowedNameModifiers.push_back(OMPD_parallel);
  4049. break;
  4050. case OMPD_parallel_for_simd:
  4051. Res = ActOnOpenMPParallelForSimdDirective(
  4052. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4053. AllowedNameModifiers.push_back(OMPD_parallel);
  4054. break;
  4055. case OMPD_parallel_sections:
  4056. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  4057. StartLoc, EndLoc);
  4058. AllowedNameModifiers.push_back(OMPD_parallel);
  4059. break;
  4060. case OMPD_task:
  4061. Res =
  4062. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4063. AllowedNameModifiers.push_back(OMPD_task);
  4064. break;
  4065. case OMPD_taskyield:
  4066. assert(ClausesWithImplicit.empty() &&
  4067. "No clauses are allowed for 'omp taskyield' directive");
  4068. assert(AStmt == nullptr &&
  4069. "No associated statement allowed for 'omp taskyield' directive");
  4070. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  4071. break;
  4072. case OMPD_barrier:
  4073. assert(ClausesWithImplicit.empty() &&
  4074. "No clauses are allowed for 'omp barrier' directive");
  4075. assert(AStmt == nullptr &&
  4076. "No associated statement allowed for 'omp barrier' directive");
  4077. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  4078. break;
  4079. case OMPD_taskwait:
  4080. assert(ClausesWithImplicit.empty() &&
  4081. "No clauses are allowed for 'omp taskwait' directive");
  4082. assert(AStmt == nullptr &&
  4083. "No associated statement allowed for 'omp taskwait' directive");
  4084. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  4085. break;
  4086. case OMPD_taskgroup:
  4087. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  4088. EndLoc);
  4089. break;
  4090. case OMPD_flush:
  4091. assert(AStmt == nullptr &&
  4092. "No associated statement allowed for 'omp flush' directive");
  4093. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  4094. break;
  4095. case OMPD_ordered:
  4096. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  4097. EndLoc);
  4098. break;
  4099. case OMPD_atomic:
  4100. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  4101. EndLoc);
  4102. break;
  4103. case OMPD_teams:
  4104. Res =
  4105. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  4106. break;
  4107. case OMPD_target:
  4108. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  4109. EndLoc);
  4110. AllowedNameModifiers.push_back(OMPD_target);
  4111. break;
  4112. case OMPD_target_parallel:
  4113. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  4114. StartLoc, EndLoc);
  4115. AllowedNameModifiers.push_back(OMPD_target);
  4116. AllowedNameModifiers.push_back(OMPD_parallel);
  4117. break;
  4118. case OMPD_target_parallel_for:
  4119. Res = ActOnOpenMPTargetParallelForDirective(
  4120. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4121. AllowedNameModifiers.push_back(OMPD_target);
  4122. AllowedNameModifiers.push_back(OMPD_parallel);
  4123. break;
  4124. case OMPD_cancellation_point:
  4125. assert(ClausesWithImplicit.empty() &&
  4126. "No clauses are allowed for 'omp cancellation point' directive");
  4127. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  4128. "cancellation point' directive");
  4129. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  4130. break;
  4131. case OMPD_cancel:
  4132. assert(AStmt == nullptr &&
  4133. "No associated statement allowed for 'omp cancel' directive");
  4134. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  4135. CancelRegion);
  4136. AllowedNameModifiers.push_back(OMPD_cancel);
  4137. break;
  4138. case OMPD_target_data:
  4139. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  4140. EndLoc);
  4141. AllowedNameModifiers.push_back(OMPD_target_data);
  4142. break;
  4143. case OMPD_target_enter_data:
  4144. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  4145. EndLoc, AStmt);
  4146. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  4147. break;
  4148. case OMPD_target_exit_data:
  4149. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  4150. EndLoc, AStmt);
  4151. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  4152. break;
  4153. case OMPD_taskloop:
  4154. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  4155. EndLoc, VarsWithInheritedDSA);
  4156. AllowedNameModifiers.push_back(OMPD_taskloop);
  4157. break;
  4158. case OMPD_taskloop_simd:
  4159. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4160. EndLoc, VarsWithInheritedDSA);
  4161. AllowedNameModifiers.push_back(OMPD_taskloop);
  4162. break;
  4163. case OMPD_master_taskloop:
  4164. Res = ActOnOpenMPMasterTaskLoopDirective(
  4165. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4166. AllowedNameModifiers.push_back(OMPD_taskloop);
  4167. break;
  4168. case OMPD_distribute:
  4169. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  4170. EndLoc, VarsWithInheritedDSA);
  4171. break;
  4172. case OMPD_target_update:
  4173. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  4174. EndLoc, AStmt);
  4175. AllowedNameModifiers.push_back(OMPD_target_update);
  4176. break;
  4177. case OMPD_distribute_parallel_for:
  4178. Res = ActOnOpenMPDistributeParallelForDirective(
  4179. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4180. AllowedNameModifiers.push_back(OMPD_parallel);
  4181. break;
  4182. case OMPD_distribute_parallel_for_simd:
  4183. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  4184. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4185. AllowedNameModifiers.push_back(OMPD_parallel);
  4186. break;
  4187. case OMPD_distribute_simd:
  4188. Res = ActOnOpenMPDistributeSimdDirective(
  4189. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4190. break;
  4191. case OMPD_target_parallel_for_simd:
  4192. Res = ActOnOpenMPTargetParallelForSimdDirective(
  4193. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4194. AllowedNameModifiers.push_back(OMPD_target);
  4195. AllowedNameModifiers.push_back(OMPD_parallel);
  4196. break;
  4197. case OMPD_target_simd:
  4198. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  4199. EndLoc, VarsWithInheritedDSA);
  4200. AllowedNameModifiers.push_back(OMPD_target);
  4201. break;
  4202. case OMPD_teams_distribute:
  4203. Res = ActOnOpenMPTeamsDistributeDirective(
  4204. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4205. break;
  4206. case OMPD_teams_distribute_simd:
  4207. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  4208. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4209. break;
  4210. case OMPD_teams_distribute_parallel_for_simd:
  4211. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  4212. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4213. AllowedNameModifiers.push_back(OMPD_parallel);
  4214. break;
  4215. case OMPD_teams_distribute_parallel_for:
  4216. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  4217. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4218. AllowedNameModifiers.push_back(OMPD_parallel);
  4219. break;
  4220. case OMPD_target_teams:
  4221. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  4222. EndLoc);
  4223. AllowedNameModifiers.push_back(OMPD_target);
  4224. break;
  4225. case OMPD_target_teams_distribute:
  4226. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  4227. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4228. AllowedNameModifiers.push_back(OMPD_target);
  4229. break;
  4230. case OMPD_target_teams_distribute_parallel_for:
  4231. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  4232. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4233. AllowedNameModifiers.push_back(OMPD_target);
  4234. AllowedNameModifiers.push_back(OMPD_parallel);
  4235. break;
  4236. case OMPD_target_teams_distribute_parallel_for_simd:
  4237. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  4238. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4239. AllowedNameModifiers.push_back(OMPD_target);
  4240. AllowedNameModifiers.push_back(OMPD_parallel);
  4241. break;
  4242. case OMPD_target_teams_distribute_simd:
  4243. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  4244. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  4245. AllowedNameModifiers.push_back(OMPD_target);
  4246. break;
  4247. case OMPD_declare_target:
  4248. case OMPD_end_declare_target:
  4249. case OMPD_threadprivate:
  4250. case OMPD_allocate:
  4251. case OMPD_declare_reduction:
  4252. case OMPD_declare_mapper:
  4253. case OMPD_declare_simd:
  4254. case OMPD_requires:
  4255. case OMPD_declare_variant:
  4256. llvm_unreachable("OpenMP Directive is not allowed");
  4257. case OMPD_unknown:
  4258. llvm_unreachable("Unknown OpenMP directive");
  4259. }
  4260. ErrorFound = Res.isInvalid() || ErrorFound;
  4261. // Check variables in the clauses if default(none) was specified.
  4262. if (DSAStack->getDefaultDSA() == DSA_none) {
  4263. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  4264. for (OMPClause *C : Clauses) {
  4265. switch (C->getClauseKind()) {
  4266. case OMPC_num_threads:
  4267. case OMPC_dist_schedule:
  4268. // Do not analyse if no parent teams directive.
  4269. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
  4270. break;
  4271. continue;
  4272. case OMPC_if:
  4273. if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
  4274. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  4275. break;
  4276. continue;
  4277. case OMPC_schedule:
  4278. break;
  4279. case OMPC_ordered:
  4280. case OMPC_device:
  4281. case OMPC_num_teams:
  4282. case OMPC_thread_limit:
  4283. case OMPC_priority:
  4284. case OMPC_grainsize:
  4285. case OMPC_num_tasks:
  4286. case OMPC_hint:
  4287. case OMPC_collapse:
  4288. case OMPC_safelen:
  4289. case OMPC_simdlen:
  4290. case OMPC_final:
  4291. case OMPC_default:
  4292. case OMPC_proc_bind:
  4293. case OMPC_private:
  4294. case OMPC_firstprivate:
  4295. case OMPC_lastprivate:
  4296. case OMPC_shared:
  4297. case OMPC_reduction:
  4298. case OMPC_task_reduction:
  4299. case OMPC_in_reduction:
  4300. case OMPC_linear:
  4301. case OMPC_aligned:
  4302. case OMPC_copyin:
  4303. case OMPC_copyprivate:
  4304. case OMPC_nowait:
  4305. case OMPC_untied:
  4306. case OMPC_mergeable:
  4307. case OMPC_allocate:
  4308. case OMPC_read:
  4309. case OMPC_write:
  4310. case OMPC_update:
  4311. case OMPC_capture:
  4312. case OMPC_seq_cst:
  4313. case OMPC_depend:
  4314. case OMPC_threads:
  4315. case OMPC_simd:
  4316. case OMPC_map:
  4317. case OMPC_nogroup:
  4318. case OMPC_defaultmap:
  4319. case OMPC_to:
  4320. case OMPC_from:
  4321. case OMPC_use_device_ptr:
  4322. case OMPC_is_device_ptr:
  4323. continue;
  4324. case OMPC_allocator:
  4325. case OMPC_flush:
  4326. case OMPC_threadprivate:
  4327. case OMPC_uniform:
  4328. case OMPC_unknown:
  4329. case OMPC_unified_address:
  4330. case OMPC_unified_shared_memory:
  4331. case OMPC_reverse_offload:
  4332. case OMPC_dynamic_allocators:
  4333. case OMPC_atomic_default_mem_order:
  4334. case OMPC_device_type:
  4335. case OMPC_match:
  4336. llvm_unreachable("Unexpected clause");
  4337. }
  4338. for (Stmt *CC : C->children()) {
  4339. if (CC)
  4340. DSAChecker.Visit(CC);
  4341. }
  4342. }
  4343. for (auto &P : DSAChecker.getVarsWithInheritedDSA())
  4344. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  4345. }
  4346. for (const auto &P : VarsWithInheritedDSA) {
  4347. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  4348. continue;
  4349. ErrorFound = true;
  4350. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  4351. << P.first << P.second->getSourceRange();
  4352. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  4353. }
  4354. if (!AllowedNameModifiers.empty())
  4355. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  4356. ErrorFound;
  4357. if (ErrorFound)
  4358. return StmtError();
  4359. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  4360. Res.getAs<OMPExecutableDirective>()
  4361. ->getStructuredBlock()
  4362. ->setIsOMPStructuredBlock(true);
  4363. }
  4364. if (!CurContext->isDependentContext() &&
  4365. isOpenMPTargetExecutionDirective(Kind) &&
  4366. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  4367. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  4368. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  4369. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  4370. // Register target to DSA Stack.
  4371. DSAStack->addTargetDirLocation(StartLoc);
  4372. }
  4373. return Res;
  4374. }
  4375. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  4376. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  4377. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  4378. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  4379. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  4380. assert(Aligneds.size() == Alignments.size());
  4381. assert(Linears.size() == LinModifiers.size());
  4382. assert(Linears.size() == Steps.size());
  4383. if (!DG || DG.get().isNull())
  4384. return DeclGroupPtrTy();
  4385. const int SimdId = 0;
  4386. if (!DG.get().isSingleDecl()) {
  4387. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4388. << SimdId;
  4389. return DG;
  4390. }
  4391. Decl *ADecl = DG.get().getSingleDecl();
  4392. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4393. ADecl = FTD->getTemplatedDecl();
  4394. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4395. if (!FD) {
  4396. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  4397. return DeclGroupPtrTy();
  4398. }
  4399. // OpenMP [2.8.2, declare simd construct, Description]
  4400. // The parameter of the simdlen clause must be a constant positive integer
  4401. // expression.
  4402. ExprResult SL;
  4403. if (Simdlen)
  4404. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  4405. // OpenMP [2.8.2, declare simd construct, Description]
  4406. // The special this pointer can be used as if was one of the arguments to the
  4407. // function in any of the linear, aligned, or uniform clauses.
  4408. // The uniform clause declares one or more arguments to have an invariant
  4409. // value for all concurrent invocations of the function in the execution of a
  4410. // single SIMD loop.
  4411. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  4412. const Expr *UniformedLinearThis = nullptr;
  4413. for (const Expr *E : Uniforms) {
  4414. E = E->IgnoreParenImpCasts();
  4415. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4416. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4417. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4418. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4419. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  4420. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  4421. continue;
  4422. }
  4423. if (isa<CXXThisExpr>(E)) {
  4424. UniformedLinearThis = E;
  4425. continue;
  4426. }
  4427. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4428. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4429. }
  4430. // OpenMP [2.8.2, declare simd construct, Description]
  4431. // The aligned clause declares that the object to which each list item points
  4432. // is aligned to the number of bytes expressed in the optional parameter of
  4433. // the aligned clause.
  4434. // The special this pointer can be used as if was one of the arguments to the
  4435. // function in any of the linear, aligned, or uniform clauses.
  4436. // The type of list items appearing in the aligned clause must be array,
  4437. // pointer, reference to array, or reference to pointer.
  4438. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  4439. const Expr *AlignedThis = nullptr;
  4440. for (const Expr *E : Aligneds) {
  4441. E = E->IgnoreParenImpCasts();
  4442. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4443. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4444. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4445. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4446. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4447. ->getCanonicalDecl() == CanonPVD) {
  4448. // OpenMP [2.8.1, simd construct, Restrictions]
  4449. // A list-item cannot appear in more than one aligned clause.
  4450. if (AlignedArgs.count(CanonPVD) > 0) {
  4451. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4452. << 1 << E->getSourceRange();
  4453. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4454. diag::note_omp_explicit_dsa)
  4455. << getOpenMPClauseName(OMPC_aligned);
  4456. continue;
  4457. }
  4458. AlignedArgs[CanonPVD] = E;
  4459. QualType QTy = PVD->getType()
  4460. .getNonReferenceType()
  4461. .getUnqualifiedType()
  4462. .getCanonicalType();
  4463. const Type *Ty = QTy.getTypePtrOrNull();
  4464. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4465. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4466. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4467. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4468. }
  4469. continue;
  4470. }
  4471. }
  4472. if (isa<CXXThisExpr>(E)) {
  4473. if (AlignedThis) {
  4474. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4475. << 2 << E->getSourceRange();
  4476. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4477. << getOpenMPClauseName(OMPC_aligned);
  4478. }
  4479. AlignedThis = E;
  4480. continue;
  4481. }
  4482. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4483. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4484. }
  4485. // The optional parameter of the aligned clause, alignment, must be a constant
  4486. // positive integer expression. If no optional parameter is specified,
  4487. // implementation-defined default alignments for SIMD instructions on the
  4488. // target platforms are assumed.
  4489. SmallVector<const Expr *, 4> NewAligns;
  4490. for (Expr *E : Alignments) {
  4491. ExprResult Align;
  4492. if (E)
  4493. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4494. NewAligns.push_back(Align.get());
  4495. }
  4496. // OpenMP [2.8.2, declare simd construct, Description]
  4497. // The linear clause declares one or more list items to be private to a SIMD
  4498. // lane and to have a linear relationship with respect to the iteration space
  4499. // of a loop.
  4500. // The special this pointer can be used as if was one of the arguments to the
  4501. // function in any of the linear, aligned, or uniform clauses.
  4502. // When a linear-step expression is specified in a linear clause it must be
  4503. // either a constant integer expression or an integer-typed parameter that is
  4504. // specified in a uniform clause on the directive.
  4505. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4506. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4507. auto MI = LinModifiers.begin();
  4508. for (const Expr *E : Linears) {
  4509. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4510. ++MI;
  4511. E = E->IgnoreParenImpCasts();
  4512. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4513. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4514. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4515. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4516. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4517. ->getCanonicalDecl() == CanonPVD) {
  4518. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4519. // A list-item cannot appear in more than one linear clause.
  4520. if (LinearArgs.count(CanonPVD) > 0) {
  4521. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4522. << getOpenMPClauseName(OMPC_linear)
  4523. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4524. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4525. diag::note_omp_explicit_dsa)
  4526. << getOpenMPClauseName(OMPC_linear);
  4527. continue;
  4528. }
  4529. // Each argument can appear in at most one uniform or linear clause.
  4530. if (UniformedArgs.count(CanonPVD) > 0) {
  4531. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4532. << getOpenMPClauseName(OMPC_linear)
  4533. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4534. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4535. diag::note_omp_explicit_dsa)
  4536. << getOpenMPClauseName(OMPC_uniform);
  4537. continue;
  4538. }
  4539. LinearArgs[CanonPVD] = E;
  4540. if (E->isValueDependent() || E->isTypeDependent() ||
  4541. E->isInstantiationDependent() ||
  4542. E->containsUnexpandedParameterPack())
  4543. continue;
  4544. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4545. PVD->getOriginalType());
  4546. continue;
  4547. }
  4548. }
  4549. if (isa<CXXThisExpr>(E)) {
  4550. if (UniformedLinearThis) {
  4551. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4552. << getOpenMPClauseName(OMPC_linear)
  4553. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4554. << E->getSourceRange();
  4555. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4556. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4557. : OMPC_linear);
  4558. continue;
  4559. }
  4560. UniformedLinearThis = E;
  4561. if (E->isValueDependent() || E->isTypeDependent() ||
  4562. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4563. continue;
  4564. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4565. E->getType());
  4566. continue;
  4567. }
  4568. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4569. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4570. }
  4571. Expr *Step = nullptr;
  4572. Expr *NewStep = nullptr;
  4573. SmallVector<Expr *, 4> NewSteps;
  4574. for (Expr *E : Steps) {
  4575. // Skip the same step expression, it was checked already.
  4576. if (Step == E || !E) {
  4577. NewSteps.push_back(E ? NewStep : nullptr);
  4578. continue;
  4579. }
  4580. Step = E;
  4581. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4582. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4583. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4584. if (UniformedArgs.count(CanonPVD) == 0) {
  4585. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4586. << Step->getSourceRange();
  4587. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4588. E->isInstantiationDependent() ||
  4589. E->containsUnexpandedParameterPack() ||
  4590. CanonPVD->getType()->hasIntegerRepresentation()) {
  4591. NewSteps.push_back(Step);
  4592. } else {
  4593. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4594. << Step->getSourceRange();
  4595. }
  4596. continue;
  4597. }
  4598. NewStep = Step;
  4599. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4600. !Step->isInstantiationDependent() &&
  4601. !Step->containsUnexpandedParameterPack()) {
  4602. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4603. .get();
  4604. if (NewStep)
  4605. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4606. }
  4607. NewSteps.push_back(NewStep);
  4608. }
  4609. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4610. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4611. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4612. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4613. const_cast<Expr **>(Linears.data()), Linears.size(),
  4614. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4615. NewSteps.data(), NewSteps.size(), SR);
  4616. ADecl->addAttr(NewAttr);
  4617. return DG;
  4618. }
  4619. Optional<std::pair<FunctionDecl *, Expr *>>
  4620. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  4621. Expr *VariantRef, SourceRange SR) {
  4622. if (!DG || DG.get().isNull())
  4623. return None;
  4624. const int VariantId = 1;
  4625. // Must be applied only to single decl.
  4626. if (!DG.get().isSingleDecl()) {
  4627. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  4628. << VariantId << SR;
  4629. return None;
  4630. }
  4631. Decl *ADecl = DG.get().getSingleDecl();
  4632. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  4633. ADecl = FTD->getTemplatedDecl();
  4634. // Decl must be a function.
  4635. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  4636. if (!FD) {
  4637. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  4638. << VariantId << SR;
  4639. return None;
  4640. }
  4641. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  4642. return FD->hasAttrs() &&
  4643. (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
  4644. FD->hasAttr<TargetAttr>());
  4645. };
  4646. // OpenMP is not compatible with CPU-specific attributes.
  4647. if (HasMultiVersionAttributes(FD)) {
  4648. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  4649. << SR;
  4650. return None;
  4651. }
  4652. // Allow #pragma omp declare variant only if the function is not used.
  4653. if (FD->isUsed(false))
  4654. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  4655. << FD->getLocation();
  4656. // Check if the function was emitted already.
  4657. const FunctionDecl *Definition;
  4658. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  4659. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  4660. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  4661. << FD->getLocation();
  4662. // The VariantRef must point to function.
  4663. if (!VariantRef) {
  4664. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  4665. return None;
  4666. }
  4667. // Do not check templates, wait until instantiation.
  4668. if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
  4669. VariantRef->containsUnexpandedParameterPack() ||
  4670. VariantRef->isInstantiationDependent() || FD->isDependentContext())
  4671. return std::make_pair(FD, VariantRef);
  4672. // Convert VariantRef expression to the type of the original function to
  4673. // resolve possible conflicts.
  4674. ExprResult VariantRefCast;
  4675. if (LangOpts.CPlusPlus) {
  4676. QualType FnPtrType;
  4677. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  4678. if (Method && !Method->isStatic()) {
  4679. const Type *ClassType =
  4680. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  4681. FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
  4682. ExprResult ER;
  4683. {
  4684. // Build adrr_of unary op to correctly handle type checks for member
  4685. // functions.
  4686. Sema::TentativeAnalysisScope Trap(*this);
  4687. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  4688. VariantRef);
  4689. }
  4690. if (!ER.isUsable()) {
  4691. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4692. << VariantId << VariantRef->getSourceRange();
  4693. return None;
  4694. }
  4695. VariantRef = ER.get();
  4696. } else {
  4697. FnPtrType = Context.getPointerType(FD->getType());
  4698. }
  4699. ImplicitConversionSequence ICS =
  4700. TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
  4701. /*SuppressUserConversions=*/false,
  4702. /*AllowExplicit=*/false,
  4703. /*InOverloadResolution=*/false,
  4704. /*CStyle=*/false,
  4705. /*AllowObjCWritebackConversion=*/false);
  4706. if (ICS.isFailure()) {
  4707. Diag(VariantRef->getExprLoc(),
  4708. diag::err_omp_declare_variant_incompat_types)
  4709. << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
  4710. return None;
  4711. }
  4712. VariantRefCast = PerformImplicitConversion(
  4713. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  4714. if (!VariantRefCast.isUsable())
  4715. return None;
  4716. // Drop previously built artificial addr_of unary op for member functions.
  4717. if (Method && !Method->isStatic()) {
  4718. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  4719. if (auto *UO = dyn_cast<UnaryOperator>(
  4720. PossibleAddrOfVariantRef->IgnoreImplicit()))
  4721. VariantRefCast = UO->getSubExpr();
  4722. }
  4723. } else {
  4724. VariantRefCast = VariantRef;
  4725. }
  4726. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  4727. if (!ER.isUsable() ||
  4728. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  4729. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4730. << VariantId << VariantRef->getSourceRange();
  4731. return None;
  4732. }
  4733. // The VariantRef must point to function.
  4734. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  4735. if (!DRE) {
  4736. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4737. << VariantId << VariantRef->getSourceRange();
  4738. return None;
  4739. }
  4740. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  4741. if (!NewFD) {
  4742. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  4743. << VariantId << VariantRef->getSourceRange();
  4744. return None;
  4745. }
  4746. // Check if variant function is not marked with declare variant directive.
  4747. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  4748. Diag(VariantRef->getExprLoc(),
  4749. diag::warn_omp_declare_variant_marked_as_declare_variant)
  4750. << VariantRef->getSourceRange();
  4751. SourceRange SR =
  4752. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  4753. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  4754. return None;
  4755. }
  4756. enum DoesntSupport {
  4757. VirtFuncs = 1,
  4758. Constructors = 3,
  4759. Destructors = 4,
  4760. DeletedFuncs = 5,
  4761. DefaultedFuncs = 6,
  4762. ConstexprFuncs = 7,
  4763. ConstevalFuncs = 8,
  4764. };
  4765. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  4766. if (CXXFD->isVirtual()) {
  4767. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4768. << VirtFuncs;
  4769. return None;
  4770. }
  4771. if (isa<CXXConstructorDecl>(FD)) {
  4772. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4773. << Constructors;
  4774. return None;
  4775. }
  4776. if (isa<CXXDestructorDecl>(FD)) {
  4777. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4778. << Destructors;
  4779. return None;
  4780. }
  4781. }
  4782. if (FD->isDeleted()) {
  4783. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4784. << DeletedFuncs;
  4785. return None;
  4786. }
  4787. if (FD->isDefaulted()) {
  4788. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4789. << DefaultedFuncs;
  4790. return None;
  4791. }
  4792. if (FD->isConstexpr()) {
  4793. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  4794. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  4795. return None;
  4796. }
  4797. // Check general compatibility.
  4798. if (areMultiversionVariantFunctionsCompatible(
  4799. FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
  4800. PartialDiagnosticAt(
  4801. SR.getBegin(),
  4802. PDiag(diag::note_omp_declare_variant_specified_here) << SR),
  4803. PartialDiagnosticAt(
  4804. VariantRef->getExprLoc(),
  4805. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  4806. PartialDiagnosticAt(VariantRef->getExprLoc(),
  4807. PDiag(diag::err_omp_declare_variant_diff)
  4808. << FD->getLocation()),
  4809. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  4810. /*CLinkageMayDiffer=*/true))
  4811. return None;
  4812. return std::make_pair(FD, cast<Expr>(DRE));
  4813. }
  4814. void Sema::ActOnOpenMPDeclareVariantDirective(
  4815. FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
  4816. const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
  4817. if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
  4818. Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
  4819. return;
  4820. Expr *Score = nullptr;
  4821. OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
  4822. if (Data.CtxScore.isUsable()) {
  4823. ST = OMPDeclareVariantAttr::ScoreSpecified;
  4824. Score = Data.CtxScore.get();
  4825. if (!Score->isTypeDependent() && !Score->isValueDependent() &&
  4826. !Score->isInstantiationDependent() &&
  4827. !Score->containsUnexpandedParameterPack()) {
  4828. llvm::APSInt Result;
  4829. ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
  4830. if (ICE.isInvalid())
  4831. return;
  4832. }
  4833. }
  4834. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  4835. Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
  4836. Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
  4837. FD->addAttr(NewAttr);
  4838. }
  4839. void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
  4840. FunctionDecl *Func,
  4841. bool MightBeOdrUse) {
  4842. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  4843. if (!Func->isDependentContext() && Func->hasAttrs()) {
  4844. for (OMPDeclareVariantAttr *A :
  4845. Func->specific_attrs<OMPDeclareVariantAttr>()) {
  4846. // TODO: add checks for active OpenMP context where possible.
  4847. Expr *VariantRef = A->getVariantFuncRef();
  4848. auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
  4849. auto *F = cast<FunctionDecl>(DRE->getDecl());
  4850. if (!F->isDefined() && F->isTemplateInstantiation())
  4851. InstantiateFunctionDefinition(Loc, F->getFirstDecl());
  4852. MarkFunctionReferenced(Loc, F, MightBeOdrUse);
  4853. }
  4854. }
  4855. }
  4856. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4857. Stmt *AStmt,
  4858. SourceLocation StartLoc,
  4859. SourceLocation EndLoc) {
  4860. if (!AStmt)
  4861. return StmtError();
  4862. auto *CS = cast<CapturedStmt>(AStmt);
  4863. // 1.2.2 OpenMP Language Terminology
  4864. // Structured block - An executable statement with a single entry at the
  4865. // top and a single exit at the bottom.
  4866. // The point of exit cannot be a branch out of the structured block.
  4867. // longjmp() and throw() must not violate the entry/exit criteria.
  4868. CS->getCapturedDecl()->setNothrow();
  4869. setFunctionHasBranchProtectedScope();
  4870. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4871. DSAStack->isCancelRegion());
  4872. }
  4873. namespace {
  4874. /// Iteration space of a single for loop.
  4875. struct LoopIterationSpace final {
  4876. /// True if the condition operator is the strict compare operator (<, > or
  4877. /// !=).
  4878. bool IsStrictCompare = false;
  4879. /// Condition of the loop.
  4880. Expr *PreCond = nullptr;
  4881. /// This expression calculates the number of iterations in the loop.
  4882. /// It is always possible to calculate it before starting the loop.
  4883. Expr *NumIterations = nullptr;
  4884. /// The loop counter variable.
  4885. Expr *CounterVar = nullptr;
  4886. /// Private loop counter variable.
  4887. Expr *PrivateCounterVar = nullptr;
  4888. /// This is initializer for the initial value of #CounterVar.
  4889. Expr *CounterInit = nullptr;
  4890. /// This is step for the #CounterVar used to generate its update:
  4891. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4892. Expr *CounterStep = nullptr;
  4893. /// Should step be subtracted?
  4894. bool Subtract = false;
  4895. /// Source range of the loop init.
  4896. SourceRange InitSrcRange;
  4897. /// Source range of the loop condition.
  4898. SourceRange CondSrcRange;
  4899. /// Source range of the loop increment.
  4900. SourceRange IncSrcRange;
  4901. /// Minimum value that can have the loop control variable. Used to support
  4902. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  4903. /// since only such variables can be used in non-loop invariant expressions.
  4904. Expr *MinValue = nullptr;
  4905. /// Maximum value that can have the loop control variable. Used to support
  4906. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  4907. /// since only such variables can be used in non-loop invariant expressions.
  4908. Expr *MaxValue = nullptr;
  4909. /// true, if the lower bound depends on the outer loop control var.
  4910. bool IsNonRectangularLB = false;
  4911. /// true, if the upper bound depends on the outer loop control var.
  4912. bool IsNonRectangularUB = false;
  4913. /// Index of the loop this loop depends on and forms non-rectangular loop
  4914. /// nest.
  4915. unsigned LoopDependentIdx = 0;
  4916. /// Final condition for the non-rectangular loop nest support. It is used to
  4917. /// check that the number of iterations for this particular counter must be
  4918. /// finished.
  4919. Expr *FinalCondition = nullptr;
  4920. };
  4921. /// Helper class for checking canonical form of the OpenMP loops and
  4922. /// extracting iteration space of each loop in the loop nest, that will be used
  4923. /// for IR generation.
  4924. class OpenMPIterationSpaceChecker {
  4925. /// Reference to Sema.
  4926. Sema &SemaRef;
  4927. /// Data-sharing stack.
  4928. DSAStackTy &Stack;
  4929. /// A location for diagnostics (when there is no some better location).
  4930. SourceLocation DefaultLoc;
  4931. /// A location for diagnostics (when increment is not compatible).
  4932. SourceLocation ConditionLoc;
  4933. /// A source location for referring to loop init later.
  4934. SourceRange InitSrcRange;
  4935. /// A source location for referring to condition later.
  4936. SourceRange ConditionSrcRange;
  4937. /// A source location for referring to increment later.
  4938. SourceRange IncrementSrcRange;
  4939. /// Loop variable.
  4940. ValueDecl *LCDecl = nullptr;
  4941. /// Reference to loop variable.
  4942. Expr *LCRef = nullptr;
  4943. /// Lower bound (initializer for the var).
  4944. Expr *LB = nullptr;
  4945. /// Upper bound.
  4946. Expr *UB = nullptr;
  4947. /// Loop step (increment).
  4948. Expr *Step = nullptr;
  4949. /// This flag is true when condition is one of:
  4950. /// Var < UB
  4951. /// Var <= UB
  4952. /// UB > Var
  4953. /// UB >= Var
  4954. /// This will have no value when the condition is !=
  4955. llvm::Optional<bool> TestIsLessOp;
  4956. /// This flag is true when condition is strict ( < or > ).
  4957. bool TestIsStrictOp = false;
  4958. /// This flag is true when step is subtracted on each iteration.
  4959. bool SubtractStep = false;
  4960. /// The outer loop counter this loop depends on (if any).
  4961. const ValueDecl *DepDecl = nullptr;
  4962. /// Contains number of loop (starts from 1) on which loop counter init
  4963. /// expression of this loop depends on.
  4964. Optional<unsigned> InitDependOnLC;
  4965. /// Contains number of loop (starts from 1) on which loop counter condition
  4966. /// expression of this loop depends on.
  4967. Optional<unsigned> CondDependOnLC;
  4968. /// Checks if the provide statement depends on the loop counter.
  4969. Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
  4970. /// Original condition required for checking of the exit condition for
  4971. /// non-rectangular loop.
  4972. Expr *Condition = nullptr;
  4973. public:
  4974. OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
  4975. SourceLocation DefaultLoc)
  4976. : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
  4977. ConditionLoc(DefaultLoc) {}
  4978. /// Check init-expr for canonical loop form and save loop counter
  4979. /// variable - #Var and its initialization value - #LB.
  4980. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4981. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4982. /// for less/greater and for strict/non-strict comparison.
  4983. bool checkAndSetCond(Expr *S);
  4984. /// Check incr-expr for canonical loop form and return true if it
  4985. /// does not conform, otherwise save loop step (#Step).
  4986. bool checkAndSetInc(Expr *S);
  4987. /// Return the loop counter variable.
  4988. ValueDecl *getLoopDecl() const { return LCDecl; }
  4989. /// Return the reference expression to loop counter variable.
  4990. Expr *getLoopDeclRefExpr() const { return LCRef; }
  4991. /// Source range of the loop init.
  4992. SourceRange getInitSrcRange() const { return InitSrcRange; }
  4993. /// Source range of the loop condition.
  4994. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  4995. /// Source range of the loop increment.
  4996. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  4997. /// True if the step should be subtracted.
  4998. bool shouldSubtractStep() const { return SubtractStep; }
  4999. /// True, if the compare operator is strict (<, > or !=).
  5000. bool isStrictTestOp() const { return TestIsStrictOp; }
  5001. /// Build the expression to calculate the number of iterations.
  5002. Expr *buildNumIterations(
  5003. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5004. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5005. /// Build the precondition expression for the loops.
  5006. Expr *
  5007. buildPreCond(Scope *S, Expr *Cond,
  5008. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5009. /// Build reference expression to the counter be used for codegen.
  5010. DeclRefExpr *
  5011. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5012. DSAStackTy &DSA) const;
  5013. /// Build reference expression to the private counter be used for
  5014. /// codegen.
  5015. Expr *buildPrivateCounterVar() const;
  5016. /// Build initialization of the counter be used for codegen.
  5017. Expr *buildCounterInit() const;
  5018. /// Build step of the counter be used for codegen.
  5019. Expr *buildCounterStep() const;
  5020. /// Build loop data with counter value for depend clauses in ordered
  5021. /// directives.
  5022. Expr *
  5023. buildOrderedLoopData(Scope *S, Expr *Counter,
  5024. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5025. SourceLocation Loc, Expr *Inc = nullptr,
  5026. OverloadedOperatorKind OOK = OO_Amp);
  5027. /// Builds the minimum value for the loop counter.
  5028. std::pair<Expr *, Expr *> buildMinMaxValues(
  5029. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  5030. /// Builds final condition for the non-rectangular loops.
  5031. Expr *buildFinalCondition(Scope *S) const;
  5032. /// Return true if any expression is dependent.
  5033. bool dependent() const;
  5034. /// Returns true if the initializer forms non-rectangular loop.
  5035. bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
  5036. /// Returns true if the condition forms non-rectangular loop.
  5037. bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
  5038. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  5039. unsigned getLoopDependentIdx() const {
  5040. return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
  5041. }
  5042. private:
  5043. /// Check the right-hand side of an assignment in the increment
  5044. /// expression.
  5045. bool checkAndSetIncRHS(Expr *RHS);
  5046. /// Helper to set loop counter variable and its initializer.
  5047. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  5048. bool EmitDiags);
  5049. /// Helper to set upper bound.
  5050. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  5051. SourceRange SR, SourceLocation SL);
  5052. /// Helper to set loop increment.
  5053. bool setStep(Expr *NewStep, bool Subtract);
  5054. };
  5055. bool OpenMPIterationSpaceChecker::dependent() const {
  5056. if (!LCDecl) {
  5057. assert(!LB && !UB && !Step);
  5058. return false;
  5059. }
  5060. return LCDecl->getType()->isDependentType() ||
  5061. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  5062. (Step && Step->isValueDependent());
  5063. }
  5064. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  5065. Expr *NewLCRefExpr,
  5066. Expr *NewLB, bool EmitDiags) {
  5067. // State consistency checking to ensure correct usage.
  5068. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  5069. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5070. if (!NewLCDecl || !NewLB)
  5071. return true;
  5072. LCDecl = getCanonicalDecl(NewLCDecl);
  5073. LCRef = NewLCRefExpr;
  5074. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  5075. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5076. if ((Ctor->isCopyOrMoveConstructor() ||
  5077. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5078. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5079. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  5080. LB = NewLB;
  5081. if (EmitDiags)
  5082. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  5083. return false;
  5084. }
  5085. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  5086. llvm::Optional<bool> LessOp,
  5087. bool StrictOp, SourceRange SR,
  5088. SourceLocation SL) {
  5089. // State consistency checking to ensure correct usage.
  5090. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  5091. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  5092. if (!NewUB)
  5093. return true;
  5094. UB = NewUB;
  5095. if (LessOp)
  5096. TestIsLessOp = LessOp;
  5097. TestIsStrictOp = StrictOp;
  5098. ConditionSrcRange = SR;
  5099. ConditionLoc = SL;
  5100. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  5101. return false;
  5102. }
  5103. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  5104. // State consistency checking to ensure correct usage.
  5105. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  5106. if (!NewStep)
  5107. return true;
  5108. if (!NewStep->isValueDependent()) {
  5109. // Check that the step is integer expression.
  5110. SourceLocation StepLoc = NewStep->getBeginLoc();
  5111. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  5112. StepLoc, getExprAsWritten(NewStep));
  5113. if (Val.isInvalid())
  5114. return true;
  5115. NewStep = Val.get();
  5116. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  5117. // If test-expr is of form var relational-op b and relational-op is < or
  5118. // <= then incr-expr must cause var to increase on each iteration of the
  5119. // loop. If test-expr is of form var relational-op b and relational-op is
  5120. // > or >= then incr-expr must cause var to decrease on each iteration of
  5121. // the loop.
  5122. // If test-expr is of form b relational-op var and relational-op is < or
  5123. // <= then incr-expr must cause var to decrease on each iteration of the
  5124. // loop. If test-expr is of form b relational-op var and relational-op is
  5125. // > or >= then incr-expr must cause var to increase on each iteration of
  5126. // the loop.
  5127. llvm::APSInt Result;
  5128. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  5129. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  5130. bool IsConstNeg =
  5131. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  5132. bool IsConstPos =
  5133. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  5134. bool IsConstZero = IsConstant && !Result.getBoolValue();
  5135. // != with increment is treated as <; != with decrement is treated as >
  5136. if (!TestIsLessOp.hasValue())
  5137. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  5138. if (UB && (IsConstZero ||
  5139. (TestIsLessOp.getValue() ?
  5140. (IsConstNeg || (IsUnsigned && Subtract)) :
  5141. (IsConstPos || (IsUnsigned && !Subtract))))) {
  5142. SemaRef.Diag(NewStep->getExprLoc(),
  5143. diag::err_omp_loop_incr_not_compatible)
  5144. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  5145. SemaRef.Diag(ConditionLoc,
  5146. diag::note_omp_loop_cond_requres_compatible_incr)
  5147. << TestIsLessOp.getValue() << ConditionSrcRange;
  5148. return true;
  5149. }
  5150. if (TestIsLessOp.getValue() == Subtract) {
  5151. NewStep =
  5152. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  5153. .get();
  5154. Subtract = !Subtract;
  5155. }
  5156. }
  5157. Step = NewStep;
  5158. SubtractStep = Subtract;
  5159. return false;
  5160. }
  5161. namespace {
  5162. /// Checker for the non-rectangular loops. Checks if the initializer or
  5163. /// condition expression references loop counter variable.
  5164. class LoopCounterRefChecker final
  5165. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  5166. Sema &SemaRef;
  5167. DSAStackTy &Stack;
  5168. const ValueDecl *CurLCDecl = nullptr;
  5169. const ValueDecl *DepDecl = nullptr;
  5170. const ValueDecl *PrevDepDecl = nullptr;
  5171. bool IsInitializer = true;
  5172. unsigned BaseLoopId = 0;
  5173. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  5174. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  5175. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  5176. << (IsInitializer ? 0 : 1);
  5177. return false;
  5178. }
  5179. const auto &&Data = Stack.isLoopControlVariable(VD);
  5180. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  5181. // The type of the loop iterator on which we depend may not have a random
  5182. // access iterator type.
  5183. if (Data.first && VD->getType()->isRecordType()) {
  5184. SmallString<128> Name;
  5185. llvm::raw_svector_ostream OS(Name);
  5186. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5187. /*Qualified=*/true);
  5188. SemaRef.Diag(E->getExprLoc(),
  5189. diag::err_omp_wrong_dependency_iterator_type)
  5190. << OS.str();
  5191. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  5192. return false;
  5193. }
  5194. if (Data.first &&
  5195. (DepDecl || (PrevDepDecl &&
  5196. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  5197. if (!DepDecl && PrevDepDecl)
  5198. DepDecl = PrevDepDecl;
  5199. SmallString<128> Name;
  5200. llvm::raw_svector_ostream OS(Name);
  5201. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  5202. /*Qualified=*/true);
  5203. SemaRef.Diag(E->getExprLoc(),
  5204. diag::err_omp_invariant_or_linear_dependency)
  5205. << OS.str();
  5206. return false;
  5207. }
  5208. if (Data.first) {
  5209. DepDecl = VD;
  5210. BaseLoopId = Data.first;
  5211. }
  5212. return Data.first;
  5213. }
  5214. public:
  5215. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5216. const ValueDecl *VD = E->getDecl();
  5217. if (isa<VarDecl>(VD))
  5218. return checkDecl(E, VD);
  5219. return false;
  5220. }
  5221. bool VisitMemberExpr(const MemberExpr *E) {
  5222. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  5223. const ValueDecl *VD = E->getMemberDecl();
  5224. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  5225. return checkDecl(E, VD);
  5226. }
  5227. return false;
  5228. }
  5229. bool VisitStmt(const Stmt *S) {
  5230. bool Res = false;
  5231. for (const Stmt *Child : S->children())
  5232. Res = (Child && Visit(Child)) || Res;
  5233. return Res;
  5234. }
  5235. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  5236. const ValueDecl *CurLCDecl, bool IsInitializer,
  5237. const ValueDecl *PrevDepDecl = nullptr)
  5238. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  5239. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
  5240. unsigned getBaseLoopId() const {
  5241. assert(CurLCDecl && "Expected loop dependency.");
  5242. return BaseLoopId;
  5243. }
  5244. const ValueDecl *getDepDecl() const {
  5245. assert(CurLCDecl && "Expected loop dependency.");
  5246. return DepDecl;
  5247. }
  5248. };
  5249. } // namespace
  5250. Optional<unsigned>
  5251. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  5252. bool IsInitializer) {
  5253. // Check for the non-rectangular loops.
  5254. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  5255. DepDecl);
  5256. if (LoopStmtChecker.Visit(S)) {
  5257. DepDecl = LoopStmtChecker.getDepDecl();
  5258. return LoopStmtChecker.getBaseLoopId();
  5259. }
  5260. return llvm::None;
  5261. }
  5262. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  5263. // Check init-expr for canonical loop form and save loop counter
  5264. // variable - #Var and its initialization value - #LB.
  5265. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  5266. // var = lb
  5267. // integer-type var = lb
  5268. // random-access-iterator-type var = lb
  5269. // pointer-type var = lb
  5270. //
  5271. if (!S) {
  5272. if (EmitDiags) {
  5273. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  5274. }
  5275. return true;
  5276. }
  5277. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5278. if (!ExprTemp->cleanupsHaveSideEffects())
  5279. S = ExprTemp->getSubExpr();
  5280. InitSrcRange = S->getSourceRange();
  5281. if (Expr *E = dyn_cast<Expr>(S))
  5282. S = E->IgnoreParens();
  5283. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5284. if (BO->getOpcode() == BO_Assign) {
  5285. Expr *LHS = BO->getLHS()->IgnoreParens();
  5286. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5287. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5288. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5289. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5290. EmitDiags);
  5291. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  5292. }
  5293. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5294. if (ME->isArrow() &&
  5295. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5296. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5297. EmitDiags);
  5298. }
  5299. }
  5300. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  5301. if (DS->isSingleDecl()) {
  5302. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  5303. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  5304. // Accept non-canonical init form here but emit ext. warning.
  5305. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  5306. SemaRef.Diag(S->getBeginLoc(),
  5307. diag::ext_omp_loop_not_canonical_init)
  5308. << S->getSourceRange();
  5309. return setLCDeclAndLB(
  5310. Var,
  5311. buildDeclRefExpr(SemaRef, Var,
  5312. Var->getType().getNonReferenceType(),
  5313. DS->getBeginLoc()),
  5314. Var->getInit(), EmitDiags);
  5315. }
  5316. }
  5317. }
  5318. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5319. if (CE->getOperator() == OO_Equal) {
  5320. Expr *LHS = CE->getArg(0);
  5321. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  5322. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  5323. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  5324. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5325. EmitDiags);
  5326. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  5327. }
  5328. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  5329. if (ME->isArrow() &&
  5330. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5331. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  5332. EmitDiags);
  5333. }
  5334. }
  5335. }
  5336. if (dependent() || SemaRef.CurContext->isDependentContext())
  5337. return false;
  5338. if (EmitDiags) {
  5339. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  5340. << S->getSourceRange();
  5341. }
  5342. return true;
  5343. }
  5344. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  5345. /// variable (which may be the loop variable) if possible.
  5346. static const ValueDecl *getInitLCDecl(const Expr *E) {
  5347. if (!E)
  5348. return nullptr;
  5349. E = getExprAsWritten(E);
  5350. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  5351. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  5352. if ((Ctor->isCopyOrMoveConstructor() ||
  5353. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  5354. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  5355. E = CE->getArg(0)->IgnoreParenImpCasts();
  5356. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  5357. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  5358. return getCanonicalDecl(VD);
  5359. }
  5360. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  5361. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  5362. return getCanonicalDecl(ME->getMemberDecl());
  5363. return nullptr;
  5364. }
  5365. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  5366. // Check test-expr for canonical form, save upper-bound UB, flags for
  5367. // less/greater and for strict/non-strict comparison.
  5368. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  5369. // var relational-op b
  5370. // b relational-op var
  5371. //
  5372. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  5373. if (!S) {
  5374. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  5375. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  5376. return true;
  5377. }
  5378. Condition = S;
  5379. S = getExprAsWritten(S);
  5380. SourceLocation CondLoc = S->getBeginLoc();
  5381. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5382. if (BO->isRelationalOp()) {
  5383. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5384. return setUB(BO->getRHS(),
  5385. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  5386. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5387. BO->getSourceRange(), BO->getOperatorLoc());
  5388. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  5389. return setUB(BO->getLHS(),
  5390. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  5391. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  5392. BO->getSourceRange(), BO->getOperatorLoc());
  5393. } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
  5394. return setUB(
  5395. getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
  5396. /*LessOp=*/llvm::None,
  5397. /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
  5398. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5399. if (CE->getNumArgs() == 2) {
  5400. auto Op = CE->getOperator();
  5401. switch (Op) {
  5402. case OO_Greater:
  5403. case OO_GreaterEqual:
  5404. case OO_Less:
  5405. case OO_LessEqual:
  5406. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5407. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  5408. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5409. CE->getOperatorLoc());
  5410. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  5411. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  5412. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  5413. CE->getOperatorLoc());
  5414. break;
  5415. case OO_ExclaimEqual:
  5416. if (IneqCondIsCanonical)
  5417. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
  5418. : CE->getArg(0),
  5419. /*LessOp=*/llvm::None,
  5420. /*StrictOp=*/true, CE->getSourceRange(),
  5421. CE->getOperatorLoc());
  5422. break;
  5423. default:
  5424. break;
  5425. }
  5426. }
  5427. }
  5428. if (dependent() || SemaRef.CurContext->isDependentContext())
  5429. return false;
  5430. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  5431. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  5432. return true;
  5433. }
  5434. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  5435. // RHS of canonical loop form increment can be:
  5436. // var + incr
  5437. // incr + var
  5438. // var - incr
  5439. //
  5440. RHS = RHS->IgnoreParenImpCasts();
  5441. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  5442. if (BO->isAdditiveOp()) {
  5443. bool IsAdd = BO->getOpcode() == BO_Add;
  5444. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5445. return setStep(BO->getRHS(), !IsAdd);
  5446. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  5447. return setStep(BO->getLHS(), /*Subtract=*/false);
  5448. }
  5449. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  5450. bool IsAdd = CE->getOperator() == OO_Plus;
  5451. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  5452. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5453. return setStep(CE->getArg(1), !IsAdd);
  5454. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  5455. return setStep(CE->getArg(0), /*Subtract=*/false);
  5456. }
  5457. }
  5458. if (dependent() || SemaRef.CurContext->isDependentContext())
  5459. return false;
  5460. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5461. << RHS->getSourceRange() << LCDecl;
  5462. return true;
  5463. }
  5464. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  5465. // Check incr-expr for canonical loop form and return true if it
  5466. // does not conform.
  5467. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  5468. // ++var
  5469. // var++
  5470. // --var
  5471. // var--
  5472. // var += incr
  5473. // var -= incr
  5474. // var = var + incr
  5475. // var = incr + var
  5476. // var = var - incr
  5477. //
  5478. if (!S) {
  5479. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  5480. return true;
  5481. }
  5482. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  5483. if (!ExprTemp->cleanupsHaveSideEffects())
  5484. S = ExprTemp->getSubExpr();
  5485. IncrementSrcRange = S->getSourceRange();
  5486. S = S->IgnoreParens();
  5487. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  5488. if (UO->isIncrementDecrementOp() &&
  5489. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  5490. return setStep(SemaRef
  5491. .ActOnIntegerConstant(UO->getBeginLoc(),
  5492. (UO->isDecrementOp() ? -1 : 1))
  5493. .get(),
  5494. /*Subtract=*/false);
  5495. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  5496. switch (BO->getOpcode()) {
  5497. case BO_AddAssign:
  5498. case BO_SubAssign:
  5499. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5500. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  5501. break;
  5502. case BO_Assign:
  5503. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  5504. return checkAndSetIncRHS(BO->getRHS());
  5505. break;
  5506. default:
  5507. break;
  5508. }
  5509. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  5510. switch (CE->getOperator()) {
  5511. case OO_PlusPlus:
  5512. case OO_MinusMinus:
  5513. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5514. return setStep(SemaRef
  5515. .ActOnIntegerConstant(
  5516. CE->getBeginLoc(),
  5517. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  5518. .get(),
  5519. /*Subtract=*/false);
  5520. break;
  5521. case OO_PlusEqual:
  5522. case OO_MinusEqual:
  5523. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5524. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  5525. break;
  5526. case OO_Equal:
  5527. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  5528. return checkAndSetIncRHS(CE->getArg(1));
  5529. break;
  5530. default:
  5531. break;
  5532. }
  5533. }
  5534. if (dependent() || SemaRef.CurContext->isDependentContext())
  5535. return false;
  5536. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  5537. << S->getSourceRange() << LCDecl;
  5538. return true;
  5539. }
  5540. static ExprResult
  5541. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  5542. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5543. if (SemaRef.CurContext->isDependentContext())
  5544. return ExprResult(Capture);
  5545. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  5546. return SemaRef.PerformImplicitConversion(
  5547. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  5548. /*AllowExplicit=*/true);
  5549. auto I = Captures.find(Capture);
  5550. if (I != Captures.end())
  5551. return buildCapture(SemaRef, Capture, I->second);
  5552. DeclRefExpr *Ref = nullptr;
  5553. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  5554. Captures[Capture] = Ref;
  5555. return Res;
  5556. }
  5557. /// Build the expression to calculate the number of iterations.
  5558. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  5559. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  5560. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5561. ExprResult Diff;
  5562. QualType VarType = LCDecl->getType().getNonReferenceType();
  5563. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5564. SemaRef.getLangOpts().CPlusPlus) {
  5565. Expr *LBVal = LB;
  5566. Expr *UBVal = UB;
  5567. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  5568. // max(LB(MinVal), LB(MaxVal))
  5569. if (InitDependOnLC) {
  5570. const LoopIterationSpace &IS =
  5571. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5572. InitDependOnLC.getValueOr(
  5573. CondDependOnLC.getValueOr(0))];
  5574. if (!IS.MinValue || !IS.MaxValue)
  5575. return nullptr;
  5576. // OuterVar = Min
  5577. ExprResult MinValue =
  5578. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5579. if (!MinValue.isUsable())
  5580. return nullptr;
  5581. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5582. IS.CounterVar, MinValue.get());
  5583. if (!LBMinVal.isUsable())
  5584. return nullptr;
  5585. // OuterVar = Min, LBVal
  5586. LBMinVal =
  5587. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  5588. if (!LBMinVal.isUsable())
  5589. return nullptr;
  5590. // (OuterVar = Min, LBVal)
  5591. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  5592. if (!LBMinVal.isUsable())
  5593. return nullptr;
  5594. // OuterVar = Max
  5595. ExprResult MaxValue =
  5596. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5597. if (!MaxValue.isUsable())
  5598. return nullptr;
  5599. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5600. IS.CounterVar, MaxValue.get());
  5601. if (!LBMaxVal.isUsable())
  5602. return nullptr;
  5603. // OuterVar = Max, LBVal
  5604. LBMaxVal =
  5605. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  5606. if (!LBMaxVal.isUsable())
  5607. return nullptr;
  5608. // (OuterVar = Max, LBVal)
  5609. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  5610. if (!LBMaxVal.isUsable())
  5611. return nullptr;
  5612. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  5613. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  5614. if (!LBMin || !LBMax)
  5615. return nullptr;
  5616. // LB(MinVal) < LB(MaxVal)
  5617. ExprResult MinLessMaxRes =
  5618. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  5619. if (!MinLessMaxRes.isUsable())
  5620. return nullptr;
  5621. Expr *MinLessMax =
  5622. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  5623. if (!MinLessMax)
  5624. return nullptr;
  5625. if (TestIsLessOp.getValue()) {
  5626. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  5627. // LB(MaxVal))
  5628. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5629. MinLessMax, LBMin, LBMax);
  5630. if (!MinLB.isUsable())
  5631. return nullptr;
  5632. LBVal = MinLB.get();
  5633. } else {
  5634. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  5635. // LB(MaxVal))
  5636. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  5637. MinLessMax, LBMax, LBMin);
  5638. if (!MaxLB.isUsable())
  5639. return nullptr;
  5640. LBVal = MaxLB.get();
  5641. }
  5642. }
  5643. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  5644. // min(UB(MinVal), UB(MaxVal))
  5645. if (CondDependOnLC) {
  5646. const LoopIterationSpace &IS =
  5647. ResultIterSpaces[ResultIterSpaces.size() - 1 -
  5648. InitDependOnLC.getValueOr(
  5649. CondDependOnLC.getValueOr(0))];
  5650. if (!IS.MinValue || !IS.MaxValue)
  5651. return nullptr;
  5652. // OuterVar = Min
  5653. ExprResult MinValue =
  5654. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  5655. if (!MinValue.isUsable())
  5656. return nullptr;
  5657. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5658. IS.CounterVar, MinValue.get());
  5659. if (!UBMinVal.isUsable())
  5660. return nullptr;
  5661. // OuterVar = Min, UBVal
  5662. UBMinVal =
  5663. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  5664. if (!UBMinVal.isUsable())
  5665. return nullptr;
  5666. // (OuterVar = Min, UBVal)
  5667. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  5668. if (!UBMinVal.isUsable())
  5669. return nullptr;
  5670. // OuterVar = Max
  5671. ExprResult MaxValue =
  5672. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  5673. if (!MaxValue.isUsable())
  5674. return nullptr;
  5675. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  5676. IS.CounterVar, MaxValue.get());
  5677. if (!UBMaxVal.isUsable())
  5678. return nullptr;
  5679. // OuterVar = Max, UBVal
  5680. UBMaxVal =
  5681. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  5682. if (!UBMaxVal.isUsable())
  5683. return nullptr;
  5684. // (OuterVar = Max, UBVal)
  5685. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  5686. if (!UBMaxVal.isUsable())
  5687. return nullptr;
  5688. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  5689. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  5690. if (!UBMin || !UBMax)
  5691. return nullptr;
  5692. // UB(MinVal) > UB(MaxVal)
  5693. ExprResult MinGreaterMaxRes =
  5694. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  5695. if (!MinGreaterMaxRes.isUsable())
  5696. return nullptr;
  5697. Expr *MinGreaterMax =
  5698. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  5699. if (!MinGreaterMax)
  5700. return nullptr;
  5701. if (TestIsLessOp.getValue()) {
  5702. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  5703. // UB(MaxVal))
  5704. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  5705. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  5706. if (!MaxUB.isUsable())
  5707. return nullptr;
  5708. UBVal = MaxUB.get();
  5709. } else {
  5710. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  5711. // UB(MaxVal))
  5712. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  5713. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  5714. if (!MinUB.isUsable())
  5715. return nullptr;
  5716. UBVal = MinUB.get();
  5717. }
  5718. }
  5719. // Upper - Lower
  5720. Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
  5721. Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
  5722. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5723. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5724. if (!Upper || !Lower)
  5725. return nullptr;
  5726. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5727. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  5728. // BuildBinOp already emitted error, this one is to point user to upper
  5729. // and lower bound, and to tell what is passed to 'operator-'.
  5730. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  5731. << Upper->getSourceRange() << Lower->getSourceRange();
  5732. return nullptr;
  5733. }
  5734. }
  5735. if (!Diff.isUsable())
  5736. return nullptr;
  5737. // Upper - Lower [- 1]
  5738. if (TestIsStrictOp)
  5739. Diff = SemaRef.BuildBinOp(
  5740. S, DefaultLoc, BO_Sub, Diff.get(),
  5741. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5742. if (!Diff.isUsable())
  5743. return nullptr;
  5744. // Upper - Lower [- 1] + Step
  5745. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5746. if (!NewStep.isUsable())
  5747. return nullptr;
  5748. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  5749. if (!Diff.isUsable())
  5750. return nullptr;
  5751. // Parentheses (for dumping/debugging purposes only).
  5752. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5753. if (!Diff.isUsable())
  5754. return nullptr;
  5755. // (Upper - Lower [- 1] + Step) / Step
  5756. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5757. if (!Diff.isUsable())
  5758. return nullptr;
  5759. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  5760. QualType Type = Diff.get()->getType();
  5761. ASTContext &C = SemaRef.Context;
  5762. bool UseVarType = VarType->hasIntegerRepresentation() &&
  5763. C.getTypeSize(Type) > C.getTypeSize(VarType);
  5764. if (!Type->isIntegerType() || UseVarType) {
  5765. unsigned NewSize =
  5766. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  5767. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  5768. : Type->hasSignedIntegerRepresentation();
  5769. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  5770. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  5771. Diff = SemaRef.PerformImplicitConversion(
  5772. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  5773. if (!Diff.isUsable())
  5774. return nullptr;
  5775. }
  5776. }
  5777. if (LimitedType) {
  5778. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  5779. if (NewSize != C.getTypeSize(Type)) {
  5780. if (NewSize < C.getTypeSize(Type)) {
  5781. assert(NewSize == 64 && "incorrect loop var size");
  5782. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  5783. << InitSrcRange << ConditionSrcRange;
  5784. }
  5785. QualType NewType = C.getIntTypeForBitwidth(
  5786. NewSize, Type->hasSignedIntegerRepresentation() ||
  5787. C.getTypeSize(Type) < NewSize);
  5788. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  5789. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  5790. Sema::AA_Converting, true);
  5791. if (!Diff.isUsable())
  5792. return nullptr;
  5793. }
  5794. }
  5795. }
  5796. return Diff.get();
  5797. }
  5798. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  5799. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5800. // Do not build for iterators, they cannot be used in non-rectangular loop
  5801. // nests.
  5802. if (LCDecl->getType()->isRecordType())
  5803. return std::make_pair(nullptr, nullptr);
  5804. // If we subtract, the min is in the condition, otherwise the min is in the
  5805. // init value.
  5806. Expr *MinExpr = nullptr;
  5807. Expr *MaxExpr = nullptr;
  5808. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  5809. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  5810. bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
  5811. : CondDependOnLC.hasValue();
  5812. bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
  5813. : InitDependOnLC.hasValue();
  5814. Expr *Lower =
  5815. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  5816. Expr *Upper =
  5817. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  5818. if (!Upper || !Lower)
  5819. return std::make_pair(nullptr, nullptr);
  5820. if (TestIsLessOp.getValue())
  5821. MinExpr = Lower;
  5822. else
  5823. MaxExpr = Upper;
  5824. // Build minimum/maximum value based on number of iterations.
  5825. ExprResult Diff;
  5826. QualType VarType = LCDecl->getType().getNonReferenceType();
  5827. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  5828. if (!Diff.isUsable())
  5829. return std::make_pair(nullptr, nullptr);
  5830. // Upper - Lower [- 1]
  5831. if (TestIsStrictOp)
  5832. Diff = SemaRef.BuildBinOp(
  5833. S, DefaultLoc, BO_Sub, Diff.get(),
  5834. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5835. if (!Diff.isUsable())
  5836. return std::make_pair(nullptr, nullptr);
  5837. // Upper - Lower [- 1] + Step
  5838. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  5839. if (!NewStep.isUsable())
  5840. return std::make_pair(nullptr, nullptr);
  5841. // Parentheses (for dumping/debugging purposes only).
  5842. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5843. if (!Diff.isUsable())
  5844. return std::make_pair(nullptr, nullptr);
  5845. // (Upper - Lower [- 1]) / Step
  5846. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  5847. if (!Diff.isUsable())
  5848. return std::make_pair(nullptr, nullptr);
  5849. // ((Upper - Lower [- 1]) / Step) * Step
  5850. // Parentheses (for dumping/debugging purposes only).
  5851. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5852. if (!Diff.isUsable())
  5853. return std::make_pair(nullptr, nullptr);
  5854. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  5855. if (!Diff.isUsable())
  5856. return std::make_pair(nullptr, nullptr);
  5857. // Convert to the original type or ptrdiff_t, if original type is pointer.
  5858. if (!VarType->isAnyPointerType() &&
  5859. !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
  5860. Diff = SemaRef.PerformImplicitConversion(
  5861. Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
  5862. } else if (VarType->isAnyPointerType() &&
  5863. !SemaRef.Context.hasSameType(
  5864. Diff.get()->getType(),
  5865. SemaRef.Context.getUnsignedPointerDiffType())) {
  5866. Diff = SemaRef.PerformImplicitConversion(
  5867. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  5868. Sema::AA_Converting, /*AllowExplicit=*/true);
  5869. }
  5870. if (!Diff.isUsable())
  5871. return std::make_pair(nullptr, nullptr);
  5872. // Parentheses (for dumping/debugging purposes only).
  5873. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  5874. if (!Diff.isUsable())
  5875. return std::make_pair(nullptr, nullptr);
  5876. if (TestIsLessOp.getValue()) {
  5877. // MinExpr = Lower;
  5878. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  5879. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
  5880. if (!Diff.isUsable())
  5881. return std::make_pair(nullptr, nullptr);
  5882. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5883. if (!Diff.isUsable())
  5884. return std::make_pair(nullptr, nullptr);
  5885. MaxExpr = Diff.get();
  5886. } else {
  5887. // MaxExpr = Upper;
  5888. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  5889. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  5890. if (!Diff.isUsable())
  5891. return std::make_pair(nullptr, nullptr);
  5892. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
  5893. if (!Diff.isUsable())
  5894. return std::make_pair(nullptr, nullptr);
  5895. MinExpr = Diff.get();
  5896. }
  5897. return std::make_pair(MinExpr, MaxExpr);
  5898. }
  5899. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  5900. if (InitDependOnLC || CondDependOnLC)
  5901. return Condition;
  5902. return nullptr;
  5903. }
  5904. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  5905. Scope *S, Expr *Cond,
  5906. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  5907. // Do not build a precondition when the condition/initialization is dependent
  5908. // to prevent pessimistic early loop exit.
  5909. // TODO: this can be improved by calculating min/max values but not sure that
  5910. // it will be very effective.
  5911. if (CondDependOnLC || InitDependOnLC)
  5912. return SemaRef.PerformImplicitConversion(
  5913. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  5914. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5915. /*AllowExplicit=*/true).get();
  5916. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  5917. Sema::TentativeAnalysisScope Trap(SemaRef);
  5918. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  5919. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  5920. if (!NewLB.isUsable() || !NewUB.isUsable())
  5921. return nullptr;
  5922. ExprResult CondExpr =
  5923. SemaRef.BuildBinOp(S, DefaultLoc,
  5924. TestIsLessOp.getValue() ?
  5925. (TestIsStrictOp ? BO_LT : BO_LE) :
  5926. (TestIsStrictOp ? BO_GT : BO_GE),
  5927. NewLB.get(), NewUB.get());
  5928. if (CondExpr.isUsable()) {
  5929. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  5930. SemaRef.Context.BoolTy))
  5931. CondExpr = SemaRef.PerformImplicitConversion(
  5932. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  5933. /*AllowExplicit=*/true);
  5934. }
  5935. // Otherwise use original loop condition and evaluate it in runtime.
  5936. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  5937. }
  5938. /// Build reference expression to the counter be used for codegen.
  5939. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  5940. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  5941. DSAStackTy &DSA) const {
  5942. auto *VD = dyn_cast<VarDecl>(LCDecl);
  5943. if (!VD) {
  5944. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  5945. DeclRefExpr *Ref = buildDeclRefExpr(
  5946. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  5947. const DSAStackTy::DSAVarData Data =
  5948. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  5949. // If the loop control decl is explicitly marked as private, do not mark it
  5950. // as captured again.
  5951. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  5952. Captures.insert(std::make_pair(LCRef, Ref));
  5953. return Ref;
  5954. }
  5955. return cast<DeclRefExpr>(LCRef);
  5956. }
  5957. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  5958. if (LCDecl && !LCDecl->isInvalidDecl()) {
  5959. QualType Type = LCDecl->getType().getNonReferenceType();
  5960. VarDecl *PrivateVar = buildVarDecl(
  5961. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  5962. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  5963. isa<VarDecl>(LCDecl)
  5964. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  5965. : nullptr);
  5966. if (PrivateVar->isInvalidDecl())
  5967. return nullptr;
  5968. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  5969. }
  5970. return nullptr;
  5971. }
  5972. /// Build initialization of the counter to be used for codegen.
  5973. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  5974. /// Build step of the counter be used for codegen.
  5975. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  5976. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  5977. Scope *S, Expr *Counter,
  5978. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  5979. Expr *Inc, OverloadedOperatorKind OOK) {
  5980. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  5981. if (!Cnt)
  5982. return nullptr;
  5983. if (Inc) {
  5984. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  5985. "Expected only + or - operations for depend clauses.");
  5986. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  5987. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  5988. if (!Cnt)
  5989. return nullptr;
  5990. }
  5991. ExprResult Diff;
  5992. QualType VarType = LCDecl->getType().getNonReferenceType();
  5993. if (VarType->isIntegerType() || VarType->isPointerType() ||
  5994. SemaRef.getLangOpts().CPlusPlus) {
  5995. // Upper - Lower
  5996. Expr *Upper = TestIsLessOp.getValue()
  5997. ? Cnt
  5998. : tryBuildCapture(SemaRef, UB, Captures).get();
  5999. Expr *Lower = TestIsLessOp.getValue()
  6000. ? tryBuildCapture(SemaRef, LB, Captures).get()
  6001. : Cnt;
  6002. if (!Upper || !Lower)
  6003. return nullptr;
  6004. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  6005. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  6006. // BuildBinOp already emitted error, this one is to point user to upper
  6007. // and lower bound, and to tell what is passed to 'operator-'.
  6008. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  6009. << Upper->getSourceRange() << Lower->getSourceRange();
  6010. return nullptr;
  6011. }
  6012. }
  6013. if (!Diff.isUsable())
  6014. return nullptr;
  6015. // Parentheses (for dumping/debugging purposes only).
  6016. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  6017. if (!Diff.isUsable())
  6018. return nullptr;
  6019. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  6020. if (!NewStep.isUsable())
  6021. return nullptr;
  6022. // (Upper - Lower) / Step
  6023. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  6024. if (!Diff.isUsable())
  6025. return nullptr;
  6026. return Diff.get();
  6027. }
  6028. } // namespace
  6029. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  6030. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  6031. assert(Init && "Expected loop in canonical form.");
  6032. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  6033. if (AssociatedLoops > 0 &&
  6034. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  6035. DSAStack->loopStart();
  6036. OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
  6037. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  6038. if (ValueDecl *D = ISC.getLoopDecl()) {
  6039. auto *VD = dyn_cast<VarDecl>(D);
  6040. DeclRefExpr *PrivateRef = nullptr;
  6041. if (!VD) {
  6042. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  6043. VD = Private;
  6044. } else {
  6045. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  6046. /*WithInit=*/false);
  6047. VD = cast<VarDecl>(PrivateRef->getDecl());
  6048. }
  6049. }
  6050. DSAStack->addLoopControlVariable(D, VD);
  6051. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  6052. if (LD != D->getCanonicalDecl()) {
  6053. DSAStack->resetPossibleLoopCounter();
  6054. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  6055. MarkDeclarationsReferencedInExpr(
  6056. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  6057. Var->getType().getNonLValueExprType(Context),
  6058. ForLoc, /*RefersToCapture=*/true));
  6059. }
  6060. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  6061. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  6062. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  6063. // associated for-loop of a simd construct with just one associated
  6064. // for-loop may be listed in a linear clause with a constant-linear-step
  6065. // that is the increment of the associated for-loop. The loop iteration
  6066. // variable(s) in the associated for-loop(s) of a for or parallel for
  6067. // construct may be listed in a private or lastprivate clause.
  6068. DSAStackTy::DSAVarData DVar =
  6069. DSAStack->getTopDSA(D, /*FromParent=*/false);
  6070. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  6071. // is declared in the loop and it is predetermined as a private.
  6072. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  6073. OpenMPClauseKind PredeterminedCKind =
  6074. isOpenMPSimdDirective(DKind)
  6075. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  6076. : OMPC_private;
  6077. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6078. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  6079. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  6080. DVar.CKind != OMPC_private))) ||
  6081. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  6082. DKind == OMPD_master_taskloop ||
  6083. isOpenMPDistributeDirective(DKind)) &&
  6084. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  6085. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  6086. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  6087. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  6088. << getOpenMPClauseName(DVar.CKind)
  6089. << getOpenMPDirectiveName(DKind)
  6090. << getOpenMPClauseName(PredeterminedCKind);
  6091. if (DVar.RefExpr == nullptr)
  6092. DVar.CKind = PredeterminedCKind;
  6093. reportOriginalDsa(*this, DSAStack, D, DVar,
  6094. /*IsLoopIterVar=*/true);
  6095. } else if (LoopDeclRefExpr) {
  6096. // Make the loop iteration variable private (for worksharing
  6097. // constructs), linear (for simd directives with the only one
  6098. // associated loop) or lastprivate (for simd directives with several
  6099. // collapsed or ordered loops).
  6100. if (DVar.CKind == OMPC_unknown)
  6101. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  6102. PrivateRef);
  6103. }
  6104. }
  6105. }
  6106. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  6107. }
  6108. }
  6109. /// Called on a for stmt to check and extract its iteration space
  6110. /// for further processing (such as collapsing).
  6111. static bool checkOpenMPIterationSpace(
  6112. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  6113. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  6114. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  6115. Expr *OrderedLoopCountExpr,
  6116. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6117. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  6118. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6119. // OpenMP [2.9.1, Canonical Loop Form]
  6120. // for (init-expr; test-expr; incr-expr) structured-block
  6121. // for (range-decl: range-expr) structured-block
  6122. auto *For = dyn_cast_or_null<ForStmt>(S);
  6123. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  6124. // Ranged for is supported only in OpenMP 5.0.
  6125. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  6126. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  6127. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  6128. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  6129. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  6130. if (TotalNestedLoopCount > 1) {
  6131. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  6132. SemaRef.Diag(DSA.getConstructLoc(),
  6133. diag::note_omp_collapse_ordered_expr)
  6134. << 2 << CollapseLoopCountExpr->getSourceRange()
  6135. << OrderedLoopCountExpr->getSourceRange();
  6136. else if (CollapseLoopCountExpr)
  6137. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6138. diag::note_omp_collapse_ordered_expr)
  6139. << 0 << CollapseLoopCountExpr->getSourceRange();
  6140. else
  6141. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6142. diag::note_omp_collapse_ordered_expr)
  6143. << 1 << OrderedLoopCountExpr->getSourceRange();
  6144. }
  6145. return true;
  6146. }
  6147. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  6148. "No loop body.");
  6149. OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
  6150. For ? For->getForLoc() : CXXFor->getForLoc());
  6151. // Check init.
  6152. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  6153. if (ISC.checkAndSetInit(Init))
  6154. return true;
  6155. bool HasErrors = false;
  6156. // Check loop variable's type.
  6157. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  6158. // OpenMP [2.6, Canonical Loop Form]
  6159. // Var is one of the following:
  6160. // A variable of signed or unsigned integer type.
  6161. // For C++, a variable of a random access iterator type.
  6162. // For C, a variable of a pointer type.
  6163. QualType VarType = LCDecl->getType().getNonReferenceType();
  6164. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  6165. !VarType->isPointerType() &&
  6166. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  6167. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  6168. << SemaRef.getLangOpts().CPlusPlus;
  6169. HasErrors = true;
  6170. }
  6171. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  6172. // a Construct
  6173. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  6174. // parallel for construct is (are) private.
  6175. // The loop iteration variable in the associated for-loop of a simd
  6176. // construct with just one associated for-loop is linear with a
  6177. // constant-linear-step that is the increment of the associated for-loop.
  6178. // Exclude loop var from the list of variables with implicitly defined data
  6179. // sharing attributes.
  6180. VarsWithImplicitDSA.erase(LCDecl);
  6181. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  6182. // Check test-expr.
  6183. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  6184. // Check incr-expr.
  6185. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  6186. }
  6187. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  6188. return HasErrors;
  6189. // Build the loop's iteration space representation.
  6190. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  6191. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  6192. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  6193. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  6194. (isOpenMPWorksharingDirective(DKind) ||
  6195. isOpenMPTaskLoopDirective(DKind) ||
  6196. isOpenMPDistributeDirective(DKind)),
  6197. Captures);
  6198. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  6199. ISC.buildCounterVar(Captures, DSA);
  6200. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  6201. ISC.buildPrivateCounterVar();
  6202. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  6203. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  6204. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  6205. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  6206. ISC.getConditionSrcRange();
  6207. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  6208. ISC.getIncrementSrcRange();
  6209. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  6210. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  6211. ISC.isStrictTestOp();
  6212. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  6213. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  6214. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  6215. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  6216. ISC.buildFinalCondition(DSA.getCurScope());
  6217. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  6218. ISC.doesInitDependOnLC();
  6219. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  6220. ISC.doesCondDependOnLC();
  6221. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  6222. ISC.getLoopDependentIdx();
  6223. HasErrors |=
  6224. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  6225. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  6226. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  6227. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  6228. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  6229. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  6230. if (!HasErrors && DSA.isOrderedRegion()) {
  6231. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  6232. if (CurrentNestedLoopCount <
  6233. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  6234. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  6235. CurrentNestedLoopCount,
  6236. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  6237. DSA.getOrderedRegionParam().second->setLoopCounter(
  6238. CurrentNestedLoopCount,
  6239. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  6240. }
  6241. }
  6242. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  6243. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  6244. // Erroneous case - clause has some problems.
  6245. continue;
  6246. }
  6247. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  6248. Pair.second.size() <= CurrentNestedLoopCount) {
  6249. // Erroneous case - clause has some problems.
  6250. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  6251. continue;
  6252. }
  6253. Expr *CntValue;
  6254. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  6255. CntValue = ISC.buildOrderedLoopData(
  6256. DSA.getCurScope(),
  6257. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6258. Pair.first->getDependencyLoc());
  6259. else
  6260. CntValue = ISC.buildOrderedLoopData(
  6261. DSA.getCurScope(),
  6262. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  6263. Pair.first->getDependencyLoc(),
  6264. Pair.second[CurrentNestedLoopCount].first,
  6265. Pair.second[CurrentNestedLoopCount].second);
  6266. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  6267. }
  6268. }
  6269. return HasErrors;
  6270. }
  6271. /// Build 'VarRef = Start.
  6272. static ExprResult
  6273. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6274. ExprResult Start, bool IsNonRectangularLB,
  6275. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6276. // Build 'VarRef = Start.
  6277. ExprResult NewStart = IsNonRectangularLB
  6278. ? Start.get()
  6279. : tryBuildCapture(SemaRef, Start.get(), Captures);
  6280. if (!NewStart.isUsable())
  6281. return ExprError();
  6282. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  6283. VarRef.get()->getType())) {
  6284. NewStart = SemaRef.PerformImplicitConversion(
  6285. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  6286. /*AllowExplicit=*/true);
  6287. if (!NewStart.isUsable())
  6288. return ExprError();
  6289. }
  6290. ExprResult Init =
  6291. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6292. return Init;
  6293. }
  6294. /// Build 'VarRef = Start + Iter * Step'.
  6295. static ExprResult buildCounterUpdate(
  6296. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  6297. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  6298. bool IsNonRectangularLB,
  6299. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  6300. // Add parentheses (for debugging purposes only).
  6301. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  6302. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  6303. !Step.isUsable())
  6304. return ExprError();
  6305. ExprResult NewStep = Step;
  6306. if (Captures)
  6307. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  6308. if (NewStep.isInvalid())
  6309. return ExprError();
  6310. ExprResult Update =
  6311. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  6312. if (!Update.isUsable())
  6313. return ExprError();
  6314. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  6315. // 'VarRef = Start (+|-) Iter * Step'.
  6316. if (!Start.isUsable())
  6317. return ExprError();
  6318. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  6319. if (!NewStart.isUsable())
  6320. return ExprError();
  6321. if (Captures && !IsNonRectangularLB)
  6322. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  6323. if (NewStart.isInvalid())
  6324. return ExprError();
  6325. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  6326. ExprResult SavedUpdate = Update;
  6327. ExprResult UpdateVal;
  6328. if (VarRef.get()->getType()->isOverloadableType() ||
  6329. NewStart.get()->getType()->isOverloadableType() ||
  6330. Update.get()->getType()->isOverloadableType()) {
  6331. Sema::TentativeAnalysisScope Trap(SemaRef);
  6332. Update =
  6333. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  6334. if (Update.isUsable()) {
  6335. UpdateVal =
  6336. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  6337. VarRef.get(), SavedUpdate.get());
  6338. if (UpdateVal.isUsable()) {
  6339. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  6340. UpdateVal.get());
  6341. }
  6342. }
  6343. }
  6344. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  6345. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  6346. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  6347. NewStart.get(), SavedUpdate.get());
  6348. if (!Update.isUsable())
  6349. return ExprError();
  6350. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  6351. VarRef.get()->getType())) {
  6352. Update = SemaRef.PerformImplicitConversion(
  6353. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  6354. if (!Update.isUsable())
  6355. return ExprError();
  6356. }
  6357. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  6358. }
  6359. return Update;
  6360. }
  6361. /// Convert integer expression \a E to make it have at least \a Bits
  6362. /// bits.
  6363. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  6364. if (E == nullptr)
  6365. return ExprError();
  6366. ASTContext &C = SemaRef.Context;
  6367. QualType OldType = E->getType();
  6368. unsigned HasBits = C.getTypeSize(OldType);
  6369. if (HasBits >= Bits)
  6370. return ExprResult(E);
  6371. // OK to convert to signed, because new type has more bits than old.
  6372. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  6373. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  6374. true);
  6375. }
  6376. /// Check if the given expression \a E is a constant integer that fits
  6377. /// into \a Bits bits.
  6378. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  6379. if (E == nullptr)
  6380. return false;
  6381. llvm::APSInt Result;
  6382. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  6383. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  6384. return false;
  6385. }
  6386. /// Build preinits statement for the given declarations.
  6387. static Stmt *buildPreInits(ASTContext &Context,
  6388. MutableArrayRef<Decl *> PreInits) {
  6389. if (!PreInits.empty()) {
  6390. return new (Context) DeclStmt(
  6391. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  6392. SourceLocation(), SourceLocation());
  6393. }
  6394. return nullptr;
  6395. }
  6396. /// Build preinits statement for the given declarations.
  6397. static Stmt *
  6398. buildPreInits(ASTContext &Context,
  6399. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  6400. if (!Captures.empty()) {
  6401. SmallVector<Decl *, 16> PreInits;
  6402. for (const auto &Pair : Captures)
  6403. PreInits.push_back(Pair.second->getDecl());
  6404. return buildPreInits(Context, PreInits);
  6405. }
  6406. return nullptr;
  6407. }
  6408. /// Build postupdate expression for the given list of postupdates expressions.
  6409. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  6410. Expr *PostUpdate = nullptr;
  6411. if (!PostUpdates.empty()) {
  6412. for (Expr *E : PostUpdates) {
  6413. Expr *ConvE = S.BuildCStyleCastExpr(
  6414. E->getExprLoc(),
  6415. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  6416. E->getExprLoc(), E)
  6417. .get();
  6418. PostUpdate = PostUpdate
  6419. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  6420. PostUpdate, ConvE)
  6421. .get()
  6422. : ConvE;
  6423. }
  6424. }
  6425. return PostUpdate;
  6426. }
  6427. /// Called on a for stmt to check itself and nested loops (if any).
  6428. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  6429. /// number of collapsed loops otherwise.
  6430. static unsigned
  6431. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  6432. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  6433. DSAStackTy &DSA,
  6434. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  6435. OMPLoopDirective::HelperExprs &Built) {
  6436. unsigned NestedLoopCount = 1;
  6437. if (CollapseLoopCountExpr) {
  6438. // Found 'collapse' clause - calculate collapse number.
  6439. Expr::EvalResult Result;
  6440. if (!CollapseLoopCountExpr->isValueDependent() &&
  6441. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  6442. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  6443. } else {
  6444. Built.clear(/*Size=*/1);
  6445. return 1;
  6446. }
  6447. }
  6448. unsigned OrderedLoopCount = 1;
  6449. if (OrderedLoopCountExpr) {
  6450. // Found 'ordered' clause - calculate collapse number.
  6451. Expr::EvalResult EVResult;
  6452. if (!OrderedLoopCountExpr->isValueDependent() &&
  6453. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  6454. SemaRef.getASTContext())) {
  6455. llvm::APSInt Result = EVResult.Val.getInt();
  6456. if (Result.getLimitedValue() < NestedLoopCount) {
  6457. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  6458. diag::err_omp_wrong_ordered_loop_count)
  6459. << OrderedLoopCountExpr->getSourceRange();
  6460. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  6461. diag::note_collapse_loop_count)
  6462. << CollapseLoopCountExpr->getSourceRange();
  6463. }
  6464. OrderedLoopCount = Result.getLimitedValue();
  6465. } else {
  6466. Built.clear(/*Size=*/1);
  6467. return 1;
  6468. }
  6469. }
  6470. // This is helper routine for loop directives (e.g., 'for', 'simd',
  6471. // 'for simd', etc.).
  6472. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  6473. SmallVector<LoopIterationSpace, 4> IterSpaces(
  6474. std::max(OrderedLoopCount, NestedLoopCount));
  6475. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  6476. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6477. if (checkOpenMPIterationSpace(
  6478. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6479. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6480. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6481. return 0;
  6482. // Move on to the next nested for loop, or to the loop body.
  6483. // OpenMP [2.8.1, simd construct, Restrictions]
  6484. // All loops associated with the construct must be perfectly nested; that
  6485. // is, there must be no intervening code nor any OpenMP directive between
  6486. // any two loops.
  6487. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6488. CurStmt = For->getBody();
  6489. } else {
  6490. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6491. "Expected canonical for or range-based for loops.");
  6492. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6493. }
  6494. CurStmt = CurStmt->IgnoreContainers();
  6495. }
  6496. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  6497. if (checkOpenMPIterationSpace(
  6498. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  6499. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  6500. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
  6501. return 0;
  6502. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  6503. // Handle initialization of captured loop iterator variables.
  6504. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  6505. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  6506. Captures[DRE] = DRE;
  6507. }
  6508. }
  6509. // Move on to the next nested for loop, or to the loop body.
  6510. // OpenMP [2.8.1, simd construct, Restrictions]
  6511. // All loops associated with the construct must be perfectly nested; that
  6512. // is, there must be no intervening code nor any OpenMP directive between
  6513. // any two loops.
  6514. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  6515. CurStmt = For->getBody();
  6516. } else {
  6517. assert(isa<CXXForRangeStmt>(CurStmt) &&
  6518. "Expected canonical for or range-based for loops.");
  6519. CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
  6520. }
  6521. CurStmt = CurStmt->IgnoreContainers();
  6522. }
  6523. Built.clear(/* size */ NestedLoopCount);
  6524. if (SemaRef.CurContext->isDependentContext())
  6525. return NestedLoopCount;
  6526. // An example of what is generated for the following code:
  6527. //
  6528. // #pragma omp simd collapse(2) ordered(2)
  6529. // for (i = 0; i < NI; ++i)
  6530. // for (k = 0; k < NK; ++k)
  6531. // for (j = J0; j < NJ; j+=2) {
  6532. // <loop body>
  6533. // }
  6534. //
  6535. // We generate the code below.
  6536. // Note: the loop body may be outlined in CodeGen.
  6537. // Note: some counters may be C++ classes, operator- is used to find number of
  6538. // iterations and operator+= to calculate counter value.
  6539. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  6540. // or i64 is currently supported).
  6541. //
  6542. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  6543. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  6544. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  6545. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  6546. // // similar updates for vars in clauses (e.g. 'linear')
  6547. // <loop body (using local i and j)>
  6548. // }
  6549. // i = NI; // assign final values of counters
  6550. // j = NJ;
  6551. //
  6552. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  6553. // the iteration counts of the collapsed for loops.
  6554. // Precondition tests if there is at least one iteration (all conditions are
  6555. // true).
  6556. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  6557. Expr *N0 = IterSpaces[0].NumIterations;
  6558. ExprResult LastIteration32 =
  6559. widenIterationCount(/*Bits=*/32,
  6560. SemaRef
  6561. .PerformImplicitConversion(
  6562. N0->IgnoreImpCasts(), N0->getType(),
  6563. Sema::AA_Converting, /*AllowExplicit=*/true)
  6564. .get(),
  6565. SemaRef);
  6566. ExprResult LastIteration64 = widenIterationCount(
  6567. /*Bits=*/64,
  6568. SemaRef
  6569. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  6570. Sema::AA_Converting,
  6571. /*AllowExplicit=*/true)
  6572. .get(),
  6573. SemaRef);
  6574. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  6575. return NestedLoopCount;
  6576. ASTContext &C = SemaRef.Context;
  6577. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  6578. Scope *CurScope = DSA.getCurScope();
  6579. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  6580. if (PreCond.isUsable()) {
  6581. PreCond =
  6582. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  6583. PreCond.get(), IterSpaces[Cnt].PreCond);
  6584. }
  6585. Expr *N = IterSpaces[Cnt].NumIterations;
  6586. SourceLocation Loc = N->getExprLoc();
  6587. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  6588. if (LastIteration32.isUsable())
  6589. LastIteration32 = SemaRef.BuildBinOp(
  6590. CurScope, Loc, BO_Mul, LastIteration32.get(),
  6591. SemaRef
  6592. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6593. Sema::AA_Converting,
  6594. /*AllowExplicit=*/true)
  6595. .get());
  6596. if (LastIteration64.isUsable())
  6597. LastIteration64 = SemaRef.BuildBinOp(
  6598. CurScope, Loc, BO_Mul, LastIteration64.get(),
  6599. SemaRef
  6600. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  6601. Sema::AA_Converting,
  6602. /*AllowExplicit=*/true)
  6603. .get());
  6604. }
  6605. // Choose either the 32-bit or 64-bit version.
  6606. ExprResult LastIteration = LastIteration64;
  6607. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  6608. (LastIteration32.isUsable() &&
  6609. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  6610. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  6611. fitsInto(
  6612. /*Bits=*/32,
  6613. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  6614. LastIteration64.get(), SemaRef))))
  6615. LastIteration = LastIteration32;
  6616. QualType VType = LastIteration.get()->getType();
  6617. QualType RealVType = VType;
  6618. QualType StrideVType = VType;
  6619. if (isOpenMPTaskLoopDirective(DKind)) {
  6620. VType =
  6621. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  6622. StrideVType =
  6623. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  6624. }
  6625. if (!LastIteration.isUsable())
  6626. return 0;
  6627. // Save the number of iterations.
  6628. ExprResult NumIterations = LastIteration;
  6629. {
  6630. LastIteration = SemaRef.BuildBinOp(
  6631. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  6632. LastIteration.get(),
  6633. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6634. if (!LastIteration.isUsable())
  6635. return 0;
  6636. }
  6637. // Calculate the last iteration number beforehand instead of doing this on
  6638. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  6639. llvm::APSInt Result;
  6640. bool IsConstant =
  6641. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  6642. ExprResult CalcLastIteration;
  6643. if (!IsConstant) {
  6644. ExprResult SaveRef =
  6645. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  6646. LastIteration = SaveRef;
  6647. // Prepare SaveRef + 1.
  6648. NumIterations = SemaRef.BuildBinOp(
  6649. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  6650. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  6651. if (!NumIterations.isUsable())
  6652. return 0;
  6653. }
  6654. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  6655. // Build variables passed into runtime, necessary for worksharing directives.
  6656. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  6657. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6658. isOpenMPDistributeDirective(DKind)) {
  6659. // Lower bound variable, initialized with zero.
  6660. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  6661. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  6662. SemaRef.AddInitializerToDecl(LBDecl,
  6663. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6664. /*DirectInit*/ false);
  6665. // Upper bound variable, initialized with last iteration number.
  6666. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  6667. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  6668. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  6669. /*DirectInit*/ false);
  6670. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  6671. // This will be used to implement clause 'lastprivate'.
  6672. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  6673. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  6674. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  6675. SemaRef.AddInitializerToDecl(ILDecl,
  6676. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6677. /*DirectInit*/ false);
  6678. // Stride variable returned by runtime (we initialize it to 1 by default).
  6679. VarDecl *STDecl =
  6680. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  6681. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  6682. SemaRef.AddInitializerToDecl(STDecl,
  6683. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  6684. /*DirectInit*/ false);
  6685. // Build expression: UB = min(UB, LastIteration)
  6686. // It is necessary for CodeGen of directives with static scheduling.
  6687. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  6688. UB.get(), LastIteration.get());
  6689. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6690. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  6691. LastIteration.get(), UB.get());
  6692. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  6693. CondOp.get());
  6694. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  6695. // If we have a combined directive that combines 'distribute', 'for' or
  6696. // 'simd' we need to be able to access the bounds of the schedule of the
  6697. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  6698. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  6699. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6700. // Lower bound variable, initialized with zero.
  6701. VarDecl *CombLBDecl =
  6702. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  6703. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  6704. SemaRef.AddInitializerToDecl(
  6705. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  6706. /*DirectInit*/ false);
  6707. // Upper bound variable, initialized with last iteration number.
  6708. VarDecl *CombUBDecl =
  6709. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  6710. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  6711. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  6712. /*DirectInit*/ false);
  6713. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  6714. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  6715. ExprResult CombCondOp =
  6716. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  6717. LastIteration.get(), CombUB.get());
  6718. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  6719. CombCondOp.get());
  6720. CombEUB =
  6721. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  6722. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  6723. // We expect to have at least 2 more parameters than the 'parallel'
  6724. // directive does - the lower and upper bounds of the previous schedule.
  6725. assert(CD->getNumParams() >= 4 &&
  6726. "Unexpected number of parameters in loop combined directive");
  6727. // Set the proper type for the bounds given what we learned from the
  6728. // enclosed loops.
  6729. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  6730. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  6731. // Previous lower and upper bounds are obtained from the region
  6732. // parameters.
  6733. PrevLB =
  6734. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  6735. PrevUB =
  6736. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  6737. }
  6738. }
  6739. // Build the iteration variable and its initialization before loop.
  6740. ExprResult IV;
  6741. ExprResult Init, CombInit;
  6742. {
  6743. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  6744. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  6745. Expr *RHS =
  6746. (isOpenMPWorksharingDirective(DKind) ||
  6747. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6748. ? LB.get()
  6749. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6750. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  6751. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  6752. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6753. Expr *CombRHS =
  6754. (isOpenMPWorksharingDirective(DKind) ||
  6755. isOpenMPTaskLoopDirective(DKind) ||
  6756. isOpenMPDistributeDirective(DKind))
  6757. ? CombLB.get()
  6758. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  6759. CombInit =
  6760. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  6761. CombInit =
  6762. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  6763. }
  6764. }
  6765. bool UseStrictCompare =
  6766. RealVType->hasUnsignedIntegerRepresentation() &&
  6767. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  6768. return LIS.IsStrictCompare;
  6769. });
  6770. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  6771. // unsigned IV)) for worksharing loops.
  6772. SourceLocation CondLoc = AStmt->getBeginLoc();
  6773. Expr *BoundUB = UB.get();
  6774. if (UseStrictCompare) {
  6775. BoundUB =
  6776. SemaRef
  6777. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  6778. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6779. .get();
  6780. BoundUB =
  6781. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  6782. }
  6783. ExprResult Cond =
  6784. (isOpenMPWorksharingDirective(DKind) ||
  6785. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  6786. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  6787. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  6788. BoundUB)
  6789. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6790. NumIterations.get());
  6791. ExprResult CombDistCond;
  6792. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6793. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  6794. NumIterations.get());
  6795. }
  6796. ExprResult CombCond;
  6797. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6798. Expr *BoundCombUB = CombUB.get();
  6799. if (UseStrictCompare) {
  6800. BoundCombUB =
  6801. SemaRef
  6802. .BuildBinOp(
  6803. CurScope, CondLoc, BO_Add, BoundCombUB,
  6804. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6805. .get();
  6806. BoundCombUB =
  6807. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  6808. .get();
  6809. }
  6810. CombCond =
  6811. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6812. IV.get(), BoundCombUB);
  6813. }
  6814. // Loop increment (IV = IV + 1)
  6815. SourceLocation IncLoc = AStmt->getBeginLoc();
  6816. ExprResult Inc =
  6817. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  6818. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  6819. if (!Inc.isUsable())
  6820. return 0;
  6821. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  6822. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  6823. if (!Inc.isUsable())
  6824. return 0;
  6825. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  6826. // Used for directives with static scheduling.
  6827. // In combined construct, add combined version that use CombLB and CombUB
  6828. // base variables for the update
  6829. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  6830. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  6831. isOpenMPDistributeDirective(DKind)) {
  6832. // LB + ST
  6833. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  6834. if (!NextLB.isUsable())
  6835. return 0;
  6836. // LB = LB + ST
  6837. NextLB =
  6838. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  6839. NextLB =
  6840. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  6841. if (!NextLB.isUsable())
  6842. return 0;
  6843. // UB + ST
  6844. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  6845. if (!NextUB.isUsable())
  6846. return 0;
  6847. // UB = UB + ST
  6848. NextUB =
  6849. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  6850. NextUB =
  6851. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  6852. if (!NextUB.isUsable())
  6853. return 0;
  6854. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6855. CombNextLB =
  6856. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  6857. if (!NextLB.isUsable())
  6858. return 0;
  6859. // LB = LB + ST
  6860. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  6861. CombNextLB.get());
  6862. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  6863. /*DiscardedValue*/ false);
  6864. if (!CombNextLB.isUsable())
  6865. return 0;
  6866. // UB + ST
  6867. CombNextUB =
  6868. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  6869. if (!CombNextUB.isUsable())
  6870. return 0;
  6871. // UB = UB + ST
  6872. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  6873. CombNextUB.get());
  6874. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  6875. /*DiscardedValue*/ false);
  6876. if (!CombNextUB.isUsable())
  6877. return 0;
  6878. }
  6879. }
  6880. // Create increment expression for distribute loop when combined in a same
  6881. // directive with for as IV = IV + ST; ensure upper bound expression based
  6882. // on PrevUB instead of NumIterations - used to implement 'for' when found
  6883. // in combination with 'distribute', like in 'distribute parallel for'
  6884. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  6885. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  6886. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  6887. DistCond = SemaRef.BuildBinOp(
  6888. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  6889. assert(DistCond.isUsable() && "distribute cond expr was not built");
  6890. DistInc =
  6891. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  6892. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6893. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  6894. DistInc.get());
  6895. DistInc =
  6896. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  6897. assert(DistInc.isUsable() && "distribute inc expr was not built");
  6898. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  6899. // construct
  6900. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  6901. ExprResult IsUBGreater =
  6902. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  6903. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  6904. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  6905. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  6906. CondOp.get());
  6907. PrevEUB =
  6908. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  6909. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  6910. // parallel for is in combination with a distribute directive with
  6911. // schedule(static, 1)
  6912. Expr *BoundPrevUB = PrevUB.get();
  6913. if (UseStrictCompare) {
  6914. BoundPrevUB =
  6915. SemaRef
  6916. .BuildBinOp(
  6917. CurScope, CondLoc, BO_Add, BoundPrevUB,
  6918. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  6919. .get();
  6920. BoundPrevUB =
  6921. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  6922. .get();
  6923. }
  6924. ParForInDistCond =
  6925. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  6926. IV.get(), BoundPrevUB);
  6927. }
  6928. // Build updates and final values of the loop counters.
  6929. bool HasErrors = false;
  6930. Built.Counters.resize(NestedLoopCount);
  6931. Built.Inits.resize(NestedLoopCount);
  6932. Built.Updates.resize(NestedLoopCount);
  6933. Built.Finals.resize(NestedLoopCount);
  6934. Built.DependentCounters.resize(NestedLoopCount);
  6935. Built.DependentInits.resize(NestedLoopCount);
  6936. Built.FinalsConditions.resize(NestedLoopCount);
  6937. {
  6938. // We implement the following algorithm for obtaining the
  6939. // original loop iteration variable values based on the
  6940. // value of the collapsed loop iteration variable IV.
  6941. //
  6942. // Let n+1 be the number of collapsed loops in the nest.
  6943. // Iteration variables (I0, I1, .... In)
  6944. // Iteration counts (N0, N1, ... Nn)
  6945. //
  6946. // Acc = IV;
  6947. //
  6948. // To compute Ik for loop k, 0 <= k <= n, generate:
  6949. // Prod = N(k+1) * N(k+2) * ... * Nn;
  6950. // Ik = Acc / Prod;
  6951. // Acc -= Ik * Prod;
  6952. //
  6953. ExprResult Acc = IV;
  6954. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  6955. LoopIterationSpace &IS = IterSpaces[Cnt];
  6956. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  6957. ExprResult Iter;
  6958. // Compute prod
  6959. ExprResult Prod =
  6960. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6961. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  6962. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  6963. IterSpaces[K].NumIterations);
  6964. // Iter = Acc / Prod
  6965. // If there is at least one more inner loop to avoid
  6966. // multiplication by 1.
  6967. if (Cnt + 1 < NestedLoopCount)
  6968. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  6969. Acc.get(), Prod.get());
  6970. else
  6971. Iter = Acc;
  6972. if (!Iter.isUsable()) {
  6973. HasErrors = true;
  6974. break;
  6975. }
  6976. // Update Acc:
  6977. // Acc -= Iter * Prod
  6978. // Check if there is at least one more inner loop to avoid
  6979. // multiplication by 1.
  6980. if (Cnt + 1 < NestedLoopCount)
  6981. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  6982. Iter.get(), Prod.get());
  6983. else
  6984. Prod = Iter;
  6985. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  6986. Acc.get(), Prod.get());
  6987. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  6988. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  6989. DeclRefExpr *CounterVar = buildDeclRefExpr(
  6990. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  6991. /*RefersToCapture=*/true);
  6992. ExprResult Init =
  6993. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  6994. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  6995. if (!Init.isUsable()) {
  6996. HasErrors = true;
  6997. break;
  6998. }
  6999. ExprResult Update = buildCounterUpdate(
  7000. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  7001. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7002. if (!Update.isUsable()) {
  7003. HasErrors = true;
  7004. break;
  7005. }
  7006. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  7007. ExprResult Final =
  7008. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  7009. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  7010. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  7011. if (!Final.isUsable()) {
  7012. HasErrors = true;
  7013. break;
  7014. }
  7015. if (!Update.isUsable() || !Final.isUsable()) {
  7016. HasErrors = true;
  7017. break;
  7018. }
  7019. // Save results
  7020. Built.Counters[Cnt] = IS.CounterVar;
  7021. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  7022. Built.Inits[Cnt] = Init.get();
  7023. Built.Updates[Cnt] = Update.get();
  7024. Built.Finals[Cnt] = Final.get();
  7025. Built.DependentCounters[Cnt] = nullptr;
  7026. Built.DependentInits[Cnt] = nullptr;
  7027. Built.FinalsConditions[Cnt] = nullptr;
  7028. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  7029. Built.DependentCounters[Cnt] =
  7030. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7031. Built.DependentInits[Cnt] =
  7032. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  7033. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  7034. }
  7035. }
  7036. }
  7037. if (HasErrors)
  7038. return 0;
  7039. // Save results
  7040. Built.IterationVarRef = IV.get();
  7041. Built.LastIteration = LastIteration.get();
  7042. Built.NumIterations = NumIterations.get();
  7043. Built.CalcLastIteration = SemaRef
  7044. .ActOnFinishFullExpr(CalcLastIteration.get(),
  7045. /*DiscardedValue=*/false)
  7046. .get();
  7047. Built.PreCond = PreCond.get();
  7048. Built.PreInits = buildPreInits(C, Captures);
  7049. Built.Cond = Cond.get();
  7050. Built.Init = Init.get();
  7051. Built.Inc = Inc.get();
  7052. Built.LB = LB.get();
  7053. Built.UB = UB.get();
  7054. Built.IL = IL.get();
  7055. Built.ST = ST.get();
  7056. Built.EUB = EUB.get();
  7057. Built.NLB = NextLB.get();
  7058. Built.NUB = NextUB.get();
  7059. Built.PrevLB = PrevLB.get();
  7060. Built.PrevUB = PrevUB.get();
  7061. Built.DistInc = DistInc.get();
  7062. Built.PrevEUB = PrevEUB.get();
  7063. Built.DistCombinedFields.LB = CombLB.get();
  7064. Built.DistCombinedFields.UB = CombUB.get();
  7065. Built.DistCombinedFields.EUB = CombEUB.get();
  7066. Built.DistCombinedFields.Init = CombInit.get();
  7067. Built.DistCombinedFields.Cond = CombCond.get();
  7068. Built.DistCombinedFields.NLB = CombNextLB.get();
  7069. Built.DistCombinedFields.NUB = CombNextUB.get();
  7070. Built.DistCombinedFields.DistCond = CombDistCond.get();
  7071. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  7072. return NestedLoopCount;
  7073. }
  7074. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7075. auto CollapseClauses =
  7076. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  7077. if (CollapseClauses.begin() != CollapseClauses.end())
  7078. return (*CollapseClauses.begin())->getNumForLoops();
  7079. return nullptr;
  7080. }
  7081. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  7082. auto OrderedClauses =
  7083. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  7084. if (OrderedClauses.begin() != OrderedClauses.end())
  7085. return (*OrderedClauses.begin())->getNumForLoops();
  7086. return nullptr;
  7087. }
  7088. static bool checkSimdlenSafelenSpecified(Sema &S,
  7089. const ArrayRef<OMPClause *> Clauses) {
  7090. const OMPSafelenClause *Safelen = nullptr;
  7091. const OMPSimdlenClause *Simdlen = nullptr;
  7092. for (const OMPClause *Clause : Clauses) {
  7093. if (Clause->getClauseKind() == OMPC_safelen)
  7094. Safelen = cast<OMPSafelenClause>(Clause);
  7095. else if (Clause->getClauseKind() == OMPC_simdlen)
  7096. Simdlen = cast<OMPSimdlenClause>(Clause);
  7097. if (Safelen && Simdlen)
  7098. break;
  7099. }
  7100. if (Simdlen && Safelen) {
  7101. const Expr *SimdlenLength = Simdlen->getSimdlen();
  7102. const Expr *SafelenLength = Safelen->getSafelen();
  7103. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  7104. SimdlenLength->isInstantiationDependent() ||
  7105. SimdlenLength->containsUnexpandedParameterPack())
  7106. return false;
  7107. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  7108. SafelenLength->isInstantiationDependent() ||
  7109. SafelenLength->containsUnexpandedParameterPack())
  7110. return false;
  7111. Expr::EvalResult SimdlenResult, SafelenResult;
  7112. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  7113. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  7114. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  7115. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  7116. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  7117. // If both simdlen and safelen clauses are specified, the value of the
  7118. // simdlen parameter must be less than or equal to the value of the safelen
  7119. // parameter.
  7120. if (SimdlenRes > SafelenRes) {
  7121. S.Diag(SimdlenLength->getExprLoc(),
  7122. diag::err_omp_wrong_simdlen_safelen_values)
  7123. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  7124. return true;
  7125. }
  7126. }
  7127. return false;
  7128. }
  7129. StmtResult
  7130. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7131. SourceLocation StartLoc, SourceLocation EndLoc,
  7132. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7133. if (!AStmt)
  7134. return StmtError();
  7135. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7136. OMPLoopDirective::HelperExprs B;
  7137. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7138. // define the nested loops number.
  7139. unsigned NestedLoopCount = checkOpenMPLoop(
  7140. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7141. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7142. if (NestedLoopCount == 0)
  7143. return StmtError();
  7144. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7145. "omp simd loop exprs were not built");
  7146. if (!CurContext->isDependentContext()) {
  7147. // Finalize the clauses that need pre-built expressions for CodeGen.
  7148. for (OMPClause *C : Clauses) {
  7149. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7150. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7151. B.NumIterations, *this, CurScope,
  7152. DSAStack))
  7153. return StmtError();
  7154. }
  7155. }
  7156. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7157. return StmtError();
  7158. setFunctionHasBranchProtectedScope();
  7159. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7160. Clauses, AStmt, B);
  7161. }
  7162. StmtResult
  7163. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  7164. SourceLocation StartLoc, SourceLocation EndLoc,
  7165. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7166. if (!AStmt)
  7167. return StmtError();
  7168. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7169. OMPLoopDirective::HelperExprs B;
  7170. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7171. // define the nested loops number.
  7172. unsigned NestedLoopCount = checkOpenMPLoop(
  7173. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  7174. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  7175. if (NestedLoopCount == 0)
  7176. return StmtError();
  7177. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7178. "omp for loop exprs were not built");
  7179. if (!CurContext->isDependentContext()) {
  7180. // Finalize the clauses that need pre-built expressions for CodeGen.
  7181. for (OMPClause *C : Clauses) {
  7182. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7183. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7184. B.NumIterations, *this, CurScope,
  7185. DSAStack))
  7186. return StmtError();
  7187. }
  7188. }
  7189. setFunctionHasBranchProtectedScope();
  7190. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7191. Clauses, AStmt, B, DSAStack->isCancelRegion());
  7192. }
  7193. StmtResult Sema::ActOnOpenMPForSimdDirective(
  7194. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7195. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7196. if (!AStmt)
  7197. return StmtError();
  7198. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7199. OMPLoopDirective::HelperExprs B;
  7200. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7201. // define the nested loops number.
  7202. unsigned NestedLoopCount =
  7203. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  7204. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7205. VarsWithImplicitDSA, B);
  7206. if (NestedLoopCount == 0)
  7207. return StmtError();
  7208. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7209. "omp for simd loop exprs were not built");
  7210. if (!CurContext->isDependentContext()) {
  7211. // Finalize the clauses that need pre-built expressions for CodeGen.
  7212. for (OMPClause *C : Clauses) {
  7213. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7214. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7215. B.NumIterations, *this, CurScope,
  7216. DSAStack))
  7217. return StmtError();
  7218. }
  7219. }
  7220. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7221. return StmtError();
  7222. setFunctionHasBranchProtectedScope();
  7223. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  7224. Clauses, AStmt, B);
  7225. }
  7226. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7227. Stmt *AStmt,
  7228. SourceLocation StartLoc,
  7229. SourceLocation EndLoc) {
  7230. if (!AStmt)
  7231. return StmtError();
  7232. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7233. auto BaseStmt = AStmt;
  7234. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7235. BaseStmt = CS->getCapturedStmt();
  7236. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7237. auto S = C->children();
  7238. if (S.begin() == S.end())
  7239. return StmtError();
  7240. // All associated statements must be '#pragma omp section' except for
  7241. // the first one.
  7242. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7243. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7244. if (SectionStmt)
  7245. Diag(SectionStmt->getBeginLoc(),
  7246. diag::err_omp_sections_substmt_not_section);
  7247. return StmtError();
  7248. }
  7249. cast<OMPSectionDirective>(SectionStmt)
  7250. ->setHasCancel(DSAStack->isCancelRegion());
  7251. }
  7252. } else {
  7253. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  7254. return StmtError();
  7255. }
  7256. setFunctionHasBranchProtectedScope();
  7257. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7258. DSAStack->isCancelRegion());
  7259. }
  7260. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  7261. SourceLocation StartLoc,
  7262. SourceLocation EndLoc) {
  7263. if (!AStmt)
  7264. return StmtError();
  7265. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7266. setFunctionHasBranchProtectedScope();
  7267. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  7268. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  7269. DSAStack->isCancelRegion());
  7270. }
  7271. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  7272. Stmt *AStmt,
  7273. SourceLocation StartLoc,
  7274. SourceLocation EndLoc) {
  7275. if (!AStmt)
  7276. return StmtError();
  7277. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7278. setFunctionHasBranchProtectedScope();
  7279. // OpenMP [2.7.3, single Construct, Restrictions]
  7280. // The copyprivate clause must not be used with the nowait clause.
  7281. const OMPClause *Nowait = nullptr;
  7282. const OMPClause *Copyprivate = nullptr;
  7283. for (const OMPClause *Clause : Clauses) {
  7284. if (Clause->getClauseKind() == OMPC_nowait)
  7285. Nowait = Clause;
  7286. else if (Clause->getClauseKind() == OMPC_copyprivate)
  7287. Copyprivate = Clause;
  7288. if (Copyprivate && Nowait) {
  7289. Diag(Copyprivate->getBeginLoc(),
  7290. diag::err_omp_single_copyprivate_with_nowait);
  7291. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  7292. return StmtError();
  7293. }
  7294. }
  7295. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7296. }
  7297. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  7298. SourceLocation StartLoc,
  7299. SourceLocation EndLoc) {
  7300. if (!AStmt)
  7301. return StmtError();
  7302. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7303. setFunctionHasBranchProtectedScope();
  7304. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  7305. }
  7306. StmtResult Sema::ActOnOpenMPCriticalDirective(
  7307. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  7308. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  7309. if (!AStmt)
  7310. return StmtError();
  7311. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7312. bool ErrorFound = false;
  7313. llvm::APSInt Hint;
  7314. SourceLocation HintLoc;
  7315. bool DependentHint = false;
  7316. for (const OMPClause *C : Clauses) {
  7317. if (C->getClauseKind() == OMPC_hint) {
  7318. if (!DirName.getName()) {
  7319. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  7320. ErrorFound = true;
  7321. }
  7322. Expr *E = cast<OMPHintClause>(C)->getHint();
  7323. if (E->isTypeDependent() || E->isValueDependent() ||
  7324. E->isInstantiationDependent()) {
  7325. DependentHint = true;
  7326. } else {
  7327. Hint = E->EvaluateKnownConstInt(Context);
  7328. HintLoc = C->getBeginLoc();
  7329. }
  7330. }
  7331. }
  7332. if (ErrorFound)
  7333. return StmtError();
  7334. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  7335. if (Pair.first && DirName.getName() && !DependentHint) {
  7336. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  7337. Diag(StartLoc, diag::err_omp_critical_with_hint);
  7338. if (HintLoc.isValid())
  7339. Diag(HintLoc, diag::note_omp_critical_hint_here)
  7340. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  7341. else
  7342. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  7343. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  7344. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  7345. << 1
  7346. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  7347. /*Radix=*/10, /*Signed=*/false);
  7348. } else {
  7349. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  7350. }
  7351. }
  7352. }
  7353. setFunctionHasBranchProtectedScope();
  7354. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  7355. Clauses, AStmt);
  7356. if (!Pair.first && DirName.getName() && !DependentHint)
  7357. DSAStack->addCriticalWithHint(Dir, Hint);
  7358. return Dir;
  7359. }
  7360. StmtResult Sema::ActOnOpenMPParallelForDirective(
  7361. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7362. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7363. if (!AStmt)
  7364. return StmtError();
  7365. auto *CS = cast<CapturedStmt>(AStmt);
  7366. // 1.2.2 OpenMP Language Terminology
  7367. // Structured block - An executable statement with a single entry at the
  7368. // top and a single exit at the bottom.
  7369. // The point of exit cannot be a branch out of the structured block.
  7370. // longjmp() and throw() must not violate the entry/exit criteria.
  7371. CS->getCapturedDecl()->setNothrow();
  7372. OMPLoopDirective::HelperExprs B;
  7373. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7374. // define the nested loops number.
  7375. unsigned NestedLoopCount =
  7376. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  7377. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7378. VarsWithImplicitDSA, B);
  7379. if (NestedLoopCount == 0)
  7380. return StmtError();
  7381. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7382. "omp parallel for loop exprs were not built");
  7383. if (!CurContext->isDependentContext()) {
  7384. // Finalize the clauses that need pre-built expressions for CodeGen.
  7385. for (OMPClause *C : Clauses) {
  7386. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7387. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7388. B.NumIterations, *this, CurScope,
  7389. DSAStack))
  7390. return StmtError();
  7391. }
  7392. }
  7393. setFunctionHasBranchProtectedScope();
  7394. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  7395. NestedLoopCount, Clauses, AStmt, B,
  7396. DSAStack->isCancelRegion());
  7397. }
  7398. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  7399. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7400. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7401. if (!AStmt)
  7402. return StmtError();
  7403. auto *CS = cast<CapturedStmt>(AStmt);
  7404. // 1.2.2 OpenMP Language Terminology
  7405. // Structured block - An executable statement with a single entry at the
  7406. // top and a single exit at the bottom.
  7407. // The point of exit cannot be a branch out of the structured block.
  7408. // longjmp() and throw() must not violate the entry/exit criteria.
  7409. CS->getCapturedDecl()->setNothrow();
  7410. OMPLoopDirective::HelperExprs B;
  7411. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7412. // define the nested loops number.
  7413. unsigned NestedLoopCount =
  7414. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7415. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  7416. VarsWithImplicitDSA, B);
  7417. if (NestedLoopCount == 0)
  7418. return StmtError();
  7419. if (!CurContext->isDependentContext()) {
  7420. // Finalize the clauses that need pre-built expressions for CodeGen.
  7421. for (OMPClause *C : Clauses) {
  7422. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7423. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7424. B.NumIterations, *this, CurScope,
  7425. DSAStack))
  7426. return StmtError();
  7427. }
  7428. }
  7429. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7430. return StmtError();
  7431. setFunctionHasBranchProtectedScope();
  7432. return OMPParallelForSimdDirective::Create(
  7433. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7434. }
  7435. StmtResult
  7436. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  7437. Stmt *AStmt, SourceLocation StartLoc,
  7438. SourceLocation EndLoc) {
  7439. if (!AStmt)
  7440. return StmtError();
  7441. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7442. auto BaseStmt = AStmt;
  7443. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  7444. BaseStmt = CS->getCapturedStmt();
  7445. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  7446. auto S = C->children();
  7447. if (S.begin() == S.end())
  7448. return StmtError();
  7449. // All associated statements must be '#pragma omp section' except for
  7450. // the first one.
  7451. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  7452. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  7453. if (SectionStmt)
  7454. Diag(SectionStmt->getBeginLoc(),
  7455. diag::err_omp_parallel_sections_substmt_not_section);
  7456. return StmtError();
  7457. }
  7458. cast<OMPSectionDirective>(SectionStmt)
  7459. ->setHasCancel(DSAStack->isCancelRegion());
  7460. }
  7461. } else {
  7462. Diag(AStmt->getBeginLoc(),
  7463. diag::err_omp_parallel_sections_not_compound_stmt);
  7464. return StmtError();
  7465. }
  7466. setFunctionHasBranchProtectedScope();
  7467. return OMPParallelSectionsDirective::Create(
  7468. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  7469. }
  7470. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  7471. Stmt *AStmt, SourceLocation StartLoc,
  7472. SourceLocation EndLoc) {
  7473. if (!AStmt)
  7474. return StmtError();
  7475. auto *CS = cast<CapturedStmt>(AStmt);
  7476. // 1.2.2 OpenMP Language Terminology
  7477. // Structured block - An executable statement with a single entry at the
  7478. // top and a single exit at the bottom.
  7479. // The point of exit cannot be a branch out of the structured block.
  7480. // longjmp() and throw() must not violate the entry/exit criteria.
  7481. CS->getCapturedDecl()->setNothrow();
  7482. setFunctionHasBranchProtectedScope();
  7483. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7484. DSAStack->isCancelRegion());
  7485. }
  7486. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  7487. SourceLocation EndLoc) {
  7488. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  7489. }
  7490. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  7491. SourceLocation EndLoc) {
  7492. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  7493. }
  7494. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  7495. SourceLocation EndLoc) {
  7496. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  7497. }
  7498. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  7499. Stmt *AStmt,
  7500. SourceLocation StartLoc,
  7501. SourceLocation EndLoc) {
  7502. if (!AStmt)
  7503. return StmtError();
  7504. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7505. setFunctionHasBranchProtectedScope();
  7506. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7507. AStmt,
  7508. DSAStack->getTaskgroupReductionRef());
  7509. }
  7510. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  7511. SourceLocation StartLoc,
  7512. SourceLocation EndLoc) {
  7513. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  7514. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  7515. }
  7516. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  7517. Stmt *AStmt,
  7518. SourceLocation StartLoc,
  7519. SourceLocation EndLoc) {
  7520. const OMPClause *DependFound = nullptr;
  7521. const OMPClause *DependSourceClause = nullptr;
  7522. const OMPClause *DependSinkClause = nullptr;
  7523. bool ErrorFound = false;
  7524. const OMPThreadsClause *TC = nullptr;
  7525. const OMPSIMDClause *SC = nullptr;
  7526. for (const OMPClause *C : Clauses) {
  7527. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  7528. DependFound = C;
  7529. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  7530. if (DependSourceClause) {
  7531. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  7532. << getOpenMPDirectiveName(OMPD_ordered)
  7533. << getOpenMPClauseName(OMPC_depend) << 2;
  7534. ErrorFound = true;
  7535. } else {
  7536. DependSourceClause = C;
  7537. }
  7538. if (DependSinkClause) {
  7539. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7540. << 0;
  7541. ErrorFound = true;
  7542. }
  7543. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  7544. if (DependSourceClause) {
  7545. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  7546. << 1;
  7547. ErrorFound = true;
  7548. }
  7549. DependSinkClause = C;
  7550. }
  7551. } else if (C->getClauseKind() == OMPC_threads) {
  7552. TC = cast<OMPThreadsClause>(C);
  7553. } else if (C->getClauseKind() == OMPC_simd) {
  7554. SC = cast<OMPSIMDClause>(C);
  7555. }
  7556. }
  7557. if (!ErrorFound && !SC &&
  7558. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  7559. // OpenMP [2.8.1,simd Construct, Restrictions]
  7560. // An ordered construct with the simd clause is the only OpenMP construct
  7561. // that can appear in the simd region.
  7562. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  7563. ErrorFound = true;
  7564. } else if (DependFound && (TC || SC)) {
  7565. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  7566. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  7567. ErrorFound = true;
  7568. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  7569. Diag(DependFound->getBeginLoc(),
  7570. diag::err_omp_ordered_directive_without_param);
  7571. ErrorFound = true;
  7572. } else if (TC || Clauses.empty()) {
  7573. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  7574. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  7575. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  7576. << (TC != nullptr);
  7577. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  7578. ErrorFound = true;
  7579. }
  7580. }
  7581. if ((!AStmt && !DependFound) || ErrorFound)
  7582. return StmtError();
  7583. if (AStmt) {
  7584. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7585. setFunctionHasBranchProtectedScope();
  7586. }
  7587. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7588. }
  7589. namespace {
  7590. /// Helper class for checking expression in 'omp atomic [update]'
  7591. /// construct.
  7592. class OpenMPAtomicUpdateChecker {
  7593. /// Error results for atomic update expressions.
  7594. enum ExprAnalysisErrorCode {
  7595. /// A statement is not an expression statement.
  7596. NotAnExpression,
  7597. /// Expression is not builtin binary or unary operation.
  7598. NotABinaryOrUnaryExpression,
  7599. /// Unary operation is not post-/pre- increment/decrement operation.
  7600. NotAnUnaryIncDecExpression,
  7601. /// An expression is not of scalar type.
  7602. NotAScalarType,
  7603. /// A binary operation is not an assignment operation.
  7604. NotAnAssignmentOp,
  7605. /// RHS part of the binary operation is not a binary expression.
  7606. NotABinaryExpression,
  7607. /// RHS part is not additive/multiplicative/shift/biwise binary
  7608. /// expression.
  7609. NotABinaryOperator,
  7610. /// RHS binary operation does not have reference to the updated LHS
  7611. /// part.
  7612. NotAnUpdateExpression,
  7613. /// No errors is found.
  7614. NoError
  7615. };
  7616. /// Reference to Sema.
  7617. Sema &SemaRef;
  7618. /// A location for note diagnostics (when error is found).
  7619. SourceLocation NoteLoc;
  7620. /// 'x' lvalue part of the source atomic expression.
  7621. Expr *X;
  7622. /// 'expr' rvalue part of the source atomic expression.
  7623. Expr *E;
  7624. /// Helper expression of the form
  7625. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7626. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7627. Expr *UpdateExpr;
  7628. /// Is 'x' a LHS in a RHS part of full update expression. It is
  7629. /// important for non-associative operations.
  7630. bool IsXLHSInRHSPart;
  7631. BinaryOperatorKind Op;
  7632. SourceLocation OpLoc;
  7633. /// true if the source expression is a postfix unary operation, false
  7634. /// if it is a prefix unary operation.
  7635. bool IsPostfixUpdate;
  7636. public:
  7637. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  7638. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  7639. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  7640. /// Check specified statement that it is suitable for 'atomic update'
  7641. /// constructs and extract 'x', 'expr' and Operation from the original
  7642. /// expression. If DiagId and NoteId == 0, then only check is performed
  7643. /// without error notification.
  7644. /// \param DiagId Diagnostic which should be emitted if error is found.
  7645. /// \param NoteId Diagnostic note for the main error message.
  7646. /// \return true if statement is not an update expression, false otherwise.
  7647. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  7648. /// Return the 'x' lvalue part of the source atomic expression.
  7649. Expr *getX() const { return X; }
  7650. /// Return the 'expr' rvalue part of the source atomic expression.
  7651. Expr *getExpr() const { return E; }
  7652. /// Return the update expression used in calculation of the updated
  7653. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  7654. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  7655. Expr *getUpdateExpr() const { return UpdateExpr; }
  7656. /// Return true if 'x' is LHS in RHS part of full update expression,
  7657. /// false otherwise.
  7658. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  7659. /// true if the source expression is a postfix unary operation, false
  7660. /// if it is a prefix unary operation.
  7661. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  7662. private:
  7663. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  7664. unsigned NoteId = 0);
  7665. };
  7666. } // namespace
  7667. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  7668. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  7669. ExprAnalysisErrorCode ErrorFound = NoError;
  7670. SourceLocation ErrorLoc, NoteLoc;
  7671. SourceRange ErrorRange, NoteRange;
  7672. // Allowed constructs are:
  7673. // x = x binop expr;
  7674. // x = expr binop x;
  7675. if (AtomicBinOp->getOpcode() == BO_Assign) {
  7676. X = AtomicBinOp->getLHS();
  7677. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  7678. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  7679. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  7680. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  7681. AtomicInnerBinOp->isBitwiseOp()) {
  7682. Op = AtomicInnerBinOp->getOpcode();
  7683. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  7684. Expr *LHS = AtomicInnerBinOp->getLHS();
  7685. Expr *RHS = AtomicInnerBinOp->getRHS();
  7686. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  7687. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  7688. /*Canonical=*/true);
  7689. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  7690. /*Canonical=*/true);
  7691. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  7692. /*Canonical=*/true);
  7693. if (XId == LHSId) {
  7694. E = RHS;
  7695. IsXLHSInRHSPart = true;
  7696. } else if (XId == RHSId) {
  7697. E = LHS;
  7698. IsXLHSInRHSPart = false;
  7699. } else {
  7700. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7701. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7702. NoteLoc = X->getExprLoc();
  7703. NoteRange = X->getSourceRange();
  7704. ErrorFound = NotAnUpdateExpression;
  7705. }
  7706. } else {
  7707. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  7708. ErrorRange = AtomicInnerBinOp->getSourceRange();
  7709. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  7710. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7711. ErrorFound = NotABinaryOperator;
  7712. }
  7713. } else {
  7714. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  7715. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  7716. ErrorFound = NotABinaryExpression;
  7717. }
  7718. } else {
  7719. ErrorLoc = AtomicBinOp->getExprLoc();
  7720. ErrorRange = AtomicBinOp->getSourceRange();
  7721. NoteLoc = AtomicBinOp->getOperatorLoc();
  7722. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7723. ErrorFound = NotAnAssignmentOp;
  7724. }
  7725. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7726. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7727. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7728. return true;
  7729. }
  7730. if (SemaRef.CurContext->isDependentContext())
  7731. E = X = UpdateExpr = nullptr;
  7732. return ErrorFound != NoError;
  7733. }
  7734. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  7735. unsigned NoteId) {
  7736. ExprAnalysisErrorCode ErrorFound = NoError;
  7737. SourceLocation ErrorLoc, NoteLoc;
  7738. SourceRange ErrorRange, NoteRange;
  7739. // Allowed constructs are:
  7740. // x++;
  7741. // x--;
  7742. // ++x;
  7743. // --x;
  7744. // x binop= expr;
  7745. // x = x binop expr;
  7746. // x = expr binop x;
  7747. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  7748. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  7749. if (AtomicBody->getType()->isScalarType() ||
  7750. AtomicBody->isInstantiationDependent()) {
  7751. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  7752. AtomicBody->IgnoreParenImpCasts())) {
  7753. // Check for Compound Assignment Operation
  7754. Op = BinaryOperator::getOpForCompoundAssignment(
  7755. AtomicCompAssignOp->getOpcode());
  7756. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  7757. E = AtomicCompAssignOp->getRHS();
  7758. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  7759. IsXLHSInRHSPart = true;
  7760. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  7761. AtomicBody->IgnoreParenImpCasts())) {
  7762. // Check for Binary Operation
  7763. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  7764. return true;
  7765. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  7766. AtomicBody->IgnoreParenImpCasts())) {
  7767. // Check for Unary Operation
  7768. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  7769. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  7770. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  7771. OpLoc = AtomicUnaryOp->getOperatorLoc();
  7772. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  7773. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  7774. IsXLHSInRHSPart = true;
  7775. } else {
  7776. ErrorFound = NotAnUnaryIncDecExpression;
  7777. ErrorLoc = AtomicUnaryOp->getExprLoc();
  7778. ErrorRange = AtomicUnaryOp->getSourceRange();
  7779. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  7780. NoteRange = SourceRange(NoteLoc, NoteLoc);
  7781. }
  7782. } else if (!AtomicBody->isInstantiationDependent()) {
  7783. ErrorFound = NotABinaryOrUnaryExpression;
  7784. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  7785. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  7786. }
  7787. } else {
  7788. ErrorFound = NotAScalarType;
  7789. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  7790. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7791. }
  7792. } else {
  7793. ErrorFound = NotAnExpression;
  7794. NoteLoc = ErrorLoc = S->getBeginLoc();
  7795. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7796. }
  7797. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  7798. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  7799. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  7800. return true;
  7801. }
  7802. if (SemaRef.CurContext->isDependentContext())
  7803. E = X = UpdateExpr = nullptr;
  7804. if (ErrorFound == NoError && E && X) {
  7805. // Build an update expression of form 'OpaqueValueExpr(x) binop
  7806. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  7807. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  7808. auto *OVEX = new (SemaRef.getASTContext())
  7809. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  7810. auto *OVEExpr = new (SemaRef.getASTContext())
  7811. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  7812. ExprResult Update =
  7813. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  7814. IsXLHSInRHSPart ? OVEExpr : OVEX);
  7815. if (Update.isInvalid())
  7816. return true;
  7817. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  7818. Sema::AA_Casting);
  7819. if (Update.isInvalid())
  7820. return true;
  7821. UpdateExpr = Update.get();
  7822. }
  7823. return ErrorFound != NoError;
  7824. }
  7825. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  7826. Stmt *AStmt,
  7827. SourceLocation StartLoc,
  7828. SourceLocation EndLoc) {
  7829. if (!AStmt)
  7830. return StmtError();
  7831. auto *CS = cast<CapturedStmt>(AStmt);
  7832. // 1.2.2 OpenMP Language Terminology
  7833. // Structured block - An executable statement with a single entry at the
  7834. // top and a single exit at the bottom.
  7835. // The point of exit cannot be a branch out of the structured block.
  7836. // longjmp() and throw() must not violate the entry/exit criteria.
  7837. OpenMPClauseKind AtomicKind = OMPC_unknown;
  7838. SourceLocation AtomicKindLoc;
  7839. for (const OMPClause *C : Clauses) {
  7840. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  7841. C->getClauseKind() == OMPC_update ||
  7842. C->getClauseKind() == OMPC_capture) {
  7843. if (AtomicKind != OMPC_unknown) {
  7844. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  7845. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  7846. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  7847. << getOpenMPClauseName(AtomicKind);
  7848. } else {
  7849. AtomicKind = C->getClauseKind();
  7850. AtomicKindLoc = C->getBeginLoc();
  7851. }
  7852. }
  7853. }
  7854. Stmt *Body = CS->getCapturedStmt();
  7855. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  7856. Body = EWC->getSubExpr();
  7857. Expr *X = nullptr;
  7858. Expr *V = nullptr;
  7859. Expr *E = nullptr;
  7860. Expr *UE = nullptr;
  7861. bool IsXLHSInRHSPart = false;
  7862. bool IsPostfixUpdate = false;
  7863. // OpenMP [2.12.6, atomic Construct]
  7864. // In the next expressions:
  7865. // * x and v (as applicable) are both l-value expressions with scalar type.
  7866. // * During the execution of an atomic region, multiple syntactic
  7867. // occurrences of x must designate the same storage location.
  7868. // * Neither of v and expr (as applicable) may access the storage location
  7869. // designated by x.
  7870. // * Neither of x and expr (as applicable) may access the storage location
  7871. // designated by v.
  7872. // * expr is an expression with scalar type.
  7873. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  7874. // * binop, binop=, ++, and -- are not overloaded operators.
  7875. // * The expression x binop expr must be numerically equivalent to x binop
  7876. // (expr). This requirement is satisfied if the operators in expr have
  7877. // precedence greater than binop, or by using parentheses around expr or
  7878. // subexpressions of expr.
  7879. // * The expression expr binop x must be numerically equivalent to (expr)
  7880. // binop x. This requirement is satisfied if the operators in expr have
  7881. // precedence equal to or greater than binop, or by using parentheses around
  7882. // expr or subexpressions of expr.
  7883. // * For forms that allow multiple occurrences of x, the number of times
  7884. // that x is evaluated is unspecified.
  7885. if (AtomicKind == OMPC_read) {
  7886. enum {
  7887. NotAnExpression,
  7888. NotAnAssignmentOp,
  7889. NotAScalarType,
  7890. NotAnLValue,
  7891. NoError
  7892. } ErrorFound = NoError;
  7893. SourceLocation ErrorLoc, NoteLoc;
  7894. SourceRange ErrorRange, NoteRange;
  7895. // If clause is read:
  7896. // v = x;
  7897. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7898. const auto *AtomicBinOp =
  7899. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7900. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7901. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  7902. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  7903. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7904. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  7905. if (!X->isLValue() || !V->isLValue()) {
  7906. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  7907. ErrorFound = NotAnLValue;
  7908. ErrorLoc = AtomicBinOp->getExprLoc();
  7909. ErrorRange = AtomicBinOp->getSourceRange();
  7910. NoteLoc = NotLValueExpr->getExprLoc();
  7911. NoteRange = NotLValueExpr->getSourceRange();
  7912. }
  7913. } else if (!X->isInstantiationDependent() ||
  7914. !V->isInstantiationDependent()) {
  7915. const Expr *NotScalarExpr =
  7916. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7917. ? V
  7918. : X;
  7919. ErrorFound = NotAScalarType;
  7920. ErrorLoc = AtomicBinOp->getExprLoc();
  7921. ErrorRange = AtomicBinOp->getSourceRange();
  7922. NoteLoc = NotScalarExpr->getExprLoc();
  7923. NoteRange = NotScalarExpr->getSourceRange();
  7924. }
  7925. } else if (!AtomicBody->isInstantiationDependent()) {
  7926. ErrorFound = NotAnAssignmentOp;
  7927. ErrorLoc = AtomicBody->getExprLoc();
  7928. ErrorRange = AtomicBody->getSourceRange();
  7929. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7930. : AtomicBody->getExprLoc();
  7931. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7932. : AtomicBody->getSourceRange();
  7933. }
  7934. } else {
  7935. ErrorFound = NotAnExpression;
  7936. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7937. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  7938. }
  7939. if (ErrorFound != NoError) {
  7940. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  7941. << ErrorRange;
  7942. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  7943. << NoteRange;
  7944. return StmtError();
  7945. }
  7946. if (CurContext->isDependentContext())
  7947. V = X = nullptr;
  7948. } else if (AtomicKind == OMPC_write) {
  7949. enum {
  7950. NotAnExpression,
  7951. NotAnAssignmentOp,
  7952. NotAScalarType,
  7953. NotAnLValue,
  7954. NoError
  7955. } ErrorFound = NoError;
  7956. SourceLocation ErrorLoc, NoteLoc;
  7957. SourceRange ErrorRange, NoteRange;
  7958. // If clause is write:
  7959. // x = expr;
  7960. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  7961. const auto *AtomicBinOp =
  7962. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  7963. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  7964. X = AtomicBinOp->getLHS();
  7965. E = AtomicBinOp->getRHS();
  7966. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  7967. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  7968. if (!X->isLValue()) {
  7969. ErrorFound = NotAnLValue;
  7970. ErrorLoc = AtomicBinOp->getExprLoc();
  7971. ErrorRange = AtomicBinOp->getSourceRange();
  7972. NoteLoc = X->getExprLoc();
  7973. NoteRange = X->getSourceRange();
  7974. }
  7975. } else if (!X->isInstantiationDependent() ||
  7976. !E->isInstantiationDependent()) {
  7977. const Expr *NotScalarExpr =
  7978. (X->isInstantiationDependent() || X->getType()->isScalarType())
  7979. ? E
  7980. : X;
  7981. ErrorFound = NotAScalarType;
  7982. ErrorLoc = AtomicBinOp->getExprLoc();
  7983. ErrorRange = AtomicBinOp->getSourceRange();
  7984. NoteLoc = NotScalarExpr->getExprLoc();
  7985. NoteRange = NotScalarExpr->getSourceRange();
  7986. }
  7987. } else if (!AtomicBody->isInstantiationDependent()) {
  7988. ErrorFound = NotAnAssignmentOp;
  7989. ErrorLoc = AtomicBody->getExprLoc();
  7990. ErrorRange = AtomicBody->getSourceRange();
  7991. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  7992. : AtomicBody->getExprLoc();
  7993. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  7994. : AtomicBody->getSourceRange();
  7995. }
  7996. } else {
  7997. ErrorFound = NotAnExpression;
  7998. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7999. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  8000. }
  8001. if (ErrorFound != NoError) {
  8002. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  8003. << ErrorRange;
  8004. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  8005. << NoteRange;
  8006. return StmtError();
  8007. }
  8008. if (CurContext->isDependentContext())
  8009. E = X = nullptr;
  8010. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  8011. // If clause is update:
  8012. // x++;
  8013. // x--;
  8014. // ++x;
  8015. // --x;
  8016. // x binop= expr;
  8017. // x = x binop expr;
  8018. // x = expr binop x;
  8019. OpenMPAtomicUpdateChecker Checker(*this);
  8020. if (Checker.checkStatement(
  8021. Body, (AtomicKind == OMPC_update)
  8022. ? diag::err_omp_atomic_update_not_expression_statement
  8023. : diag::err_omp_atomic_not_expression_statement,
  8024. diag::note_omp_atomic_update))
  8025. return StmtError();
  8026. if (!CurContext->isDependentContext()) {
  8027. E = Checker.getExpr();
  8028. X = Checker.getX();
  8029. UE = Checker.getUpdateExpr();
  8030. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8031. }
  8032. } else if (AtomicKind == OMPC_capture) {
  8033. enum {
  8034. NotAnAssignmentOp,
  8035. NotACompoundStatement,
  8036. NotTwoSubstatements,
  8037. NotASpecificExpression,
  8038. NoError
  8039. } ErrorFound = NoError;
  8040. SourceLocation ErrorLoc, NoteLoc;
  8041. SourceRange ErrorRange, NoteRange;
  8042. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  8043. // If clause is a capture:
  8044. // v = x++;
  8045. // v = x--;
  8046. // v = ++x;
  8047. // v = --x;
  8048. // v = x binop= expr;
  8049. // v = x = x binop expr;
  8050. // v = x = expr binop x;
  8051. const auto *AtomicBinOp =
  8052. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  8053. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  8054. V = AtomicBinOp->getLHS();
  8055. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  8056. OpenMPAtomicUpdateChecker Checker(*this);
  8057. if (Checker.checkStatement(
  8058. Body, diag::err_omp_atomic_capture_not_expression_statement,
  8059. diag::note_omp_atomic_update))
  8060. return StmtError();
  8061. E = Checker.getExpr();
  8062. X = Checker.getX();
  8063. UE = Checker.getUpdateExpr();
  8064. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8065. IsPostfixUpdate = Checker.isPostfixUpdate();
  8066. } else if (!AtomicBody->isInstantiationDependent()) {
  8067. ErrorLoc = AtomicBody->getExprLoc();
  8068. ErrorRange = AtomicBody->getSourceRange();
  8069. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  8070. : AtomicBody->getExprLoc();
  8071. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  8072. : AtomicBody->getSourceRange();
  8073. ErrorFound = NotAnAssignmentOp;
  8074. }
  8075. if (ErrorFound != NoError) {
  8076. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  8077. << ErrorRange;
  8078. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8079. return StmtError();
  8080. }
  8081. if (CurContext->isDependentContext())
  8082. UE = V = E = X = nullptr;
  8083. } else {
  8084. // If clause is a capture:
  8085. // { v = x; x = expr; }
  8086. // { v = x; x++; }
  8087. // { v = x; x--; }
  8088. // { v = x; ++x; }
  8089. // { v = x; --x; }
  8090. // { v = x; x binop= expr; }
  8091. // { v = x; x = x binop expr; }
  8092. // { v = x; x = expr binop x; }
  8093. // { x++; v = x; }
  8094. // { x--; v = x; }
  8095. // { ++x; v = x; }
  8096. // { --x; v = x; }
  8097. // { x binop= expr; v = x; }
  8098. // { x = x binop expr; v = x; }
  8099. // { x = expr binop x; v = x; }
  8100. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  8101. // Check that this is { expr1; expr2; }
  8102. if (CS->size() == 2) {
  8103. Stmt *First = CS->body_front();
  8104. Stmt *Second = CS->body_back();
  8105. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  8106. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  8107. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  8108. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  8109. // Need to find what subexpression is 'v' and what is 'x'.
  8110. OpenMPAtomicUpdateChecker Checker(*this);
  8111. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  8112. BinaryOperator *BinOp = nullptr;
  8113. if (IsUpdateExprFound) {
  8114. BinOp = dyn_cast<BinaryOperator>(First);
  8115. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8116. }
  8117. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8118. // { v = x; x++; }
  8119. // { v = x; x--; }
  8120. // { v = x; ++x; }
  8121. // { v = x; --x; }
  8122. // { v = x; x binop= expr; }
  8123. // { v = x; x = x binop expr; }
  8124. // { v = x; x = expr binop x; }
  8125. // Check that the first expression has form v = x.
  8126. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8127. llvm::FoldingSetNodeID XId, PossibleXId;
  8128. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8129. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8130. IsUpdateExprFound = XId == PossibleXId;
  8131. if (IsUpdateExprFound) {
  8132. V = BinOp->getLHS();
  8133. X = Checker.getX();
  8134. E = Checker.getExpr();
  8135. UE = Checker.getUpdateExpr();
  8136. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8137. IsPostfixUpdate = true;
  8138. }
  8139. }
  8140. if (!IsUpdateExprFound) {
  8141. IsUpdateExprFound = !Checker.checkStatement(First);
  8142. BinOp = nullptr;
  8143. if (IsUpdateExprFound) {
  8144. BinOp = dyn_cast<BinaryOperator>(Second);
  8145. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  8146. }
  8147. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  8148. // { x++; v = x; }
  8149. // { x--; v = x; }
  8150. // { ++x; v = x; }
  8151. // { --x; v = x; }
  8152. // { x binop= expr; v = x; }
  8153. // { x = x binop expr; v = x; }
  8154. // { x = expr binop x; v = x; }
  8155. // Check that the second expression has form v = x.
  8156. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  8157. llvm::FoldingSetNodeID XId, PossibleXId;
  8158. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  8159. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  8160. IsUpdateExprFound = XId == PossibleXId;
  8161. if (IsUpdateExprFound) {
  8162. V = BinOp->getLHS();
  8163. X = Checker.getX();
  8164. E = Checker.getExpr();
  8165. UE = Checker.getUpdateExpr();
  8166. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  8167. IsPostfixUpdate = false;
  8168. }
  8169. }
  8170. }
  8171. if (!IsUpdateExprFound) {
  8172. // { v = x; x = expr; }
  8173. auto *FirstExpr = dyn_cast<Expr>(First);
  8174. auto *SecondExpr = dyn_cast<Expr>(Second);
  8175. if (!FirstExpr || !SecondExpr ||
  8176. !(FirstExpr->isInstantiationDependent() ||
  8177. SecondExpr->isInstantiationDependent())) {
  8178. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  8179. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  8180. ErrorFound = NotAnAssignmentOp;
  8181. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  8182. : First->getBeginLoc();
  8183. NoteRange = ErrorRange = FirstBinOp
  8184. ? FirstBinOp->getSourceRange()
  8185. : SourceRange(ErrorLoc, ErrorLoc);
  8186. } else {
  8187. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  8188. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  8189. ErrorFound = NotAnAssignmentOp;
  8190. NoteLoc = ErrorLoc = SecondBinOp
  8191. ? SecondBinOp->getOperatorLoc()
  8192. : Second->getBeginLoc();
  8193. NoteRange = ErrorRange =
  8194. SecondBinOp ? SecondBinOp->getSourceRange()
  8195. : SourceRange(ErrorLoc, ErrorLoc);
  8196. } else {
  8197. Expr *PossibleXRHSInFirst =
  8198. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  8199. Expr *PossibleXLHSInSecond =
  8200. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  8201. llvm::FoldingSetNodeID X1Id, X2Id;
  8202. PossibleXRHSInFirst->Profile(X1Id, Context,
  8203. /*Canonical=*/true);
  8204. PossibleXLHSInSecond->Profile(X2Id, Context,
  8205. /*Canonical=*/true);
  8206. IsUpdateExprFound = X1Id == X2Id;
  8207. if (IsUpdateExprFound) {
  8208. V = FirstBinOp->getLHS();
  8209. X = SecondBinOp->getLHS();
  8210. E = SecondBinOp->getRHS();
  8211. UE = nullptr;
  8212. IsXLHSInRHSPart = false;
  8213. IsPostfixUpdate = true;
  8214. } else {
  8215. ErrorFound = NotASpecificExpression;
  8216. ErrorLoc = FirstBinOp->getExprLoc();
  8217. ErrorRange = FirstBinOp->getSourceRange();
  8218. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  8219. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  8220. }
  8221. }
  8222. }
  8223. }
  8224. }
  8225. } else {
  8226. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8227. NoteRange = ErrorRange =
  8228. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8229. ErrorFound = NotTwoSubstatements;
  8230. }
  8231. } else {
  8232. NoteLoc = ErrorLoc = Body->getBeginLoc();
  8233. NoteRange = ErrorRange =
  8234. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  8235. ErrorFound = NotACompoundStatement;
  8236. }
  8237. if (ErrorFound != NoError) {
  8238. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  8239. << ErrorRange;
  8240. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  8241. return StmtError();
  8242. }
  8243. if (CurContext->isDependentContext())
  8244. UE = V = E = X = nullptr;
  8245. }
  8246. }
  8247. setFunctionHasBranchProtectedScope();
  8248. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  8249. X, V, E, UE, IsXLHSInRHSPart,
  8250. IsPostfixUpdate);
  8251. }
  8252. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  8253. Stmt *AStmt,
  8254. SourceLocation StartLoc,
  8255. SourceLocation EndLoc) {
  8256. if (!AStmt)
  8257. return StmtError();
  8258. auto *CS = cast<CapturedStmt>(AStmt);
  8259. // 1.2.2 OpenMP Language Terminology
  8260. // Structured block - An executable statement with a single entry at the
  8261. // top and a single exit at the bottom.
  8262. // The point of exit cannot be a branch out of the structured block.
  8263. // longjmp() and throw() must not violate the entry/exit criteria.
  8264. CS->getCapturedDecl()->setNothrow();
  8265. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  8266. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8267. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8268. // 1.2.2 OpenMP Language Terminology
  8269. // Structured block - An executable statement with a single entry at the
  8270. // top and a single exit at the bottom.
  8271. // The point of exit cannot be a branch out of the structured block.
  8272. // longjmp() and throw() must not violate the entry/exit criteria.
  8273. CS->getCapturedDecl()->setNothrow();
  8274. }
  8275. // OpenMP [2.16, Nesting of Regions]
  8276. // If specified, a teams construct must be contained within a target
  8277. // construct. That target construct must contain no statements or directives
  8278. // outside of the teams construct.
  8279. if (DSAStack->hasInnerTeamsRegion()) {
  8280. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  8281. bool OMPTeamsFound = true;
  8282. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  8283. auto I = CS->body_begin();
  8284. while (I != CS->body_end()) {
  8285. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  8286. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  8287. OMPTeamsFound) {
  8288. OMPTeamsFound = false;
  8289. break;
  8290. }
  8291. ++I;
  8292. }
  8293. assert(I != CS->body_end() && "Not found statement");
  8294. S = *I;
  8295. } else {
  8296. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  8297. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  8298. }
  8299. if (!OMPTeamsFound) {
  8300. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  8301. Diag(DSAStack->getInnerTeamsRegionLoc(),
  8302. diag::note_omp_nested_teams_construct_here);
  8303. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  8304. << isa<OMPExecutableDirective>(S);
  8305. return StmtError();
  8306. }
  8307. }
  8308. setFunctionHasBranchProtectedScope();
  8309. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8310. }
  8311. StmtResult
  8312. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  8313. Stmt *AStmt, SourceLocation StartLoc,
  8314. SourceLocation EndLoc) {
  8315. if (!AStmt)
  8316. return StmtError();
  8317. auto *CS = cast<CapturedStmt>(AStmt);
  8318. // 1.2.2 OpenMP Language Terminology
  8319. // Structured block - An executable statement with a single entry at the
  8320. // top and a single exit at the bottom.
  8321. // The point of exit cannot be a branch out of the structured block.
  8322. // longjmp() and throw() must not violate the entry/exit criteria.
  8323. CS->getCapturedDecl()->setNothrow();
  8324. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  8325. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8326. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8327. // 1.2.2 OpenMP Language Terminology
  8328. // Structured block - An executable statement with a single entry at the
  8329. // top and a single exit at the bottom.
  8330. // The point of exit cannot be a branch out of the structured block.
  8331. // longjmp() and throw() must not violate the entry/exit criteria.
  8332. CS->getCapturedDecl()->setNothrow();
  8333. }
  8334. setFunctionHasBranchProtectedScope();
  8335. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8336. AStmt);
  8337. }
  8338. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  8339. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8340. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8341. if (!AStmt)
  8342. return StmtError();
  8343. auto *CS = cast<CapturedStmt>(AStmt);
  8344. // 1.2.2 OpenMP Language Terminology
  8345. // Structured block - An executable statement with a single entry at the
  8346. // top and a single exit at the bottom.
  8347. // The point of exit cannot be a branch out of the structured block.
  8348. // longjmp() and throw() must not violate the entry/exit criteria.
  8349. CS->getCapturedDecl()->setNothrow();
  8350. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8351. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8352. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8353. // 1.2.2 OpenMP Language Terminology
  8354. // Structured block - An executable statement with a single entry at the
  8355. // top and a single exit at the bottom.
  8356. // The point of exit cannot be a branch out of the structured block.
  8357. // longjmp() and throw() must not violate the entry/exit criteria.
  8358. CS->getCapturedDecl()->setNothrow();
  8359. }
  8360. OMPLoopDirective::HelperExprs B;
  8361. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8362. // define the nested loops number.
  8363. unsigned NestedLoopCount =
  8364. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  8365. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8366. VarsWithImplicitDSA, B);
  8367. if (NestedLoopCount == 0)
  8368. return StmtError();
  8369. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8370. "omp target parallel for loop exprs were not built");
  8371. if (!CurContext->isDependentContext()) {
  8372. // Finalize the clauses that need pre-built expressions for CodeGen.
  8373. for (OMPClause *C : Clauses) {
  8374. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8375. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8376. B.NumIterations, *this, CurScope,
  8377. DSAStack))
  8378. return StmtError();
  8379. }
  8380. }
  8381. setFunctionHasBranchProtectedScope();
  8382. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  8383. NestedLoopCount, Clauses, AStmt,
  8384. B, DSAStack->isCancelRegion());
  8385. }
  8386. /// Check for existence of a map clause in the list of clauses.
  8387. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  8388. const OpenMPClauseKind K) {
  8389. return llvm::any_of(
  8390. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  8391. }
  8392. template <typename... Params>
  8393. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  8394. const Params... ClauseTypes) {
  8395. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  8396. }
  8397. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  8398. Stmt *AStmt,
  8399. SourceLocation StartLoc,
  8400. SourceLocation EndLoc) {
  8401. if (!AStmt)
  8402. return StmtError();
  8403. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8404. // OpenMP [2.10.1, Restrictions, p. 97]
  8405. // At least one map clause must appear on the directive.
  8406. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  8407. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8408. << "'map' or 'use_device_ptr'"
  8409. << getOpenMPDirectiveName(OMPD_target_data);
  8410. return StmtError();
  8411. }
  8412. setFunctionHasBranchProtectedScope();
  8413. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8414. AStmt);
  8415. }
  8416. StmtResult
  8417. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  8418. SourceLocation StartLoc,
  8419. SourceLocation EndLoc, Stmt *AStmt) {
  8420. if (!AStmt)
  8421. return StmtError();
  8422. auto *CS = cast<CapturedStmt>(AStmt);
  8423. // 1.2.2 OpenMP Language Terminology
  8424. // Structured block - An executable statement with a single entry at the
  8425. // top and a single exit at the bottom.
  8426. // The point of exit cannot be a branch out of the structured block.
  8427. // longjmp() and throw() must not violate the entry/exit criteria.
  8428. CS->getCapturedDecl()->setNothrow();
  8429. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  8430. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8431. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8432. // 1.2.2 OpenMP Language Terminology
  8433. // Structured block - An executable statement with a single entry at the
  8434. // top and a single exit at the bottom.
  8435. // The point of exit cannot be a branch out of the structured block.
  8436. // longjmp() and throw() must not violate the entry/exit criteria.
  8437. CS->getCapturedDecl()->setNothrow();
  8438. }
  8439. // OpenMP [2.10.2, Restrictions, p. 99]
  8440. // At least one map clause must appear on the directive.
  8441. if (!hasClauses(Clauses, OMPC_map)) {
  8442. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8443. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  8444. return StmtError();
  8445. }
  8446. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8447. AStmt);
  8448. }
  8449. StmtResult
  8450. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  8451. SourceLocation StartLoc,
  8452. SourceLocation EndLoc, Stmt *AStmt) {
  8453. if (!AStmt)
  8454. return StmtError();
  8455. auto *CS = cast<CapturedStmt>(AStmt);
  8456. // 1.2.2 OpenMP Language Terminology
  8457. // Structured block - An executable statement with a single entry at the
  8458. // top and a single exit at the bottom.
  8459. // The point of exit cannot be a branch out of the structured block.
  8460. // longjmp() and throw() must not violate the entry/exit criteria.
  8461. CS->getCapturedDecl()->setNothrow();
  8462. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  8463. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8464. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8465. // 1.2.2 OpenMP Language Terminology
  8466. // Structured block - An executable statement with a single entry at the
  8467. // top and a single exit at the bottom.
  8468. // The point of exit cannot be a branch out of the structured block.
  8469. // longjmp() and throw() must not violate the entry/exit criteria.
  8470. CS->getCapturedDecl()->setNothrow();
  8471. }
  8472. // OpenMP [2.10.3, Restrictions, p. 102]
  8473. // At least one map clause must appear on the directive.
  8474. if (!hasClauses(Clauses, OMPC_map)) {
  8475. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  8476. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  8477. return StmtError();
  8478. }
  8479. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8480. AStmt);
  8481. }
  8482. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  8483. SourceLocation StartLoc,
  8484. SourceLocation EndLoc,
  8485. Stmt *AStmt) {
  8486. if (!AStmt)
  8487. return StmtError();
  8488. auto *CS = cast<CapturedStmt>(AStmt);
  8489. // 1.2.2 OpenMP Language Terminology
  8490. // Structured block - An executable statement with a single entry at the
  8491. // top and a single exit at the bottom.
  8492. // The point of exit cannot be a branch out of the structured block.
  8493. // longjmp() and throw() must not violate the entry/exit criteria.
  8494. CS->getCapturedDecl()->setNothrow();
  8495. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  8496. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8497. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8498. // 1.2.2 OpenMP Language Terminology
  8499. // Structured block - An executable statement with a single entry at the
  8500. // top and a single exit at the bottom.
  8501. // The point of exit cannot be a branch out of the structured block.
  8502. // longjmp() and throw() must not violate the entry/exit criteria.
  8503. CS->getCapturedDecl()->setNothrow();
  8504. }
  8505. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  8506. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  8507. return StmtError();
  8508. }
  8509. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8510. AStmt);
  8511. }
  8512. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  8513. Stmt *AStmt, SourceLocation StartLoc,
  8514. SourceLocation EndLoc) {
  8515. if (!AStmt)
  8516. return StmtError();
  8517. auto *CS = cast<CapturedStmt>(AStmt);
  8518. // 1.2.2 OpenMP Language Terminology
  8519. // Structured block - An executable statement with a single entry at the
  8520. // top and a single exit at the bottom.
  8521. // The point of exit cannot be a branch out of the structured block.
  8522. // longjmp() and throw() must not violate the entry/exit criteria.
  8523. CS->getCapturedDecl()->setNothrow();
  8524. setFunctionHasBranchProtectedScope();
  8525. DSAStack->setParentTeamsRegionLoc(StartLoc);
  8526. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  8527. }
  8528. StmtResult
  8529. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  8530. SourceLocation EndLoc,
  8531. OpenMPDirectiveKind CancelRegion) {
  8532. if (DSAStack->isParentNowaitRegion()) {
  8533. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  8534. return StmtError();
  8535. }
  8536. if (DSAStack->isParentOrderedRegion()) {
  8537. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  8538. return StmtError();
  8539. }
  8540. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  8541. CancelRegion);
  8542. }
  8543. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  8544. SourceLocation StartLoc,
  8545. SourceLocation EndLoc,
  8546. OpenMPDirectiveKind CancelRegion) {
  8547. if (DSAStack->isParentNowaitRegion()) {
  8548. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  8549. return StmtError();
  8550. }
  8551. if (DSAStack->isParentOrderedRegion()) {
  8552. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  8553. return StmtError();
  8554. }
  8555. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  8556. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  8557. CancelRegion);
  8558. }
  8559. static bool checkGrainsizeNumTasksClauses(Sema &S,
  8560. ArrayRef<OMPClause *> Clauses) {
  8561. const OMPClause *PrevClause = nullptr;
  8562. bool ErrorFound = false;
  8563. for (const OMPClause *C : Clauses) {
  8564. if (C->getClauseKind() == OMPC_grainsize ||
  8565. C->getClauseKind() == OMPC_num_tasks) {
  8566. if (!PrevClause)
  8567. PrevClause = C;
  8568. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  8569. S.Diag(C->getBeginLoc(),
  8570. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  8571. << getOpenMPClauseName(C->getClauseKind())
  8572. << getOpenMPClauseName(PrevClause->getClauseKind());
  8573. S.Diag(PrevClause->getBeginLoc(),
  8574. diag::note_omp_previous_grainsize_num_tasks)
  8575. << getOpenMPClauseName(PrevClause->getClauseKind());
  8576. ErrorFound = true;
  8577. }
  8578. }
  8579. }
  8580. return ErrorFound;
  8581. }
  8582. static bool checkReductionClauseWithNogroup(Sema &S,
  8583. ArrayRef<OMPClause *> Clauses) {
  8584. const OMPClause *ReductionClause = nullptr;
  8585. const OMPClause *NogroupClause = nullptr;
  8586. for (const OMPClause *C : Clauses) {
  8587. if (C->getClauseKind() == OMPC_reduction) {
  8588. ReductionClause = C;
  8589. if (NogroupClause)
  8590. break;
  8591. continue;
  8592. }
  8593. if (C->getClauseKind() == OMPC_nogroup) {
  8594. NogroupClause = C;
  8595. if (ReductionClause)
  8596. break;
  8597. continue;
  8598. }
  8599. }
  8600. if (ReductionClause && NogroupClause) {
  8601. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  8602. << SourceRange(NogroupClause->getBeginLoc(),
  8603. NogroupClause->getEndLoc());
  8604. return true;
  8605. }
  8606. return false;
  8607. }
  8608. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  8609. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8610. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8611. if (!AStmt)
  8612. return StmtError();
  8613. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8614. OMPLoopDirective::HelperExprs B;
  8615. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8616. // define the nested loops number.
  8617. unsigned NestedLoopCount =
  8618. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  8619. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8620. VarsWithImplicitDSA, B);
  8621. if (NestedLoopCount == 0)
  8622. return StmtError();
  8623. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8624. "omp for loop exprs were not built");
  8625. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8626. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8627. // not appear on the same taskloop directive.
  8628. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8629. return StmtError();
  8630. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8631. // If a reduction clause is present on the taskloop directive, the nogroup
  8632. // clause must not be specified.
  8633. if (checkReductionClauseWithNogroup(*this, Clauses))
  8634. return StmtError();
  8635. setFunctionHasBranchProtectedScope();
  8636. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8637. NestedLoopCount, Clauses, AStmt, B);
  8638. }
  8639. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  8640. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8641. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8642. if (!AStmt)
  8643. return StmtError();
  8644. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8645. OMPLoopDirective::HelperExprs B;
  8646. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8647. // define the nested loops number.
  8648. unsigned NestedLoopCount =
  8649. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  8650. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8651. VarsWithImplicitDSA, B);
  8652. if (NestedLoopCount == 0)
  8653. return StmtError();
  8654. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8655. "omp for loop exprs were not built");
  8656. if (!CurContext->isDependentContext()) {
  8657. // Finalize the clauses that need pre-built expressions for CodeGen.
  8658. for (OMPClause *C : Clauses) {
  8659. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8660. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8661. B.NumIterations, *this, CurScope,
  8662. DSAStack))
  8663. return StmtError();
  8664. }
  8665. }
  8666. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8667. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8668. // not appear on the same taskloop directive.
  8669. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8670. return StmtError();
  8671. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8672. // If a reduction clause is present on the taskloop directive, the nogroup
  8673. // clause must not be specified.
  8674. if (checkReductionClauseWithNogroup(*this, Clauses))
  8675. return StmtError();
  8676. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8677. return StmtError();
  8678. setFunctionHasBranchProtectedScope();
  8679. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  8680. NestedLoopCount, Clauses, AStmt, B);
  8681. }
  8682. StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
  8683. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8684. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8685. if (!AStmt)
  8686. return StmtError();
  8687. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8688. OMPLoopDirective::HelperExprs B;
  8689. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8690. // define the nested loops number.
  8691. unsigned NestedLoopCount =
  8692. checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
  8693. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  8694. VarsWithImplicitDSA, B);
  8695. if (NestedLoopCount == 0)
  8696. return StmtError();
  8697. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8698. "omp for loop exprs were not built");
  8699. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8700. // The grainsize clause and num_tasks clause are mutually exclusive and may
  8701. // not appear on the same taskloop directive.
  8702. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  8703. return StmtError();
  8704. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  8705. // If a reduction clause is present on the taskloop directive, the nogroup
  8706. // clause must not be specified.
  8707. if (checkReductionClauseWithNogroup(*this, Clauses))
  8708. return StmtError();
  8709. setFunctionHasBranchProtectedScope();
  8710. return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  8711. NestedLoopCount, Clauses, AStmt, B);
  8712. }
  8713. StmtResult Sema::ActOnOpenMPDistributeDirective(
  8714. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8715. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8716. if (!AStmt)
  8717. return StmtError();
  8718. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  8719. OMPLoopDirective::HelperExprs B;
  8720. // In presence of clause 'collapse' with number of loops, it will
  8721. // define the nested loops number.
  8722. unsigned NestedLoopCount =
  8723. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  8724. nullptr /*ordered not a clause on distribute*/, AStmt,
  8725. *this, *DSAStack, VarsWithImplicitDSA, B);
  8726. if (NestedLoopCount == 0)
  8727. return StmtError();
  8728. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8729. "omp for loop exprs were not built");
  8730. setFunctionHasBranchProtectedScope();
  8731. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  8732. NestedLoopCount, Clauses, AStmt, B);
  8733. }
  8734. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  8735. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8736. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8737. if (!AStmt)
  8738. return StmtError();
  8739. auto *CS = cast<CapturedStmt>(AStmt);
  8740. // 1.2.2 OpenMP Language Terminology
  8741. // Structured block - An executable statement with a single entry at the
  8742. // top and a single exit at the bottom.
  8743. // The point of exit cannot be a branch out of the structured block.
  8744. // longjmp() and throw() must not violate the entry/exit criteria.
  8745. CS->getCapturedDecl()->setNothrow();
  8746. for (int ThisCaptureLevel =
  8747. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  8748. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8749. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8750. // 1.2.2 OpenMP Language Terminology
  8751. // Structured block - An executable statement with a single entry at the
  8752. // top and a single exit at the bottom.
  8753. // The point of exit cannot be a branch out of the structured block.
  8754. // longjmp() and throw() must not violate the entry/exit criteria.
  8755. CS->getCapturedDecl()->setNothrow();
  8756. }
  8757. OMPLoopDirective::HelperExprs B;
  8758. // In presence of clause 'collapse' with number of loops, it will
  8759. // define the nested loops number.
  8760. unsigned NestedLoopCount = checkOpenMPLoop(
  8761. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8762. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8763. VarsWithImplicitDSA, B);
  8764. if (NestedLoopCount == 0)
  8765. return StmtError();
  8766. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8767. "omp for loop exprs were not built");
  8768. setFunctionHasBranchProtectedScope();
  8769. return OMPDistributeParallelForDirective::Create(
  8770. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8771. DSAStack->isCancelRegion());
  8772. }
  8773. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  8774. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8775. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8776. if (!AStmt)
  8777. return StmtError();
  8778. auto *CS = cast<CapturedStmt>(AStmt);
  8779. // 1.2.2 OpenMP Language Terminology
  8780. // Structured block - An executable statement with a single entry at the
  8781. // top and a single exit at the bottom.
  8782. // The point of exit cannot be a branch out of the structured block.
  8783. // longjmp() and throw() must not violate the entry/exit criteria.
  8784. CS->getCapturedDecl()->setNothrow();
  8785. for (int ThisCaptureLevel =
  8786. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  8787. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8788. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8789. // 1.2.2 OpenMP Language Terminology
  8790. // Structured block - An executable statement with a single entry at the
  8791. // top and a single exit at the bottom.
  8792. // The point of exit cannot be a branch out of the structured block.
  8793. // longjmp() and throw() must not violate the entry/exit criteria.
  8794. CS->getCapturedDecl()->setNothrow();
  8795. }
  8796. OMPLoopDirective::HelperExprs B;
  8797. // In presence of clause 'collapse' with number of loops, it will
  8798. // define the nested loops number.
  8799. unsigned NestedLoopCount = checkOpenMPLoop(
  8800. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8801. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8802. VarsWithImplicitDSA, B);
  8803. if (NestedLoopCount == 0)
  8804. return StmtError();
  8805. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8806. "omp for loop exprs were not built");
  8807. if (!CurContext->isDependentContext()) {
  8808. // Finalize the clauses that need pre-built expressions for CodeGen.
  8809. for (OMPClause *C : Clauses) {
  8810. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8811. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8812. B.NumIterations, *this, CurScope,
  8813. DSAStack))
  8814. return StmtError();
  8815. }
  8816. }
  8817. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8818. return StmtError();
  8819. setFunctionHasBranchProtectedScope();
  8820. return OMPDistributeParallelForSimdDirective::Create(
  8821. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8822. }
  8823. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  8824. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8825. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8826. if (!AStmt)
  8827. return StmtError();
  8828. auto *CS = cast<CapturedStmt>(AStmt);
  8829. // 1.2.2 OpenMP Language Terminology
  8830. // Structured block - An executable statement with a single entry at the
  8831. // top and a single exit at the bottom.
  8832. // The point of exit cannot be a branch out of the structured block.
  8833. // longjmp() and throw() must not violate the entry/exit criteria.
  8834. CS->getCapturedDecl()->setNothrow();
  8835. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  8836. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8837. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8838. // 1.2.2 OpenMP Language Terminology
  8839. // Structured block - An executable statement with a single entry at the
  8840. // top and a single exit at the bottom.
  8841. // The point of exit cannot be a branch out of the structured block.
  8842. // longjmp() and throw() must not violate the entry/exit criteria.
  8843. CS->getCapturedDecl()->setNothrow();
  8844. }
  8845. OMPLoopDirective::HelperExprs B;
  8846. // In presence of clause 'collapse' with number of loops, it will
  8847. // define the nested loops number.
  8848. unsigned NestedLoopCount =
  8849. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  8850. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8851. *DSAStack, VarsWithImplicitDSA, B);
  8852. if (NestedLoopCount == 0)
  8853. return StmtError();
  8854. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8855. "omp for loop exprs were not built");
  8856. if (!CurContext->isDependentContext()) {
  8857. // Finalize the clauses that need pre-built expressions for CodeGen.
  8858. for (OMPClause *C : Clauses) {
  8859. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8860. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8861. B.NumIterations, *this, CurScope,
  8862. DSAStack))
  8863. return StmtError();
  8864. }
  8865. }
  8866. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8867. return StmtError();
  8868. setFunctionHasBranchProtectedScope();
  8869. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  8870. NestedLoopCount, Clauses, AStmt, B);
  8871. }
  8872. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  8873. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8874. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8875. if (!AStmt)
  8876. return StmtError();
  8877. auto *CS = cast<CapturedStmt>(AStmt);
  8878. // 1.2.2 OpenMP Language Terminology
  8879. // Structured block - An executable statement with a single entry at the
  8880. // top and a single exit at the bottom.
  8881. // The point of exit cannot be a branch out of the structured block.
  8882. // longjmp() and throw() must not violate the entry/exit criteria.
  8883. CS->getCapturedDecl()->setNothrow();
  8884. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  8885. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8886. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8887. // 1.2.2 OpenMP Language Terminology
  8888. // Structured block - An executable statement with a single entry at the
  8889. // top and a single exit at the bottom.
  8890. // The point of exit cannot be a branch out of the structured block.
  8891. // longjmp() and throw() must not violate the entry/exit criteria.
  8892. CS->getCapturedDecl()->setNothrow();
  8893. }
  8894. OMPLoopDirective::HelperExprs B;
  8895. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  8896. // define the nested loops number.
  8897. unsigned NestedLoopCount = checkOpenMPLoop(
  8898. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  8899. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8900. VarsWithImplicitDSA, B);
  8901. if (NestedLoopCount == 0)
  8902. return StmtError();
  8903. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8904. "omp target parallel for simd loop exprs were not built");
  8905. if (!CurContext->isDependentContext()) {
  8906. // Finalize the clauses that need pre-built expressions for CodeGen.
  8907. for (OMPClause *C : Clauses) {
  8908. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8909. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8910. B.NumIterations, *this, CurScope,
  8911. DSAStack))
  8912. return StmtError();
  8913. }
  8914. }
  8915. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8916. return StmtError();
  8917. setFunctionHasBranchProtectedScope();
  8918. return OMPTargetParallelForSimdDirective::Create(
  8919. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8920. }
  8921. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  8922. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8923. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8924. if (!AStmt)
  8925. return StmtError();
  8926. auto *CS = cast<CapturedStmt>(AStmt);
  8927. // 1.2.2 OpenMP Language Terminology
  8928. // Structured block - An executable statement with a single entry at the
  8929. // top and a single exit at the bottom.
  8930. // The point of exit cannot be a branch out of the structured block.
  8931. // longjmp() and throw() must not violate the entry/exit criteria.
  8932. CS->getCapturedDecl()->setNothrow();
  8933. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  8934. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8935. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8936. // 1.2.2 OpenMP Language Terminology
  8937. // Structured block - An executable statement with a single entry at the
  8938. // top and a single exit at the bottom.
  8939. // The point of exit cannot be a branch out of the structured block.
  8940. // longjmp() and throw() must not violate the entry/exit criteria.
  8941. CS->getCapturedDecl()->setNothrow();
  8942. }
  8943. OMPLoopDirective::HelperExprs B;
  8944. // In presence of clause 'collapse' with number of loops, it will define the
  8945. // nested loops number.
  8946. unsigned NestedLoopCount =
  8947. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  8948. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  8949. VarsWithImplicitDSA, B);
  8950. if (NestedLoopCount == 0)
  8951. return StmtError();
  8952. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8953. "omp target simd loop exprs were not built");
  8954. if (!CurContext->isDependentContext()) {
  8955. // Finalize the clauses that need pre-built expressions for CodeGen.
  8956. for (OMPClause *C : Clauses) {
  8957. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8958. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8959. B.NumIterations, *this, CurScope,
  8960. DSAStack))
  8961. return StmtError();
  8962. }
  8963. }
  8964. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8965. return StmtError();
  8966. setFunctionHasBranchProtectedScope();
  8967. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  8968. NestedLoopCount, Clauses, AStmt, B);
  8969. }
  8970. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  8971. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8972. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8973. if (!AStmt)
  8974. return StmtError();
  8975. auto *CS = cast<CapturedStmt>(AStmt);
  8976. // 1.2.2 OpenMP Language Terminology
  8977. // Structured block - An executable statement with a single entry at the
  8978. // top and a single exit at the bottom.
  8979. // The point of exit cannot be a branch out of the structured block.
  8980. // longjmp() and throw() must not violate the entry/exit criteria.
  8981. CS->getCapturedDecl()->setNothrow();
  8982. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  8983. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8984. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8985. // 1.2.2 OpenMP Language Terminology
  8986. // Structured block - An executable statement with a single entry at the
  8987. // top and a single exit at the bottom.
  8988. // The point of exit cannot be a branch out of the structured block.
  8989. // longjmp() and throw() must not violate the entry/exit criteria.
  8990. CS->getCapturedDecl()->setNothrow();
  8991. }
  8992. OMPLoopDirective::HelperExprs B;
  8993. // In presence of clause 'collapse' with number of loops, it will
  8994. // define the nested loops number.
  8995. unsigned NestedLoopCount =
  8996. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  8997. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8998. *DSAStack, VarsWithImplicitDSA, B);
  8999. if (NestedLoopCount == 0)
  9000. return StmtError();
  9001. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9002. "omp teams distribute loop exprs were not built");
  9003. setFunctionHasBranchProtectedScope();
  9004. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9005. return OMPTeamsDistributeDirective::Create(
  9006. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9007. }
  9008. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  9009. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9010. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9011. if (!AStmt)
  9012. return StmtError();
  9013. auto *CS = cast<CapturedStmt>(AStmt);
  9014. // 1.2.2 OpenMP Language Terminology
  9015. // Structured block - An executable statement with a single entry at the
  9016. // top and a single exit at the bottom.
  9017. // The point of exit cannot be a branch out of the structured block.
  9018. // longjmp() and throw() must not violate the entry/exit criteria.
  9019. CS->getCapturedDecl()->setNothrow();
  9020. for (int ThisCaptureLevel =
  9021. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  9022. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9023. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9024. // 1.2.2 OpenMP Language Terminology
  9025. // Structured block - An executable statement with a single entry at the
  9026. // top and a single exit at the bottom.
  9027. // The point of exit cannot be a branch out of the structured block.
  9028. // longjmp() and throw() must not violate the entry/exit criteria.
  9029. CS->getCapturedDecl()->setNothrow();
  9030. }
  9031. OMPLoopDirective::HelperExprs B;
  9032. // In presence of clause 'collapse' with number of loops, it will
  9033. // define the nested loops number.
  9034. unsigned NestedLoopCount = checkOpenMPLoop(
  9035. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9036. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9037. VarsWithImplicitDSA, B);
  9038. if (NestedLoopCount == 0)
  9039. return StmtError();
  9040. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9041. "omp teams distribute simd loop exprs were not built");
  9042. if (!CurContext->isDependentContext()) {
  9043. // Finalize the clauses that need pre-built expressions for CodeGen.
  9044. for (OMPClause *C : Clauses) {
  9045. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9046. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9047. B.NumIterations, *this, CurScope,
  9048. DSAStack))
  9049. return StmtError();
  9050. }
  9051. }
  9052. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9053. return StmtError();
  9054. setFunctionHasBranchProtectedScope();
  9055. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9056. return OMPTeamsDistributeSimdDirective::Create(
  9057. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9058. }
  9059. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  9060. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9061. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9062. if (!AStmt)
  9063. return StmtError();
  9064. auto *CS = cast<CapturedStmt>(AStmt);
  9065. // 1.2.2 OpenMP Language Terminology
  9066. // Structured block - An executable statement with a single entry at the
  9067. // top and a single exit at the bottom.
  9068. // The point of exit cannot be a branch out of the structured block.
  9069. // longjmp() and throw() must not violate the entry/exit criteria.
  9070. CS->getCapturedDecl()->setNothrow();
  9071. for (int ThisCaptureLevel =
  9072. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  9073. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9074. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9075. // 1.2.2 OpenMP Language Terminology
  9076. // Structured block - An executable statement with a single entry at the
  9077. // top and a single exit at the bottom.
  9078. // The point of exit cannot be a branch out of the structured block.
  9079. // longjmp() and throw() must not violate the entry/exit criteria.
  9080. CS->getCapturedDecl()->setNothrow();
  9081. }
  9082. OMPLoopDirective::HelperExprs B;
  9083. // In presence of clause 'collapse' with number of loops, it will
  9084. // define the nested loops number.
  9085. unsigned NestedLoopCount = checkOpenMPLoop(
  9086. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  9087. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9088. VarsWithImplicitDSA, B);
  9089. if (NestedLoopCount == 0)
  9090. return StmtError();
  9091. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9092. "omp for loop exprs were not built");
  9093. if (!CurContext->isDependentContext()) {
  9094. // Finalize the clauses that need pre-built expressions for CodeGen.
  9095. for (OMPClause *C : Clauses) {
  9096. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9097. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9098. B.NumIterations, *this, CurScope,
  9099. DSAStack))
  9100. return StmtError();
  9101. }
  9102. }
  9103. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9104. return StmtError();
  9105. setFunctionHasBranchProtectedScope();
  9106. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9107. return OMPTeamsDistributeParallelForSimdDirective::Create(
  9108. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9109. }
  9110. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  9111. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9112. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9113. if (!AStmt)
  9114. return StmtError();
  9115. auto *CS = cast<CapturedStmt>(AStmt);
  9116. // 1.2.2 OpenMP Language Terminology
  9117. // Structured block - An executable statement with a single entry at the
  9118. // top and a single exit at the bottom.
  9119. // The point of exit cannot be a branch out of the structured block.
  9120. // longjmp() and throw() must not violate the entry/exit criteria.
  9121. CS->getCapturedDecl()->setNothrow();
  9122. for (int ThisCaptureLevel =
  9123. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  9124. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9125. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9126. // 1.2.2 OpenMP Language Terminology
  9127. // Structured block - An executable statement with a single entry at the
  9128. // top and a single exit at the bottom.
  9129. // The point of exit cannot be a branch out of the structured block.
  9130. // longjmp() and throw() must not violate the entry/exit criteria.
  9131. CS->getCapturedDecl()->setNothrow();
  9132. }
  9133. OMPLoopDirective::HelperExprs B;
  9134. // In presence of clause 'collapse' with number of loops, it will
  9135. // define the nested loops number.
  9136. unsigned NestedLoopCount = checkOpenMPLoop(
  9137. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9138. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9139. VarsWithImplicitDSA, B);
  9140. if (NestedLoopCount == 0)
  9141. return StmtError();
  9142. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9143. "omp for loop exprs were not built");
  9144. setFunctionHasBranchProtectedScope();
  9145. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9146. return OMPTeamsDistributeParallelForDirective::Create(
  9147. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9148. DSAStack->isCancelRegion());
  9149. }
  9150. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  9151. Stmt *AStmt,
  9152. SourceLocation StartLoc,
  9153. SourceLocation EndLoc) {
  9154. if (!AStmt)
  9155. return StmtError();
  9156. auto *CS = cast<CapturedStmt>(AStmt);
  9157. // 1.2.2 OpenMP Language Terminology
  9158. // Structured block - An executable statement with a single entry at the
  9159. // top and a single exit at the bottom.
  9160. // The point of exit cannot be a branch out of the structured block.
  9161. // longjmp() and throw() must not violate the entry/exit criteria.
  9162. CS->getCapturedDecl()->setNothrow();
  9163. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  9164. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9165. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9166. // 1.2.2 OpenMP Language Terminology
  9167. // Structured block - An executable statement with a single entry at the
  9168. // top and a single exit at the bottom.
  9169. // The point of exit cannot be a branch out of the structured block.
  9170. // longjmp() and throw() must not violate the entry/exit criteria.
  9171. CS->getCapturedDecl()->setNothrow();
  9172. }
  9173. setFunctionHasBranchProtectedScope();
  9174. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  9175. AStmt);
  9176. }
  9177. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  9178. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9179. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9180. if (!AStmt)
  9181. return StmtError();
  9182. auto *CS = cast<CapturedStmt>(AStmt);
  9183. // 1.2.2 OpenMP Language Terminology
  9184. // Structured block - An executable statement with a single entry at the
  9185. // top and a single exit at the bottom.
  9186. // The point of exit cannot be a branch out of the structured block.
  9187. // longjmp() and throw() must not violate the entry/exit criteria.
  9188. CS->getCapturedDecl()->setNothrow();
  9189. for (int ThisCaptureLevel =
  9190. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  9191. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9192. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9193. // 1.2.2 OpenMP Language Terminology
  9194. // Structured block - An executable statement with a single entry at the
  9195. // top and a single exit at the bottom.
  9196. // The point of exit cannot be a branch out of the structured block.
  9197. // longjmp() and throw() must not violate the entry/exit criteria.
  9198. CS->getCapturedDecl()->setNothrow();
  9199. }
  9200. OMPLoopDirective::HelperExprs B;
  9201. // In presence of clause 'collapse' with number of loops, it will
  9202. // define the nested loops number.
  9203. unsigned NestedLoopCount = checkOpenMPLoop(
  9204. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  9205. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9206. VarsWithImplicitDSA, B);
  9207. if (NestedLoopCount == 0)
  9208. return StmtError();
  9209. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9210. "omp target teams distribute loop exprs were not built");
  9211. setFunctionHasBranchProtectedScope();
  9212. return OMPTargetTeamsDistributeDirective::Create(
  9213. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9214. }
  9215. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  9216. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9217. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9218. if (!AStmt)
  9219. return StmtError();
  9220. auto *CS = cast<CapturedStmt>(AStmt);
  9221. // 1.2.2 OpenMP Language Terminology
  9222. // Structured block - An executable statement with a single entry at the
  9223. // top and a single exit at the bottom.
  9224. // The point of exit cannot be a branch out of the structured block.
  9225. // longjmp() and throw() must not violate the entry/exit criteria.
  9226. CS->getCapturedDecl()->setNothrow();
  9227. for (int ThisCaptureLevel =
  9228. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  9229. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9230. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9231. // 1.2.2 OpenMP Language Terminology
  9232. // Structured block - An executable statement with a single entry at the
  9233. // top and a single exit at the bottom.
  9234. // The point of exit cannot be a branch out of the structured block.
  9235. // longjmp() and throw() must not violate the entry/exit criteria.
  9236. CS->getCapturedDecl()->setNothrow();
  9237. }
  9238. OMPLoopDirective::HelperExprs B;
  9239. // In presence of clause 'collapse' with number of loops, it will
  9240. // define the nested loops number.
  9241. unsigned NestedLoopCount = checkOpenMPLoop(
  9242. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  9243. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9244. VarsWithImplicitDSA, B);
  9245. if (NestedLoopCount == 0)
  9246. return StmtError();
  9247. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9248. "omp target teams distribute parallel for loop exprs were not built");
  9249. if (!CurContext->isDependentContext()) {
  9250. // Finalize the clauses that need pre-built expressions for CodeGen.
  9251. for (OMPClause *C : Clauses) {
  9252. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9253. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9254. B.NumIterations, *this, CurScope,
  9255. DSAStack))
  9256. return StmtError();
  9257. }
  9258. }
  9259. setFunctionHasBranchProtectedScope();
  9260. return OMPTargetTeamsDistributeParallelForDirective::Create(
  9261. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9262. DSAStack->isCancelRegion());
  9263. }
  9264. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  9265. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9266. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9267. if (!AStmt)
  9268. return StmtError();
  9269. auto *CS = cast<CapturedStmt>(AStmt);
  9270. // 1.2.2 OpenMP Language Terminology
  9271. // Structured block - An executable statement with a single entry at the
  9272. // top and a single exit at the bottom.
  9273. // The point of exit cannot be a branch out of the structured block.
  9274. // longjmp() and throw() must not violate the entry/exit criteria.
  9275. CS->getCapturedDecl()->setNothrow();
  9276. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  9277. OMPD_target_teams_distribute_parallel_for_simd);
  9278. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9279. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9280. // 1.2.2 OpenMP Language Terminology
  9281. // Structured block - An executable statement with a single entry at the
  9282. // top and a single exit at the bottom.
  9283. // The point of exit cannot be a branch out of the structured block.
  9284. // longjmp() and throw() must not violate the entry/exit criteria.
  9285. CS->getCapturedDecl()->setNothrow();
  9286. }
  9287. OMPLoopDirective::HelperExprs B;
  9288. // In presence of clause 'collapse' with number of loops, it will
  9289. // define the nested loops number.
  9290. unsigned NestedLoopCount =
  9291. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  9292. getCollapseNumberExpr(Clauses),
  9293. nullptr /*ordered not a clause on distribute*/, CS, *this,
  9294. *DSAStack, VarsWithImplicitDSA, B);
  9295. if (NestedLoopCount == 0)
  9296. return StmtError();
  9297. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9298. "omp target teams distribute parallel for simd loop exprs were not "
  9299. "built");
  9300. if (!CurContext->isDependentContext()) {
  9301. // Finalize the clauses that need pre-built expressions for CodeGen.
  9302. for (OMPClause *C : Clauses) {
  9303. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9304. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9305. B.NumIterations, *this, CurScope,
  9306. DSAStack))
  9307. return StmtError();
  9308. }
  9309. }
  9310. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9311. return StmtError();
  9312. setFunctionHasBranchProtectedScope();
  9313. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  9314. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9315. }
  9316. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  9317. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9318. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9319. if (!AStmt)
  9320. return StmtError();
  9321. auto *CS = cast<CapturedStmt>(AStmt);
  9322. // 1.2.2 OpenMP Language Terminology
  9323. // Structured block - An executable statement with a single entry at the
  9324. // top and a single exit at the bottom.
  9325. // The point of exit cannot be a branch out of the structured block.
  9326. // longjmp() and throw() must not violate the entry/exit criteria.
  9327. CS->getCapturedDecl()->setNothrow();
  9328. for (int ThisCaptureLevel =
  9329. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  9330. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9331. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9332. // 1.2.2 OpenMP Language Terminology
  9333. // Structured block - An executable statement with a single entry at the
  9334. // top and a single exit at the bottom.
  9335. // The point of exit cannot be a branch out of the structured block.
  9336. // longjmp() and throw() must not violate the entry/exit criteria.
  9337. CS->getCapturedDecl()->setNothrow();
  9338. }
  9339. OMPLoopDirective::HelperExprs B;
  9340. // In presence of clause 'collapse' with number of loops, it will
  9341. // define the nested loops number.
  9342. unsigned NestedLoopCount = checkOpenMPLoop(
  9343. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  9344. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  9345. VarsWithImplicitDSA, B);
  9346. if (NestedLoopCount == 0)
  9347. return StmtError();
  9348. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9349. "omp target teams distribute simd loop exprs were not built");
  9350. if (!CurContext->isDependentContext()) {
  9351. // Finalize the clauses that need pre-built expressions for CodeGen.
  9352. for (OMPClause *C : Clauses) {
  9353. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9354. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9355. B.NumIterations, *this, CurScope,
  9356. DSAStack))
  9357. return StmtError();
  9358. }
  9359. }
  9360. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9361. return StmtError();
  9362. setFunctionHasBranchProtectedScope();
  9363. return OMPTargetTeamsDistributeSimdDirective::Create(
  9364. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9365. }
  9366. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  9367. SourceLocation StartLoc,
  9368. SourceLocation LParenLoc,
  9369. SourceLocation EndLoc) {
  9370. OMPClause *Res = nullptr;
  9371. switch (Kind) {
  9372. case OMPC_final:
  9373. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  9374. break;
  9375. case OMPC_num_threads:
  9376. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9377. break;
  9378. case OMPC_safelen:
  9379. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9380. break;
  9381. case OMPC_simdlen:
  9382. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  9383. break;
  9384. case OMPC_allocator:
  9385. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  9386. break;
  9387. case OMPC_collapse:
  9388. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  9389. break;
  9390. case OMPC_ordered:
  9391. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  9392. break;
  9393. case OMPC_device:
  9394. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  9395. break;
  9396. case OMPC_num_teams:
  9397. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  9398. break;
  9399. case OMPC_thread_limit:
  9400. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  9401. break;
  9402. case OMPC_priority:
  9403. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  9404. break;
  9405. case OMPC_grainsize:
  9406. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  9407. break;
  9408. case OMPC_num_tasks:
  9409. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  9410. break;
  9411. case OMPC_hint:
  9412. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  9413. break;
  9414. case OMPC_if:
  9415. case OMPC_default:
  9416. case OMPC_proc_bind:
  9417. case OMPC_schedule:
  9418. case OMPC_private:
  9419. case OMPC_firstprivate:
  9420. case OMPC_lastprivate:
  9421. case OMPC_shared:
  9422. case OMPC_reduction:
  9423. case OMPC_task_reduction:
  9424. case OMPC_in_reduction:
  9425. case OMPC_linear:
  9426. case OMPC_aligned:
  9427. case OMPC_copyin:
  9428. case OMPC_copyprivate:
  9429. case OMPC_nowait:
  9430. case OMPC_untied:
  9431. case OMPC_mergeable:
  9432. case OMPC_threadprivate:
  9433. case OMPC_allocate:
  9434. case OMPC_flush:
  9435. case OMPC_read:
  9436. case OMPC_write:
  9437. case OMPC_update:
  9438. case OMPC_capture:
  9439. case OMPC_seq_cst:
  9440. case OMPC_depend:
  9441. case OMPC_threads:
  9442. case OMPC_simd:
  9443. case OMPC_map:
  9444. case OMPC_nogroup:
  9445. case OMPC_dist_schedule:
  9446. case OMPC_defaultmap:
  9447. case OMPC_unknown:
  9448. case OMPC_uniform:
  9449. case OMPC_to:
  9450. case OMPC_from:
  9451. case OMPC_use_device_ptr:
  9452. case OMPC_is_device_ptr:
  9453. case OMPC_unified_address:
  9454. case OMPC_unified_shared_memory:
  9455. case OMPC_reverse_offload:
  9456. case OMPC_dynamic_allocators:
  9457. case OMPC_atomic_default_mem_order:
  9458. case OMPC_device_type:
  9459. case OMPC_match:
  9460. llvm_unreachable("Clause is not allowed.");
  9461. }
  9462. return Res;
  9463. }
  9464. // An OpenMP directive such as 'target parallel' has two captured regions:
  9465. // for the 'target' and 'parallel' respectively. This function returns
  9466. // the region in which to capture expressions associated with a clause.
  9467. // A return value of OMPD_unknown signifies that the expression should not
  9468. // be captured.
  9469. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  9470. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  9471. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  9472. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  9473. switch (CKind) {
  9474. case OMPC_if:
  9475. switch (DKind) {
  9476. case OMPD_target_parallel:
  9477. case OMPD_target_parallel_for:
  9478. case OMPD_target_parallel_for_simd:
  9479. // If this clause applies to the nested 'parallel' region, capture within
  9480. // the 'target' region, otherwise do not capture.
  9481. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9482. CaptureRegion = OMPD_target;
  9483. break;
  9484. case OMPD_target_teams_distribute_parallel_for:
  9485. case OMPD_target_teams_distribute_parallel_for_simd:
  9486. // If this clause applies to the nested 'parallel' region, capture within
  9487. // the 'teams' region, otherwise do not capture.
  9488. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  9489. CaptureRegion = OMPD_teams;
  9490. break;
  9491. case OMPD_teams_distribute_parallel_for:
  9492. case OMPD_teams_distribute_parallel_for_simd:
  9493. CaptureRegion = OMPD_teams;
  9494. break;
  9495. case OMPD_target_update:
  9496. case OMPD_target_enter_data:
  9497. case OMPD_target_exit_data:
  9498. CaptureRegion = OMPD_task;
  9499. break;
  9500. case OMPD_cancel:
  9501. case OMPD_parallel:
  9502. case OMPD_parallel_sections:
  9503. case OMPD_parallel_for:
  9504. case OMPD_parallel_for_simd:
  9505. case OMPD_target:
  9506. case OMPD_target_simd:
  9507. case OMPD_target_teams:
  9508. case OMPD_target_teams_distribute:
  9509. case OMPD_target_teams_distribute_simd:
  9510. case OMPD_distribute_parallel_for:
  9511. case OMPD_distribute_parallel_for_simd:
  9512. case OMPD_task:
  9513. case OMPD_taskloop:
  9514. case OMPD_taskloop_simd:
  9515. case OMPD_master_taskloop:
  9516. case OMPD_target_data:
  9517. // Do not capture if-clause expressions.
  9518. break;
  9519. case OMPD_threadprivate:
  9520. case OMPD_allocate:
  9521. case OMPD_taskyield:
  9522. case OMPD_barrier:
  9523. case OMPD_taskwait:
  9524. case OMPD_cancellation_point:
  9525. case OMPD_flush:
  9526. case OMPD_declare_reduction:
  9527. case OMPD_declare_mapper:
  9528. case OMPD_declare_simd:
  9529. case OMPD_declare_variant:
  9530. case OMPD_declare_target:
  9531. case OMPD_end_declare_target:
  9532. case OMPD_teams:
  9533. case OMPD_simd:
  9534. case OMPD_for:
  9535. case OMPD_for_simd:
  9536. case OMPD_sections:
  9537. case OMPD_section:
  9538. case OMPD_single:
  9539. case OMPD_master:
  9540. case OMPD_critical:
  9541. case OMPD_taskgroup:
  9542. case OMPD_distribute:
  9543. case OMPD_ordered:
  9544. case OMPD_atomic:
  9545. case OMPD_distribute_simd:
  9546. case OMPD_teams_distribute:
  9547. case OMPD_teams_distribute_simd:
  9548. case OMPD_requires:
  9549. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  9550. case OMPD_unknown:
  9551. llvm_unreachable("Unknown OpenMP directive");
  9552. }
  9553. break;
  9554. case OMPC_num_threads:
  9555. switch (DKind) {
  9556. case OMPD_target_parallel:
  9557. case OMPD_target_parallel_for:
  9558. case OMPD_target_parallel_for_simd:
  9559. CaptureRegion = OMPD_target;
  9560. break;
  9561. case OMPD_teams_distribute_parallel_for:
  9562. case OMPD_teams_distribute_parallel_for_simd:
  9563. case OMPD_target_teams_distribute_parallel_for:
  9564. case OMPD_target_teams_distribute_parallel_for_simd:
  9565. CaptureRegion = OMPD_teams;
  9566. break;
  9567. case OMPD_parallel:
  9568. case OMPD_parallel_sections:
  9569. case OMPD_parallel_for:
  9570. case OMPD_parallel_for_simd:
  9571. case OMPD_distribute_parallel_for:
  9572. case OMPD_distribute_parallel_for_simd:
  9573. // Do not capture num_threads-clause expressions.
  9574. break;
  9575. case OMPD_target_data:
  9576. case OMPD_target_enter_data:
  9577. case OMPD_target_exit_data:
  9578. case OMPD_target_update:
  9579. case OMPD_target:
  9580. case OMPD_target_simd:
  9581. case OMPD_target_teams:
  9582. case OMPD_target_teams_distribute:
  9583. case OMPD_target_teams_distribute_simd:
  9584. case OMPD_cancel:
  9585. case OMPD_task:
  9586. case OMPD_taskloop:
  9587. case OMPD_taskloop_simd:
  9588. case OMPD_master_taskloop:
  9589. case OMPD_threadprivate:
  9590. case OMPD_allocate:
  9591. case OMPD_taskyield:
  9592. case OMPD_barrier:
  9593. case OMPD_taskwait:
  9594. case OMPD_cancellation_point:
  9595. case OMPD_flush:
  9596. case OMPD_declare_reduction:
  9597. case OMPD_declare_mapper:
  9598. case OMPD_declare_simd:
  9599. case OMPD_declare_variant:
  9600. case OMPD_declare_target:
  9601. case OMPD_end_declare_target:
  9602. case OMPD_teams:
  9603. case OMPD_simd:
  9604. case OMPD_for:
  9605. case OMPD_for_simd:
  9606. case OMPD_sections:
  9607. case OMPD_section:
  9608. case OMPD_single:
  9609. case OMPD_master:
  9610. case OMPD_critical:
  9611. case OMPD_taskgroup:
  9612. case OMPD_distribute:
  9613. case OMPD_ordered:
  9614. case OMPD_atomic:
  9615. case OMPD_distribute_simd:
  9616. case OMPD_teams_distribute:
  9617. case OMPD_teams_distribute_simd:
  9618. case OMPD_requires:
  9619. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  9620. case OMPD_unknown:
  9621. llvm_unreachable("Unknown OpenMP directive");
  9622. }
  9623. break;
  9624. case OMPC_num_teams:
  9625. switch (DKind) {
  9626. case OMPD_target_teams:
  9627. case OMPD_target_teams_distribute:
  9628. case OMPD_target_teams_distribute_simd:
  9629. case OMPD_target_teams_distribute_parallel_for:
  9630. case OMPD_target_teams_distribute_parallel_for_simd:
  9631. CaptureRegion = OMPD_target;
  9632. break;
  9633. case OMPD_teams_distribute_parallel_for:
  9634. case OMPD_teams_distribute_parallel_for_simd:
  9635. case OMPD_teams:
  9636. case OMPD_teams_distribute:
  9637. case OMPD_teams_distribute_simd:
  9638. // Do not capture num_teams-clause expressions.
  9639. break;
  9640. case OMPD_distribute_parallel_for:
  9641. case OMPD_distribute_parallel_for_simd:
  9642. case OMPD_task:
  9643. case OMPD_taskloop:
  9644. case OMPD_taskloop_simd:
  9645. case OMPD_master_taskloop:
  9646. case OMPD_target_data:
  9647. case OMPD_target_enter_data:
  9648. case OMPD_target_exit_data:
  9649. case OMPD_target_update:
  9650. case OMPD_cancel:
  9651. case OMPD_parallel:
  9652. case OMPD_parallel_sections:
  9653. case OMPD_parallel_for:
  9654. case OMPD_parallel_for_simd:
  9655. case OMPD_target:
  9656. case OMPD_target_simd:
  9657. case OMPD_target_parallel:
  9658. case OMPD_target_parallel_for:
  9659. case OMPD_target_parallel_for_simd:
  9660. case OMPD_threadprivate:
  9661. case OMPD_allocate:
  9662. case OMPD_taskyield:
  9663. case OMPD_barrier:
  9664. case OMPD_taskwait:
  9665. case OMPD_cancellation_point:
  9666. case OMPD_flush:
  9667. case OMPD_declare_reduction:
  9668. case OMPD_declare_mapper:
  9669. case OMPD_declare_simd:
  9670. case OMPD_declare_variant:
  9671. case OMPD_declare_target:
  9672. case OMPD_end_declare_target:
  9673. case OMPD_simd:
  9674. case OMPD_for:
  9675. case OMPD_for_simd:
  9676. case OMPD_sections:
  9677. case OMPD_section:
  9678. case OMPD_single:
  9679. case OMPD_master:
  9680. case OMPD_critical:
  9681. case OMPD_taskgroup:
  9682. case OMPD_distribute:
  9683. case OMPD_ordered:
  9684. case OMPD_atomic:
  9685. case OMPD_distribute_simd:
  9686. case OMPD_requires:
  9687. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9688. case OMPD_unknown:
  9689. llvm_unreachable("Unknown OpenMP directive");
  9690. }
  9691. break;
  9692. case OMPC_thread_limit:
  9693. switch (DKind) {
  9694. case OMPD_target_teams:
  9695. case OMPD_target_teams_distribute:
  9696. case OMPD_target_teams_distribute_simd:
  9697. case OMPD_target_teams_distribute_parallel_for:
  9698. case OMPD_target_teams_distribute_parallel_for_simd:
  9699. CaptureRegion = OMPD_target;
  9700. break;
  9701. case OMPD_teams_distribute_parallel_for:
  9702. case OMPD_teams_distribute_parallel_for_simd:
  9703. case OMPD_teams:
  9704. case OMPD_teams_distribute:
  9705. case OMPD_teams_distribute_simd:
  9706. // Do not capture thread_limit-clause expressions.
  9707. break;
  9708. case OMPD_distribute_parallel_for:
  9709. case OMPD_distribute_parallel_for_simd:
  9710. case OMPD_task:
  9711. case OMPD_taskloop:
  9712. case OMPD_taskloop_simd:
  9713. case OMPD_master_taskloop:
  9714. case OMPD_target_data:
  9715. case OMPD_target_enter_data:
  9716. case OMPD_target_exit_data:
  9717. case OMPD_target_update:
  9718. case OMPD_cancel:
  9719. case OMPD_parallel:
  9720. case OMPD_parallel_sections:
  9721. case OMPD_parallel_for:
  9722. case OMPD_parallel_for_simd:
  9723. case OMPD_target:
  9724. case OMPD_target_simd:
  9725. case OMPD_target_parallel:
  9726. case OMPD_target_parallel_for:
  9727. case OMPD_target_parallel_for_simd:
  9728. case OMPD_threadprivate:
  9729. case OMPD_allocate:
  9730. case OMPD_taskyield:
  9731. case OMPD_barrier:
  9732. case OMPD_taskwait:
  9733. case OMPD_cancellation_point:
  9734. case OMPD_flush:
  9735. case OMPD_declare_reduction:
  9736. case OMPD_declare_mapper:
  9737. case OMPD_declare_simd:
  9738. case OMPD_declare_variant:
  9739. case OMPD_declare_target:
  9740. case OMPD_end_declare_target:
  9741. case OMPD_simd:
  9742. case OMPD_for:
  9743. case OMPD_for_simd:
  9744. case OMPD_sections:
  9745. case OMPD_section:
  9746. case OMPD_single:
  9747. case OMPD_master:
  9748. case OMPD_critical:
  9749. case OMPD_taskgroup:
  9750. case OMPD_distribute:
  9751. case OMPD_ordered:
  9752. case OMPD_atomic:
  9753. case OMPD_distribute_simd:
  9754. case OMPD_requires:
  9755. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  9756. case OMPD_unknown:
  9757. llvm_unreachable("Unknown OpenMP directive");
  9758. }
  9759. break;
  9760. case OMPC_schedule:
  9761. switch (DKind) {
  9762. case OMPD_parallel_for:
  9763. case OMPD_parallel_for_simd:
  9764. case OMPD_distribute_parallel_for:
  9765. case OMPD_distribute_parallel_for_simd:
  9766. case OMPD_teams_distribute_parallel_for:
  9767. case OMPD_teams_distribute_parallel_for_simd:
  9768. case OMPD_target_parallel_for:
  9769. case OMPD_target_parallel_for_simd:
  9770. case OMPD_target_teams_distribute_parallel_for:
  9771. case OMPD_target_teams_distribute_parallel_for_simd:
  9772. CaptureRegion = OMPD_parallel;
  9773. break;
  9774. case OMPD_for:
  9775. case OMPD_for_simd:
  9776. // Do not capture schedule-clause expressions.
  9777. break;
  9778. case OMPD_task:
  9779. case OMPD_taskloop:
  9780. case OMPD_taskloop_simd:
  9781. case OMPD_master_taskloop:
  9782. case OMPD_target_data:
  9783. case OMPD_target_enter_data:
  9784. case OMPD_target_exit_data:
  9785. case OMPD_target_update:
  9786. case OMPD_teams:
  9787. case OMPD_teams_distribute:
  9788. case OMPD_teams_distribute_simd:
  9789. case OMPD_target_teams_distribute:
  9790. case OMPD_target_teams_distribute_simd:
  9791. case OMPD_target:
  9792. case OMPD_target_simd:
  9793. case OMPD_target_parallel:
  9794. case OMPD_cancel:
  9795. case OMPD_parallel:
  9796. case OMPD_parallel_sections:
  9797. case OMPD_threadprivate:
  9798. case OMPD_allocate:
  9799. case OMPD_taskyield:
  9800. case OMPD_barrier:
  9801. case OMPD_taskwait:
  9802. case OMPD_cancellation_point:
  9803. case OMPD_flush:
  9804. case OMPD_declare_reduction:
  9805. case OMPD_declare_mapper:
  9806. case OMPD_declare_simd:
  9807. case OMPD_declare_variant:
  9808. case OMPD_declare_target:
  9809. case OMPD_end_declare_target:
  9810. case OMPD_simd:
  9811. case OMPD_sections:
  9812. case OMPD_section:
  9813. case OMPD_single:
  9814. case OMPD_master:
  9815. case OMPD_critical:
  9816. case OMPD_taskgroup:
  9817. case OMPD_distribute:
  9818. case OMPD_ordered:
  9819. case OMPD_atomic:
  9820. case OMPD_distribute_simd:
  9821. case OMPD_target_teams:
  9822. case OMPD_requires:
  9823. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9824. case OMPD_unknown:
  9825. llvm_unreachable("Unknown OpenMP directive");
  9826. }
  9827. break;
  9828. case OMPC_dist_schedule:
  9829. switch (DKind) {
  9830. case OMPD_teams_distribute_parallel_for:
  9831. case OMPD_teams_distribute_parallel_for_simd:
  9832. case OMPD_teams_distribute:
  9833. case OMPD_teams_distribute_simd:
  9834. case OMPD_target_teams_distribute_parallel_for:
  9835. case OMPD_target_teams_distribute_parallel_for_simd:
  9836. case OMPD_target_teams_distribute:
  9837. case OMPD_target_teams_distribute_simd:
  9838. CaptureRegion = OMPD_teams;
  9839. break;
  9840. case OMPD_distribute_parallel_for:
  9841. case OMPD_distribute_parallel_for_simd:
  9842. case OMPD_distribute:
  9843. case OMPD_distribute_simd:
  9844. // Do not capture thread_limit-clause expressions.
  9845. break;
  9846. case OMPD_parallel_for:
  9847. case OMPD_parallel_for_simd:
  9848. case OMPD_target_parallel_for_simd:
  9849. case OMPD_target_parallel_for:
  9850. case OMPD_task:
  9851. case OMPD_taskloop:
  9852. case OMPD_taskloop_simd:
  9853. case OMPD_master_taskloop:
  9854. case OMPD_target_data:
  9855. case OMPD_target_enter_data:
  9856. case OMPD_target_exit_data:
  9857. case OMPD_target_update:
  9858. case OMPD_teams:
  9859. case OMPD_target:
  9860. case OMPD_target_simd:
  9861. case OMPD_target_parallel:
  9862. case OMPD_cancel:
  9863. case OMPD_parallel:
  9864. case OMPD_parallel_sections:
  9865. case OMPD_threadprivate:
  9866. case OMPD_allocate:
  9867. case OMPD_taskyield:
  9868. case OMPD_barrier:
  9869. case OMPD_taskwait:
  9870. case OMPD_cancellation_point:
  9871. case OMPD_flush:
  9872. case OMPD_declare_reduction:
  9873. case OMPD_declare_mapper:
  9874. case OMPD_declare_simd:
  9875. case OMPD_declare_variant:
  9876. case OMPD_declare_target:
  9877. case OMPD_end_declare_target:
  9878. case OMPD_simd:
  9879. case OMPD_for:
  9880. case OMPD_for_simd:
  9881. case OMPD_sections:
  9882. case OMPD_section:
  9883. case OMPD_single:
  9884. case OMPD_master:
  9885. case OMPD_critical:
  9886. case OMPD_taskgroup:
  9887. case OMPD_ordered:
  9888. case OMPD_atomic:
  9889. case OMPD_target_teams:
  9890. case OMPD_requires:
  9891. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  9892. case OMPD_unknown:
  9893. llvm_unreachable("Unknown OpenMP directive");
  9894. }
  9895. break;
  9896. case OMPC_device:
  9897. switch (DKind) {
  9898. case OMPD_target_update:
  9899. case OMPD_target_enter_data:
  9900. case OMPD_target_exit_data:
  9901. case OMPD_target:
  9902. case OMPD_target_simd:
  9903. case OMPD_target_teams:
  9904. case OMPD_target_parallel:
  9905. case OMPD_target_teams_distribute:
  9906. case OMPD_target_teams_distribute_simd:
  9907. case OMPD_target_parallel_for:
  9908. case OMPD_target_parallel_for_simd:
  9909. case OMPD_target_teams_distribute_parallel_for:
  9910. case OMPD_target_teams_distribute_parallel_for_simd:
  9911. CaptureRegion = OMPD_task;
  9912. break;
  9913. case OMPD_target_data:
  9914. // Do not capture device-clause expressions.
  9915. break;
  9916. case OMPD_teams_distribute_parallel_for:
  9917. case OMPD_teams_distribute_parallel_for_simd:
  9918. case OMPD_teams:
  9919. case OMPD_teams_distribute:
  9920. case OMPD_teams_distribute_simd:
  9921. case OMPD_distribute_parallel_for:
  9922. case OMPD_distribute_parallel_for_simd:
  9923. case OMPD_task:
  9924. case OMPD_taskloop:
  9925. case OMPD_taskloop_simd:
  9926. case OMPD_master_taskloop:
  9927. case OMPD_cancel:
  9928. case OMPD_parallel:
  9929. case OMPD_parallel_sections:
  9930. case OMPD_parallel_for:
  9931. case OMPD_parallel_for_simd:
  9932. case OMPD_threadprivate:
  9933. case OMPD_allocate:
  9934. case OMPD_taskyield:
  9935. case OMPD_barrier:
  9936. case OMPD_taskwait:
  9937. case OMPD_cancellation_point:
  9938. case OMPD_flush:
  9939. case OMPD_declare_reduction:
  9940. case OMPD_declare_mapper:
  9941. case OMPD_declare_simd:
  9942. case OMPD_declare_variant:
  9943. case OMPD_declare_target:
  9944. case OMPD_end_declare_target:
  9945. case OMPD_simd:
  9946. case OMPD_for:
  9947. case OMPD_for_simd:
  9948. case OMPD_sections:
  9949. case OMPD_section:
  9950. case OMPD_single:
  9951. case OMPD_master:
  9952. case OMPD_critical:
  9953. case OMPD_taskgroup:
  9954. case OMPD_distribute:
  9955. case OMPD_ordered:
  9956. case OMPD_atomic:
  9957. case OMPD_distribute_simd:
  9958. case OMPD_requires:
  9959. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  9960. case OMPD_unknown:
  9961. llvm_unreachable("Unknown OpenMP directive");
  9962. }
  9963. break;
  9964. case OMPC_firstprivate:
  9965. case OMPC_lastprivate:
  9966. case OMPC_reduction:
  9967. case OMPC_task_reduction:
  9968. case OMPC_in_reduction:
  9969. case OMPC_linear:
  9970. case OMPC_default:
  9971. case OMPC_proc_bind:
  9972. case OMPC_final:
  9973. case OMPC_safelen:
  9974. case OMPC_simdlen:
  9975. case OMPC_allocator:
  9976. case OMPC_collapse:
  9977. case OMPC_private:
  9978. case OMPC_shared:
  9979. case OMPC_aligned:
  9980. case OMPC_copyin:
  9981. case OMPC_copyprivate:
  9982. case OMPC_ordered:
  9983. case OMPC_nowait:
  9984. case OMPC_untied:
  9985. case OMPC_mergeable:
  9986. case OMPC_threadprivate:
  9987. case OMPC_allocate:
  9988. case OMPC_flush:
  9989. case OMPC_read:
  9990. case OMPC_write:
  9991. case OMPC_update:
  9992. case OMPC_capture:
  9993. case OMPC_seq_cst:
  9994. case OMPC_depend:
  9995. case OMPC_threads:
  9996. case OMPC_simd:
  9997. case OMPC_map:
  9998. case OMPC_priority:
  9999. case OMPC_grainsize:
  10000. case OMPC_nogroup:
  10001. case OMPC_num_tasks:
  10002. case OMPC_hint:
  10003. case OMPC_defaultmap:
  10004. case OMPC_unknown:
  10005. case OMPC_uniform:
  10006. case OMPC_to:
  10007. case OMPC_from:
  10008. case OMPC_use_device_ptr:
  10009. case OMPC_is_device_ptr:
  10010. case OMPC_unified_address:
  10011. case OMPC_unified_shared_memory:
  10012. case OMPC_reverse_offload:
  10013. case OMPC_dynamic_allocators:
  10014. case OMPC_atomic_default_mem_order:
  10015. case OMPC_device_type:
  10016. case OMPC_match:
  10017. llvm_unreachable("Unexpected OpenMP clause.");
  10018. }
  10019. return CaptureRegion;
  10020. }
  10021. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  10022. Expr *Condition, SourceLocation StartLoc,
  10023. SourceLocation LParenLoc,
  10024. SourceLocation NameModifierLoc,
  10025. SourceLocation ColonLoc,
  10026. SourceLocation EndLoc) {
  10027. Expr *ValExpr = Condition;
  10028. Stmt *HelperValStmt = nullptr;
  10029. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  10030. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10031. !Condition->isInstantiationDependent() &&
  10032. !Condition->containsUnexpandedParameterPack()) {
  10033. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10034. if (Val.isInvalid())
  10035. return nullptr;
  10036. ValExpr = Val.get();
  10037. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10038. CaptureRegion =
  10039. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  10040. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10041. ValExpr = MakeFullExpr(ValExpr).get();
  10042. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10043. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10044. HelperValStmt = buildPreInits(Context, Captures);
  10045. }
  10046. }
  10047. return new (Context)
  10048. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  10049. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  10050. }
  10051. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  10052. SourceLocation StartLoc,
  10053. SourceLocation LParenLoc,
  10054. SourceLocation EndLoc) {
  10055. Expr *ValExpr = Condition;
  10056. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  10057. !Condition->isInstantiationDependent() &&
  10058. !Condition->containsUnexpandedParameterPack()) {
  10059. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  10060. if (Val.isInvalid())
  10061. return nullptr;
  10062. ValExpr = MakeFullExpr(Val.get()).get();
  10063. }
  10064. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  10065. }
  10066. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  10067. Expr *Op) {
  10068. if (!Op)
  10069. return ExprError();
  10070. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  10071. public:
  10072. IntConvertDiagnoser()
  10073. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  10074. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  10075. QualType T) override {
  10076. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  10077. }
  10078. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  10079. QualType T) override {
  10080. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  10081. }
  10082. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  10083. QualType T,
  10084. QualType ConvTy) override {
  10085. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  10086. }
  10087. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  10088. QualType ConvTy) override {
  10089. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10090. << ConvTy->isEnumeralType() << ConvTy;
  10091. }
  10092. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  10093. QualType T) override {
  10094. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  10095. }
  10096. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  10097. QualType ConvTy) override {
  10098. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  10099. << ConvTy->isEnumeralType() << ConvTy;
  10100. }
  10101. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  10102. QualType) override {
  10103. llvm_unreachable("conversion functions are permitted");
  10104. }
  10105. } ConvertDiagnoser;
  10106. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  10107. }
  10108. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  10109. OpenMPClauseKind CKind,
  10110. bool StrictlyPositive) {
  10111. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  10112. !ValExpr->isInstantiationDependent()) {
  10113. SourceLocation Loc = ValExpr->getExprLoc();
  10114. ExprResult Value =
  10115. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  10116. if (Value.isInvalid())
  10117. return false;
  10118. ValExpr = Value.get();
  10119. // The expression must evaluate to a non-negative integer value.
  10120. llvm::APSInt Result;
  10121. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  10122. Result.isSigned() &&
  10123. !((!StrictlyPositive && Result.isNonNegative()) ||
  10124. (StrictlyPositive && Result.isStrictlyPositive()))) {
  10125. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  10126. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10127. << ValExpr->getSourceRange();
  10128. return false;
  10129. }
  10130. }
  10131. return true;
  10132. }
  10133. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  10134. SourceLocation StartLoc,
  10135. SourceLocation LParenLoc,
  10136. SourceLocation EndLoc) {
  10137. Expr *ValExpr = NumThreads;
  10138. Stmt *HelperValStmt = nullptr;
  10139. // OpenMP [2.5, Restrictions]
  10140. // The num_threads expression must evaluate to a positive integer value.
  10141. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  10142. /*StrictlyPositive=*/true))
  10143. return nullptr;
  10144. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10145. OpenMPDirectiveKind CaptureRegion =
  10146. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  10147. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10148. ValExpr = MakeFullExpr(ValExpr).get();
  10149. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10150. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10151. HelperValStmt = buildPreInits(Context, Captures);
  10152. }
  10153. return new (Context) OMPNumThreadsClause(
  10154. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  10155. }
  10156. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  10157. OpenMPClauseKind CKind,
  10158. bool StrictlyPositive) {
  10159. if (!E)
  10160. return ExprError();
  10161. if (E->isValueDependent() || E->isTypeDependent() ||
  10162. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  10163. return E;
  10164. llvm::APSInt Result;
  10165. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  10166. if (ICE.isInvalid())
  10167. return ExprError();
  10168. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  10169. (!StrictlyPositive && !Result.isNonNegative())) {
  10170. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  10171. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  10172. << E->getSourceRange();
  10173. return ExprError();
  10174. }
  10175. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  10176. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  10177. << E->getSourceRange();
  10178. return ExprError();
  10179. }
  10180. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  10181. DSAStack->setAssociatedLoops(Result.getExtValue());
  10182. else if (CKind == OMPC_ordered)
  10183. DSAStack->setAssociatedLoops(Result.getExtValue());
  10184. return ICE;
  10185. }
  10186. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  10187. SourceLocation LParenLoc,
  10188. SourceLocation EndLoc) {
  10189. // OpenMP [2.8.1, simd construct, Description]
  10190. // The parameter of the safelen clause must be a constant
  10191. // positive integer expression.
  10192. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  10193. if (Safelen.isInvalid())
  10194. return nullptr;
  10195. return new (Context)
  10196. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  10197. }
  10198. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  10199. SourceLocation LParenLoc,
  10200. SourceLocation EndLoc) {
  10201. // OpenMP [2.8.1, simd construct, Description]
  10202. // The parameter of the simdlen clause must be a constant
  10203. // positive integer expression.
  10204. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  10205. if (Simdlen.isInvalid())
  10206. return nullptr;
  10207. return new (Context)
  10208. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  10209. }
  10210. /// Tries to find omp_allocator_handle_t type.
  10211. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  10212. DSAStackTy *Stack) {
  10213. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  10214. if (!OMPAllocatorHandleT.isNull())
  10215. return true;
  10216. // Build the predefined allocator expressions.
  10217. bool ErrorFound = false;
  10218. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  10219. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  10220. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  10221. StringRef Allocator =
  10222. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  10223. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  10224. auto *VD = dyn_cast_or_null<ValueDecl>(
  10225. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  10226. if (!VD) {
  10227. ErrorFound = true;
  10228. break;
  10229. }
  10230. QualType AllocatorType =
  10231. VD->getType().getNonLValueExprType(S.getASTContext());
  10232. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  10233. if (!Res.isUsable()) {
  10234. ErrorFound = true;
  10235. break;
  10236. }
  10237. if (OMPAllocatorHandleT.isNull())
  10238. OMPAllocatorHandleT = AllocatorType;
  10239. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  10240. ErrorFound = true;
  10241. break;
  10242. }
  10243. Stack->setAllocator(AllocatorKind, Res.get());
  10244. }
  10245. if (ErrorFound) {
  10246. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  10247. return false;
  10248. }
  10249. OMPAllocatorHandleT.addConst();
  10250. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  10251. return true;
  10252. }
  10253. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  10254. SourceLocation LParenLoc,
  10255. SourceLocation EndLoc) {
  10256. // OpenMP [2.11.3, allocate Directive, Description]
  10257. // allocator is an expression of omp_allocator_handle_t type.
  10258. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  10259. return nullptr;
  10260. ExprResult Allocator = DefaultLvalueConversion(A);
  10261. if (Allocator.isInvalid())
  10262. return nullptr;
  10263. Allocator = PerformImplicitConversion(Allocator.get(),
  10264. DSAStack->getOMPAllocatorHandleT(),
  10265. Sema::AA_Initializing,
  10266. /*AllowExplicit=*/true);
  10267. if (Allocator.isInvalid())
  10268. return nullptr;
  10269. return new (Context)
  10270. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  10271. }
  10272. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  10273. SourceLocation StartLoc,
  10274. SourceLocation LParenLoc,
  10275. SourceLocation EndLoc) {
  10276. // OpenMP [2.7.1, loop construct, Description]
  10277. // OpenMP [2.8.1, simd construct, Description]
  10278. // OpenMP [2.9.6, distribute construct, Description]
  10279. // The parameter of the collapse clause must be a constant
  10280. // positive integer expression.
  10281. ExprResult NumForLoopsResult =
  10282. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  10283. if (NumForLoopsResult.isInvalid())
  10284. return nullptr;
  10285. return new (Context)
  10286. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  10287. }
  10288. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  10289. SourceLocation EndLoc,
  10290. SourceLocation LParenLoc,
  10291. Expr *NumForLoops) {
  10292. // OpenMP [2.7.1, loop construct, Description]
  10293. // OpenMP [2.8.1, simd construct, Description]
  10294. // OpenMP [2.9.6, distribute construct, Description]
  10295. // The parameter of the ordered clause must be a constant
  10296. // positive integer expression if any.
  10297. if (NumForLoops && LParenLoc.isValid()) {
  10298. ExprResult NumForLoopsResult =
  10299. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  10300. if (NumForLoopsResult.isInvalid())
  10301. return nullptr;
  10302. NumForLoops = NumForLoopsResult.get();
  10303. } else {
  10304. NumForLoops = nullptr;
  10305. }
  10306. auto *Clause = OMPOrderedClause::Create(
  10307. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  10308. StartLoc, LParenLoc, EndLoc);
  10309. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  10310. return Clause;
  10311. }
  10312. OMPClause *Sema::ActOnOpenMPSimpleClause(
  10313. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  10314. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10315. OMPClause *Res = nullptr;
  10316. switch (Kind) {
  10317. case OMPC_default:
  10318. Res =
  10319. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  10320. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10321. break;
  10322. case OMPC_proc_bind:
  10323. Res = ActOnOpenMPProcBindClause(
  10324. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  10325. LParenLoc, EndLoc);
  10326. break;
  10327. case OMPC_atomic_default_mem_order:
  10328. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  10329. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  10330. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  10331. break;
  10332. case OMPC_if:
  10333. case OMPC_final:
  10334. case OMPC_num_threads:
  10335. case OMPC_safelen:
  10336. case OMPC_simdlen:
  10337. case OMPC_allocator:
  10338. case OMPC_collapse:
  10339. case OMPC_schedule:
  10340. case OMPC_private:
  10341. case OMPC_firstprivate:
  10342. case OMPC_lastprivate:
  10343. case OMPC_shared:
  10344. case OMPC_reduction:
  10345. case OMPC_task_reduction:
  10346. case OMPC_in_reduction:
  10347. case OMPC_linear:
  10348. case OMPC_aligned:
  10349. case OMPC_copyin:
  10350. case OMPC_copyprivate:
  10351. case OMPC_ordered:
  10352. case OMPC_nowait:
  10353. case OMPC_untied:
  10354. case OMPC_mergeable:
  10355. case OMPC_threadprivate:
  10356. case OMPC_allocate:
  10357. case OMPC_flush:
  10358. case OMPC_read:
  10359. case OMPC_write:
  10360. case OMPC_update:
  10361. case OMPC_capture:
  10362. case OMPC_seq_cst:
  10363. case OMPC_depend:
  10364. case OMPC_device:
  10365. case OMPC_threads:
  10366. case OMPC_simd:
  10367. case OMPC_map:
  10368. case OMPC_num_teams:
  10369. case OMPC_thread_limit:
  10370. case OMPC_priority:
  10371. case OMPC_grainsize:
  10372. case OMPC_nogroup:
  10373. case OMPC_num_tasks:
  10374. case OMPC_hint:
  10375. case OMPC_dist_schedule:
  10376. case OMPC_defaultmap:
  10377. case OMPC_unknown:
  10378. case OMPC_uniform:
  10379. case OMPC_to:
  10380. case OMPC_from:
  10381. case OMPC_use_device_ptr:
  10382. case OMPC_is_device_ptr:
  10383. case OMPC_unified_address:
  10384. case OMPC_unified_shared_memory:
  10385. case OMPC_reverse_offload:
  10386. case OMPC_dynamic_allocators:
  10387. case OMPC_device_type:
  10388. case OMPC_match:
  10389. llvm_unreachable("Clause is not allowed.");
  10390. }
  10391. return Res;
  10392. }
  10393. static std::string
  10394. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  10395. ArrayRef<unsigned> Exclude = llvm::None) {
  10396. SmallString<256> Buffer;
  10397. llvm::raw_svector_ostream Out(Buffer);
  10398. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  10399. unsigned Skipped = Exclude.size();
  10400. auto S = Exclude.begin(), E = Exclude.end();
  10401. for (unsigned I = First; I < Last; ++I) {
  10402. if (std::find(S, E, I) != E) {
  10403. --Skipped;
  10404. continue;
  10405. }
  10406. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  10407. if (I == Bound - Skipped)
  10408. Out << " or ";
  10409. else if (I != Bound + 1 - Skipped)
  10410. Out << ", ";
  10411. }
  10412. return Out.str();
  10413. }
  10414. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  10415. SourceLocation KindKwLoc,
  10416. SourceLocation StartLoc,
  10417. SourceLocation LParenLoc,
  10418. SourceLocation EndLoc) {
  10419. if (Kind == OMPC_DEFAULT_unknown) {
  10420. static_assert(OMPC_DEFAULT_unknown > 0,
  10421. "OMPC_DEFAULT_unknown not greater than 0");
  10422. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10423. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  10424. /*Last=*/OMPC_DEFAULT_unknown)
  10425. << getOpenMPClauseName(OMPC_default);
  10426. return nullptr;
  10427. }
  10428. switch (Kind) {
  10429. case OMPC_DEFAULT_none:
  10430. DSAStack->setDefaultDSANone(KindKwLoc);
  10431. break;
  10432. case OMPC_DEFAULT_shared:
  10433. DSAStack->setDefaultDSAShared(KindKwLoc);
  10434. break;
  10435. case OMPC_DEFAULT_unknown:
  10436. llvm_unreachable("Clause kind is not allowed.");
  10437. break;
  10438. }
  10439. return new (Context)
  10440. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10441. }
  10442. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  10443. SourceLocation KindKwLoc,
  10444. SourceLocation StartLoc,
  10445. SourceLocation LParenLoc,
  10446. SourceLocation EndLoc) {
  10447. if (Kind == OMPC_PROC_BIND_unknown) {
  10448. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10449. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  10450. /*Last=*/OMPC_PROC_BIND_unknown)
  10451. << getOpenMPClauseName(OMPC_proc_bind);
  10452. return nullptr;
  10453. }
  10454. return new (Context)
  10455. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  10456. }
  10457. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  10458. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  10459. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  10460. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  10461. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  10462. << getListOfPossibleValues(
  10463. OMPC_atomic_default_mem_order, /*First=*/0,
  10464. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  10465. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  10466. return nullptr;
  10467. }
  10468. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  10469. LParenLoc, EndLoc);
  10470. }
  10471. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  10472. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  10473. SourceLocation StartLoc, SourceLocation LParenLoc,
  10474. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  10475. SourceLocation EndLoc) {
  10476. OMPClause *Res = nullptr;
  10477. switch (Kind) {
  10478. case OMPC_schedule:
  10479. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  10480. assert(Argument.size() == NumberOfElements &&
  10481. ArgumentLoc.size() == NumberOfElements);
  10482. Res = ActOnOpenMPScheduleClause(
  10483. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  10484. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  10485. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  10486. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  10487. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  10488. break;
  10489. case OMPC_if:
  10490. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  10491. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  10492. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  10493. DelimLoc, EndLoc);
  10494. break;
  10495. case OMPC_dist_schedule:
  10496. Res = ActOnOpenMPDistScheduleClause(
  10497. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  10498. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  10499. break;
  10500. case OMPC_defaultmap:
  10501. enum { Modifier, DefaultmapKind };
  10502. Res = ActOnOpenMPDefaultmapClause(
  10503. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  10504. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  10505. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  10506. EndLoc);
  10507. break;
  10508. case OMPC_final:
  10509. case OMPC_num_threads:
  10510. case OMPC_safelen:
  10511. case OMPC_simdlen:
  10512. case OMPC_allocator:
  10513. case OMPC_collapse:
  10514. case OMPC_default:
  10515. case OMPC_proc_bind:
  10516. case OMPC_private:
  10517. case OMPC_firstprivate:
  10518. case OMPC_lastprivate:
  10519. case OMPC_shared:
  10520. case OMPC_reduction:
  10521. case OMPC_task_reduction:
  10522. case OMPC_in_reduction:
  10523. case OMPC_linear:
  10524. case OMPC_aligned:
  10525. case OMPC_copyin:
  10526. case OMPC_copyprivate:
  10527. case OMPC_ordered:
  10528. case OMPC_nowait:
  10529. case OMPC_untied:
  10530. case OMPC_mergeable:
  10531. case OMPC_threadprivate:
  10532. case OMPC_allocate:
  10533. case OMPC_flush:
  10534. case OMPC_read:
  10535. case OMPC_write:
  10536. case OMPC_update:
  10537. case OMPC_capture:
  10538. case OMPC_seq_cst:
  10539. case OMPC_depend:
  10540. case OMPC_device:
  10541. case OMPC_threads:
  10542. case OMPC_simd:
  10543. case OMPC_map:
  10544. case OMPC_num_teams:
  10545. case OMPC_thread_limit:
  10546. case OMPC_priority:
  10547. case OMPC_grainsize:
  10548. case OMPC_nogroup:
  10549. case OMPC_num_tasks:
  10550. case OMPC_hint:
  10551. case OMPC_unknown:
  10552. case OMPC_uniform:
  10553. case OMPC_to:
  10554. case OMPC_from:
  10555. case OMPC_use_device_ptr:
  10556. case OMPC_is_device_ptr:
  10557. case OMPC_unified_address:
  10558. case OMPC_unified_shared_memory:
  10559. case OMPC_reverse_offload:
  10560. case OMPC_dynamic_allocators:
  10561. case OMPC_atomic_default_mem_order:
  10562. case OMPC_device_type:
  10563. case OMPC_match:
  10564. llvm_unreachable("Clause is not allowed.");
  10565. }
  10566. return Res;
  10567. }
  10568. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  10569. OpenMPScheduleClauseModifier M2,
  10570. SourceLocation M1Loc, SourceLocation M2Loc) {
  10571. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  10572. SmallVector<unsigned, 2> Excluded;
  10573. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  10574. Excluded.push_back(M2);
  10575. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  10576. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  10577. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  10578. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  10579. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  10580. << getListOfPossibleValues(OMPC_schedule,
  10581. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  10582. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10583. Excluded)
  10584. << getOpenMPClauseName(OMPC_schedule);
  10585. return true;
  10586. }
  10587. return false;
  10588. }
  10589. OMPClause *Sema::ActOnOpenMPScheduleClause(
  10590. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  10591. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  10592. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  10593. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  10594. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  10595. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  10596. return nullptr;
  10597. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10598. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  10599. // but not both.
  10600. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  10601. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  10602. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  10603. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  10604. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  10605. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  10606. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  10607. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  10608. return nullptr;
  10609. }
  10610. if (Kind == OMPC_SCHEDULE_unknown) {
  10611. std::string Values;
  10612. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  10613. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  10614. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10615. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  10616. Exclude);
  10617. } else {
  10618. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  10619. /*Last=*/OMPC_SCHEDULE_unknown);
  10620. }
  10621. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  10622. << Values << getOpenMPClauseName(OMPC_schedule);
  10623. return nullptr;
  10624. }
  10625. // OpenMP, 2.7.1, Loop Construct, Restrictions
  10626. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  10627. // schedule(guided).
  10628. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  10629. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  10630. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  10631. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  10632. diag::err_omp_schedule_nonmonotonic_static);
  10633. return nullptr;
  10634. }
  10635. Expr *ValExpr = ChunkSize;
  10636. Stmt *HelperValStmt = nullptr;
  10637. if (ChunkSize) {
  10638. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  10639. !ChunkSize->isInstantiationDependent() &&
  10640. !ChunkSize->containsUnexpandedParameterPack()) {
  10641. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  10642. ExprResult Val =
  10643. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  10644. if (Val.isInvalid())
  10645. return nullptr;
  10646. ValExpr = Val.get();
  10647. // OpenMP [2.7.1, Restrictions]
  10648. // chunk_size must be a loop invariant integer expression with a positive
  10649. // value.
  10650. llvm::APSInt Result;
  10651. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  10652. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  10653. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  10654. << "schedule" << 1 << ChunkSize->getSourceRange();
  10655. return nullptr;
  10656. }
  10657. } else if (getOpenMPCaptureRegionForClause(
  10658. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  10659. OMPD_unknown &&
  10660. !CurContext->isDependentContext()) {
  10661. ValExpr = MakeFullExpr(ValExpr).get();
  10662. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  10663. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10664. HelperValStmt = buildPreInits(Context, Captures);
  10665. }
  10666. }
  10667. }
  10668. return new (Context)
  10669. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  10670. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  10671. }
  10672. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  10673. SourceLocation StartLoc,
  10674. SourceLocation EndLoc) {
  10675. OMPClause *Res = nullptr;
  10676. switch (Kind) {
  10677. case OMPC_ordered:
  10678. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  10679. break;
  10680. case OMPC_nowait:
  10681. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  10682. break;
  10683. case OMPC_untied:
  10684. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  10685. break;
  10686. case OMPC_mergeable:
  10687. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  10688. break;
  10689. case OMPC_read:
  10690. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  10691. break;
  10692. case OMPC_write:
  10693. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  10694. break;
  10695. case OMPC_update:
  10696. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  10697. break;
  10698. case OMPC_capture:
  10699. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  10700. break;
  10701. case OMPC_seq_cst:
  10702. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  10703. break;
  10704. case OMPC_threads:
  10705. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  10706. break;
  10707. case OMPC_simd:
  10708. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  10709. break;
  10710. case OMPC_nogroup:
  10711. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  10712. break;
  10713. case OMPC_unified_address:
  10714. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  10715. break;
  10716. case OMPC_unified_shared_memory:
  10717. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10718. break;
  10719. case OMPC_reverse_offload:
  10720. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  10721. break;
  10722. case OMPC_dynamic_allocators:
  10723. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10724. break;
  10725. case OMPC_if:
  10726. case OMPC_final:
  10727. case OMPC_num_threads:
  10728. case OMPC_safelen:
  10729. case OMPC_simdlen:
  10730. case OMPC_allocator:
  10731. case OMPC_collapse:
  10732. case OMPC_schedule:
  10733. case OMPC_private:
  10734. case OMPC_firstprivate:
  10735. case OMPC_lastprivate:
  10736. case OMPC_shared:
  10737. case OMPC_reduction:
  10738. case OMPC_task_reduction:
  10739. case OMPC_in_reduction:
  10740. case OMPC_linear:
  10741. case OMPC_aligned:
  10742. case OMPC_copyin:
  10743. case OMPC_copyprivate:
  10744. case OMPC_default:
  10745. case OMPC_proc_bind:
  10746. case OMPC_threadprivate:
  10747. case OMPC_allocate:
  10748. case OMPC_flush:
  10749. case OMPC_depend:
  10750. case OMPC_device:
  10751. case OMPC_map:
  10752. case OMPC_num_teams:
  10753. case OMPC_thread_limit:
  10754. case OMPC_priority:
  10755. case OMPC_grainsize:
  10756. case OMPC_num_tasks:
  10757. case OMPC_hint:
  10758. case OMPC_dist_schedule:
  10759. case OMPC_defaultmap:
  10760. case OMPC_unknown:
  10761. case OMPC_uniform:
  10762. case OMPC_to:
  10763. case OMPC_from:
  10764. case OMPC_use_device_ptr:
  10765. case OMPC_is_device_ptr:
  10766. case OMPC_atomic_default_mem_order:
  10767. case OMPC_device_type:
  10768. case OMPC_match:
  10769. llvm_unreachable("Clause is not allowed.");
  10770. }
  10771. return Res;
  10772. }
  10773. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  10774. SourceLocation EndLoc) {
  10775. DSAStack->setNowaitRegion();
  10776. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  10777. }
  10778. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  10779. SourceLocation EndLoc) {
  10780. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  10781. }
  10782. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  10783. SourceLocation EndLoc) {
  10784. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  10785. }
  10786. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  10787. SourceLocation EndLoc) {
  10788. return new (Context) OMPReadClause(StartLoc, EndLoc);
  10789. }
  10790. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  10791. SourceLocation EndLoc) {
  10792. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  10793. }
  10794. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  10795. SourceLocation EndLoc) {
  10796. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  10797. }
  10798. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  10799. SourceLocation EndLoc) {
  10800. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  10801. }
  10802. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  10803. SourceLocation EndLoc) {
  10804. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  10805. }
  10806. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  10807. SourceLocation EndLoc) {
  10808. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  10809. }
  10810. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  10811. SourceLocation EndLoc) {
  10812. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  10813. }
  10814. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  10815. SourceLocation EndLoc) {
  10816. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  10817. }
  10818. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  10819. SourceLocation EndLoc) {
  10820. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  10821. }
  10822. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  10823. SourceLocation EndLoc) {
  10824. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  10825. }
  10826. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  10827. SourceLocation EndLoc) {
  10828. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  10829. }
  10830. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  10831. SourceLocation EndLoc) {
  10832. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  10833. }
  10834. OMPClause *Sema::ActOnOpenMPVarListClause(
  10835. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  10836. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  10837. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  10838. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  10839. OpenMPLinearClauseKind LinKind,
  10840. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  10841. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  10842. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  10843. SourceLocation StartLoc = Locs.StartLoc;
  10844. SourceLocation LParenLoc = Locs.LParenLoc;
  10845. SourceLocation EndLoc = Locs.EndLoc;
  10846. OMPClause *Res = nullptr;
  10847. switch (Kind) {
  10848. case OMPC_private:
  10849. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10850. break;
  10851. case OMPC_firstprivate:
  10852. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10853. break;
  10854. case OMPC_lastprivate:
  10855. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10856. break;
  10857. case OMPC_shared:
  10858. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  10859. break;
  10860. case OMPC_reduction:
  10861. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10862. EndLoc, ReductionOrMapperIdScopeSpec,
  10863. ReductionOrMapperId);
  10864. break;
  10865. case OMPC_task_reduction:
  10866. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10867. EndLoc, ReductionOrMapperIdScopeSpec,
  10868. ReductionOrMapperId);
  10869. break;
  10870. case OMPC_in_reduction:
  10871. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  10872. EndLoc, ReductionOrMapperIdScopeSpec,
  10873. ReductionOrMapperId);
  10874. break;
  10875. case OMPC_linear:
  10876. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  10877. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  10878. break;
  10879. case OMPC_aligned:
  10880. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  10881. ColonLoc, EndLoc);
  10882. break;
  10883. case OMPC_copyin:
  10884. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  10885. break;
  10886. case OMPC_copyprivate:
  10887. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  10888. break;
  10889. case OMPC_flush:
  10890. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  10891. break;
  10892. case OMPC_depend:
  10893. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  10894. StartLoc, LParenLoc, EndLoc);
  10895. break;
  10896. case OMPC_map:
  10897. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  10898. ReductionOrMapperIdScopeSpec,
  10899. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  10900. DepLinMapLoc, ColonLoc, VarList, Locs);
  10901. break;
  10902. case OMPC_to:
  10903. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  10904. ReductionOrMapperId, Locs);
  10905. break;
  10906. case OMPC_from:
  10907. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  10908. ReductionOrMapperId, Locs);
  10909. break;
  10910. case OMPC_use_device_ptr:
  10911. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  10912. break;
  10913. case OMPC_is_device_ptr:
  10914. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  10915. break;
  10916. case OMPC_allocate:
  10917. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  10918. ColonLoc, EndLoc);
  10919. break;
  10920. case OMPC_if:
  10921. case OMPC_final:
  10922. case OMPC_num_threads:
  10923. case OMPC_safelen:
  10924. case OMPC_simdlen:
  10925. case OMPC_allocator:
  10926. case OMPC_collapse:
  10927. case OMPC_default:
  10928. case OMPC_proc_bind:
  10929. case OMPC_schedule:
  10930. case OMPC_ordered:
  10931. case OMPC_nowait:
  10932. case OMPC_untied:
  10933. case OMPC_mergeable:
  10934. case OMPC_threadprivate:
  10935. case OMPC_read:
  10936. case OMPC_write:
  10937. case OMPC_update:
  10938. case OMPC_capture:
  10939. case OMPC_seq_cst:
  10940. case OMPC_device:
  10941. case OMPC_threads:
  10942. case OMPC_simd:
  10943. case OMPC_num_teams:
  10944. case OMPC_thread_limit:
  10945. case OMPC_priority:
  10946. case OMPC_grainsize:
  10947. case OMPC_nogroup:
  10948. case OMPC_num_tasks:
  10949. case OMPC_hint:
  10950. case OMPC_dist_schedule:
  10951. case OMPC_defaultmap:
  10952. case OMPC_unknown:
  10953. case OMPC_uniform:
  10954. case OMPC_unified_address:
  10955. case OMPC_unified_shared_memory:
  10956. case OMPC_reverse_offload:
  10957. case OMPC_dynamic_allocators:
  10958. case OMPC_atomic_default_mem_order:
  10959. case OMPC_device_type:
  10960. case OMPC_match:
  10961. llvm_unreachable("Clause is not allowed.");
  10962. }
  10963. return Res;
  10964. }
  10965. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  10966. ExprObjectKind OK, SourceLocation Loc) {
  10967. ExprResult Res = BuildDeclRefExpr(
  10968. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  10969. if (!Res.isUsable())
  10970. return ExprError();
  10971. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  10972. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  10973. if (!Res.isUsable())
  10974. return ExprError();
  10975. }
  10976. if (VK != VK_LValue && Res.get()->isGLValue()) {
  10977. Res = DefaultLvalueConversion(Res.get());
  10978. if (!Res.isUsable())
  10979. return ExprError();
  10980. }
  10981. return Res;
  10982. }
  10983. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  10984. SourceLocation StartLoc,
  10985. SourceLocation LParenLoc,
  10986. SourceLocation EndLoc) {
  10987. SmallVector<Expr *, 8> Vars;
  10988. SmallVector<Expr *, 8> PrivateCopies;
  10989. for (Expr *RefExpr : VarList) {
  10990. assert(RefExpr && "NULL expr in OpenMP private clause.");
  10991. SourceLocation ELoc;
  10992. SourceRange ERange;
  10993. Expr *SimpleRefExpr = RefExpr;
  10994. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10995. if (Res.second) {
  10996. // It will be analyzed later.
  10997. Vars.push_back(RefExpr);
  10998. PrivateCopies.push_back(nullptr);
  10999. }
  11000. ValueDecl *D = Res.first;
  11001. if (!D)
  11002. continue;
  11003. QualType Type = D->getType();
  11004. auto *VD = dyn_cast<VarDecl>(D);
  11005. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11006. // A variable that appears in a private clause must not have an incomplete
  11007. // type or a reference type.
  11008. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  11009. continue;
  11010. Type = Type.getNonReferenceType();
  11011. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11012. // A variable that is privatized must not have a const-qualified type
  11013. // unless it is of class type with a mutable member. This restriction does
  11014. // not apply to the firstprivate clause.
  11015. //
  11016. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  11017. // A variable that appears in a private clause must not have a
  11018. // const-qualified type unless it is of class type with a mutable member.
  11019. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  11020. continue;
  11021. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11022. // in a Construct]
  11023. // Variables with the predetermined data-sharing attributes may not be
  11024. // listed in data-sharing attributes clauses, except for the cases
  11025. // listed below. For these exceptions only, listing a predetermined
  11026. // variable in a data-sharing attribute clause is allowed and overrides
  11027. // the variable's predetermined data-sharing attributes.
  11028. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11029. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  11030. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11031. << getOpenMPClauseName(OMPC_private);
  11032. reportOriginalDsa(*this, DSAStack, D, DVar);
  11033. continue;
  11034. }
  11035. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11036. // Variably modified types are not supported for tasks.
  11037. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11038. isOpenMPTaskingDirective(CurrDir)) {
  11039. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11040. << getOpenMPClauseName(OMPC_private) << Type
  11041. << getOpenMPDirectiveName(CurrDir);
  11042. bool IsDecl =
  11043. !VD ||
  11044. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11045. Diag(D->getLocation(),
  11046. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11047. << D;
  11048. continue;
  11049. }
  11050. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11051. // A list item cannot appear in both a map clause and a data-sharing
  11052. // attribute clause on the same construct
  11053. //
  11054. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11055. // A list item cannot appear in both a map clause and a data-sharing
  11056. // attribute clause on the same construct unless the construct is a
  11057. // combined construct.
  11058. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  11059. CurrDir == OMPD_target) {
  11060. OpenMPClauseKind ConflictKind;
  11061. if (DSAStack->checkMappableExprComponentListsForDecl(
  11062. VD, /*CurrentRegionOnly=*/true,
  11063. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11064. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  11065. ConflictKind = WhereFoundClauseKind;
  11066. return true;
  11067. })) {
  11068. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11069. << getOpenMPClauseName(OMPC_private)
  11070. << getOpenMPClauseName(ConflictKind)
  11071. << getOpenMPDirectiveName(CurrDir);
  11072. reportOriginalDsa(*this, DSAStack, D, DVar);
  11073. continue;
  11074. }
  11075. }
  11076. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  11077. // A variable of class type (or array thereof) that appears in a private
  11078. // clause requires an accessible, unambiguous default constructor for the
  11079. // class type.
  11080. // Generate helper private variable and initialize it with the default
  11081. // value. The address of the original variable is replaced by the address of
  11082. // the new private variable in CodeGen. This new variable is not added to
  11083. // IdResolver, so the code in the OpenMP region uses original variable for
  11084. // proper diagnostics.
  11085. Type = Type.getUnqualifiedType();
  11086. VarDecl *VDPrivate =
  11087. buildVarDecl(*this, ELoc, Type, D->getName(),
  11088. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11089. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11090. ActOnUninitializedDecl(VDPrivate);
  11091. if (VDPrivate->isInvalidDecl())
  11092. continue;
  11093. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11094. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11095. DeclRefExpr *Ref = nullptr;
  11096. if (!VD && !CurContext->isDependentContext())
  11097. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11098. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  11099. Vars.push_back((VD || CurContext->isDependentContext())
  11100. ? RefExpr->IgnoreParens()
  11101. : Ref);
  11102. PrivateCopies.push_back(VDPrivateRefExpr);
  11103. }
  11104. if (Vars.empty())
  11105. return nullptr;
  11106. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11107. PrivateCopies);
  11108. }
  11109. namespace {
  11110. class DiagsUninitializedSeveretyRAII {
  11111. private:
  11112. DiagnosticsEngine &Diags;
  11113. SourceLocation SavedLoc;
  11114. bool IsIgnored = false;
  11115. public:
  11116. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  11117. bool IsIgnored)
  11118. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  11119. if (!IsIgnored) {
  11120. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  11121. /*Map*/ diag::Severity::Ignored, Loc);
  11122. }
  11123. }
  11124. ~DiagsUninitializedSeveretyRAII() {
  11125. if (!IsIgnored)
  11126. Diags.popMappings(SavedLoc);
  11127. }
  11128. };
  11129. }
  11130. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  11131. SourceLocation StartLoc,
  11132. SourceLocation LParenLoc,
  11133. SourceLocation EndLoc) {
  11134. SmallVector<Expr *, 8> Vars;
  11135. SmallVector<Expr *, 8> PrivateCopies;
  11136. SmallVector<Expr *, 8> Inits;
  11137. SmallVector<Decl *, 4> ExprCaptures;
  11138. bool IsImplicitClause =
  11139. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  11140. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  11141. for (Expr *RefExpr : VarList) {
  11142. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  11143. SourceLocation ELoc;
  11144. SourceRange ERange;
  11145. Expr *SimpleRefExpr = RefExpr;
  11146. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11147. if (Res.second) {
  11148. // It will be analyzed later.
  11149. Vars.push_back(RefExpr);
  11150. PrivateCopies.push_back(nullptr);
  11151. Inits.push_back(nullptr);
  11152. }
  11153. ValueDecl *D = Res.first;
  11154. if (!D)
  11155. continue;
  11156. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  11157. QualType Type = D->getType();
  11158. auto *VD = dyn_cast<VarDecl>(D);
  11159. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  11160. // A variable that appears in a private clause must not have an incomplete
  11161. // type or a reference type.
  11162. if (RequireCompleteType(ELoc, Type,
  11163. diag::err_omp_firstprivate_incomplete_type))
  11164. continue;
  11165. Type = Type.getNonReferenceType();
  11166. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  11167. // A variable of class type (or array thereof) that appears in a private
  11168. // clause requires an accessible, unambiguous copy constructor for the
  11169. // class type.
  11170. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11171. // If an implicit firstprivate variable found it was checked already.
  11172. DSAStackTy::DSAVarData TopDVar;
  11173. if (!IsImplicitClause) {
  11174. DSAStackTy::DSAVarData DVar =
  11175. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11176. TopDVar = DVar;
  11177. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11178. bool IsConstant = ElemType.isConstant(Context);
  11179. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  11180. // A list item that specifies a given variable may not appear in more
  11181. // than one clause on the same directive, except that a variable may be
  11182. // specified in both firstprivate and lastprivate clauses.
  11183. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11184. // A list item may appear in a firstprivate or lastprivate clause but not
  11185. // both.
  11186. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  11187. (isOpenMPDistributeDirective(CurrDir) ||
  11188. DVar.CKind != OMPC_lastprivate) &&
  11189. DVar.RefExpr) {
  11190. Diag(ELoc, diag::err_omp_wrong_dsa)
  11191. << getOpenMPClauseName(DVar.CKind)
  11192. << getOpenMPClauseName(OMPC_firstprivate);
  11193. reportOriginalDsa(*this, DSAStack, D, DVar);
  11194. continue;
  11195. }
  11196. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11197. // in a Construct]
  11198. // Variables with the predetermined data-sharing attributes may not be
  11199. // listed in data-sharing attributes clauses, except for the cases
  11200. // listed below. For these exceptions only, listing a predetermined
  11201. // variable in a data-sharing attribute clause is allowed and overrides
  11202. // the variable's predetermined data-sharing attributes.
  11203. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11204. // in a Construct, C/C++, p.2]
  11205. // Variables with const-qualified type having no mutable member may be
  11206. // listed in a firstprivate clause, even if they are static data members.
  11207. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  11208. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  11209. Diag(ELoc, diag::err_omp_wrong_dsa)
  11210. << getOpenMPClauseName(DVar.CKind)
  11211. << getOpenMPClauseName(OMPC_firstprivate);
  11212. reportOriginalDsa(*this, DSAStack, D, DVar);
  11213. continue;
  11214. }
  11215. // OpenMP [2.9.3.4, Restrictions, p.2]
  11216. // A list item that is private within a parallel region must not appear
  11217. // in a firstprivate clause on a worksharing construct if any of the
  11218. // worksharing regions arising from the worksharing construct ever bind
  11219. // to any of the parallel regions arising from the parallel construct.
  11220. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11221. // A list item that is private within a teams region must not appear in a
  11222. // firstprivate clause on a distribute construct if any of the distribute
  11223. // regions arising from the distribute construct ever bind to any of the
  11224. // teams regions arising from the teams construct.
  11225. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  11226. // A list item that appears in a reduction clause of a teams construct
  11227. // must not appear in a firstprivate clause on a distribute construct if
  11228. // any of the distribute regions arising from the distribute construct
  11229. // ever bind to any of the teams regions arising from the teams construct.
  11230. if ((isOpenMPWorksharingDirective(CurrDir) ||
  11231. isOpenMPDistributeDirective(CurrDir)) &&
  11232. !isOpenMPParallelDirective(CurrDir) &&
  11233. !isOpenMPTeamsDirective(CurrDir)) {
  11234. DVar = DSAStack->getImplicitDSA(D, true);
  11235. if (DVar.CKind != OMPC_shared &&
  11236. (isOpenMPParallelDirective(DVar.DKind) ||
  11237. isOpenMPTeamsDirective(DVar.DKind) ||
  11238. DVar.DKind == OMPD_unknown)) {
  11239. Diag(ELoc, diag::err_omp_required_access)
  11240. << getOpenMPClauseName(OMPC_firstprivate)
  11241. << getOpenMPClauseName(OMPC_shared);
  11242. reportOriginalDsa(*this, DSAStack, D, DVar);
  11243. continue;
  11244. }
  11245. }
  11246. // OpenMP [2.9.3.4, Restrictions, p.3]
  11247. // A list item that appears in a reduction clause of a parallel construct
  11248. // must not appear in a firstprivate clause on a worksharing or task
  11249. // construct if any of the worksharing or task regions arising from the
  11250. // worksharing or task construct ever bind to any of the parallel regions
  11251. // arising from the parallel construct.
  11252. // OpenMP [2.9.3.4, Restrictions, p.4]
  11253. // A list item that appears in a reduction clause in worksharing
  11254. // construct must not appear in a firstprivate clause in a task construct
  11255. // encountered during execution of any of the worksharing regions arising
  11256. // from the worksharing construct.
  11257. if (isOpenMPTaskingDirective(CurrDir)) {
  11258. DVar = DSAStack->hasInnermostDSA(
  11259. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  11260. [](OpenMPDirectiveKind K) {
  11261. return isOpenMPParallelDirective(K) ||
  11262. isOpenMPWorksharingDirective(K) ||
  11263. isOpenMPTeamsDirective(K);
  11264. },
  11265. /*FromParent=*/true);
  11266. if (DVar.CKind == OMPC_reduction &&
  11267. (isOpenMPParallelDirective(DVar.DKind) ||
  11268. isOpenMPWorksharingDirective(DVar.DKind) ||
  11269. isOpenMPTeamsDirective(DVar.DKind))) {
  11270. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  11271. << getOpenMPDirectiveName(DVar.DKind);
  11272. reportOriginalDsa(*this, DSAStack, D, DVar);
  11273. continue;
  11274. }
  11275. }
  11276. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11277. // A list item cannot appear in both a map clause and a data-sharing
  11278. // attribute clause on the same construct
  11279. //
  11280. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  11281. // A list item cannot appear in both a map clause and a data-sharing
  11282. // attribute clause on the same construct unless the construct is a
  11283. // combined construct.
  11284. if ((LangOpts.OpenMP <= 45 &&
  11285. isOpenMPTargetExecutionDirective(CurrDir)) ||
  11286. CurrDir == OMPD_target) {
  11287. OpenMPClauseKind ConflictKind;
  11288. if (DSAStack->checkMappableExprComponentListsForDecl(
  11289. VD, /*CurrentRegionOnly=*/true,
  11290. [&ConflictKind](
  11291. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  11292. OpenMPClauseKind WhereFoundClauseKind) {
  11293. ConflictKind = WhereFoundClauseKind;
  11294. return true;
  11295. })) {
  11296. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11297. << getOpenMPClauseName(OMPC_firstprivate)
  11298. << getOpenMPClauseName(ConflictKind)
  11299. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11300. reportOriginalDsa(*this, DSAStack, D, DVar);
  11301. continue;
  11302. }
  11303. }
  11304. }
  11305. // Variably modified types are not supported for tasks.
  11306. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  11307. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  11308. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11309. << getOpenMPClauseName(OMPC_firstprivate) << Type
  11310. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11311. bool IsDecl =
  11312. !VD ||
  11313. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11314. Diag(D->getLocation(),
  11315. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11316. << D;
  11317. continue;
  11318. }
  11319. Type = Type.getUnqualifiedType();
  11320. VarDecl *VDPrivate =
  11321. buildVarDecl(*this, ELoc, Type, D->getName(),
  11322. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11323. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11324. // Generate helper private variable and initialize it with the value of the
  11325. // original variable. The address of the original variable is replaced by
  11326. // the address of the new private variable in the CodeGen. This new variable
  11327. // is not added to IdResolver, so the code in the OpenMP region uses
  11328. // original variable for proper diagnostics and variable capturing.
  11329. Expr *VDInitRefExpr = nullptr;
  11330. // For arrays generate initializer for single element and replace it by the
  11331. // original array element in CodeGen.
  11332. if (Type->isArrayType()) {
  11333. VarDecl *VDInit =
  11334. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  11335. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  11336. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  11337. ElemType = ElemType.getUnqualifiedType();
  11338. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  11339. ".firstprivate.temp");
  11340. InitializedEntity Entity =
  11341. InitializedEntity::InitializeVariable(VDInitTemp);
  11342. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  11343. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  11344. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  11345. if (Result.isInvalid())
  11346. VDPrivate->setInvalidDecl();
  11347. else
  11348. VDPrivate->setInit(Result.getAs<Expr>());
  11349. // Remove temp variable declaration.
  11350. Context.Deallocate(VDInitTemp);
  11351. } else {
  11352. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  11353. ".firstprivate.temp");
  11354. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11355. RefExpr->getExprLoc());
  11356. AddInitializerToDecl(VDPrivate,
  11357. DefaultLvalueConversion(VDInitRefExpr).get(),
  11358. /*DirectInit=*/false);
  11359. }
  11360. if (VDPrivate->isInvalidDecl()) {
  11361. if (IsImplicitClause) {
  11362. Diag(RefExpr->getExprLoc(),
  11363. diag::note_omp_task_predetermined_firstprivate_here);
  11364. }
  11365. continue;
  11366. }
  11367. CurContext->addDecl(VDPrivate);
  11368. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  11369. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  11370. RefExpr->getExprLoc());
  11371. DeclRefExpr *Ref = nullptr;
  11372. if (!VD && !CurContext->isDependentContext()) {
  11373. if (TopDVar.CKind == OMPC_lastprivate) {
  11374. Ref = TopDVar.PrivateCopy;
  11375. } else {
  11376. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11377. if (!isOpenMPCapturedDecl(D))
  11378. ExprCaptures.push_back(Ref->getDecl());
  11379. }
  11380. }
  11381. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11382. Vars.push_back((VD || CurContext->isDependentContext())
  11383. ? RefExpr->IgnoreParens()
  11384. : Ref);
  11385. PrivateCopies.push_back(VDPrivateRefExpr);
  11386. Inits.push_back(VDInitRefExpr);
  11387. }
  11388. if (Vars.empty())
  11389. return nullptr;
  11390. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11391. Vars, PrivateCopies, Inits,
  11392. buildPreInits(Context, ExprCaptures));
  11393. }
  11394. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  11395. SourceLocation StartLoc,
  11396. SourceLocation LParenLoc,
  11397. SourceLocation EndLoc) {
  11398. SmallVector<Expr *, 8> Vars;
  11399. SmallVector<Expr *, 8> SrcExprs;
  11400. SmallVector<Expr *, 8> DstExprs;
  11401. SmallVector<Expr *, 8> AssignmentOps;
  11402. SmallVector<Decl *, 4> ExprCaptures;
  11403. SmallVector<Expr *, 4> ExprPostUpdates;
  11404. for (Expr *RefExpr : VarList) {
  11405. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11406. SourceLocation ELoc;
  11407. SourceRange ERange;
  11408. Expr *SimpleRefExpr = RefExpr;
  11409. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11410. if (Res.second) {
  11411. // It will be analyzed later.
  11412. Vars.push_back(RefExpr);
  11413. SrcExprs.push_back(nullptr);
  11414. DstExprs.push_back(nullptr);
  11415. AssignmentOps.push_back(nullptr);
  11416. }
  11417. ValueDecl *D = Res.first;
  11418. if (!D)
  11419. continue;
  11420. QualType Type = D->getType();
  11421. auto *VD = dyn_cast<VarDecl>(D);
  11422. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  11423. // A variable that appears in a lastprivate clause must not have an
  11424. // incomplete type or a reference type.
  11425. if (RequireCompleteType(ELoc, Type,
  11426. diag::err_omp_lastprivate_incomplete_type))
  11427. continue;
  11428. Type = Type.getNonReferenceType();
  11429. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11430. // A variable that is privatized must not have a const-qualified type
  11431. // unless it is of class type with a mutable member. This restriction does
  11432. // not apply to the firstprivate clause.
  11433. //
  11434. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  11435. // A variable that appears in a lastprivate clause must not have a
  11436. // const-qualified type unless it is of class type with a mutable member.
  11437. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  11438. continue;
  11439. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  11440. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  11441. // in a Construct]
  11442. // Variables with the predetermined data-sharing attributes may not be
  11443. // listed in data-sharing attributes clauses, except for the cases
  11444. // listed below.
  11445. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  11446. // A list item may appear in a firstprivate or lastprivate clause but not
  11447. // both.
  11448. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11449. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  11450. (isOpenMPDistributeDirective(CurrDir) ||
  11451. DVar.CKind != OMPC_firstprivate) &&
  11452. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  11453. Diag(ELoc, diag::err_omp_wrong_dsa)
  11454. << getOpenMPClauseName(DVar.CKind)
  11455. << getOpenMPClauseName(OMPC_lastprivate);
  11456. reportOriginalDsa(*this, DSAStack, D, DVar);
  11457. continue;
  11458. }
  11459. // OpenMP [2.14.3.5, Restrictions, p.2]
  11460. // A list item that is private within a parallel region, or that appears in
  11461. // the reduction clause of a parallel construct, must not appear in a
  11462. // lastprivate clause on a worksharing construct if any of the corresponding
  11463. // worksharing regions ever binds to any of the corresponding parallel
  11464. // regions.
  11465. DSAStackTy::DSAVarData TopDVar = DVar;
  11466. if (isOpenMPWorksharingDirective(CurrDir) &&
  11467. !isOpenMPParallelDirective(CurrDir) &&
  11468. !isOpenMPTeamsDirective(CurrDir)) {
  11469. DVar = DSAStack->getImplicitDSA(D, true);
  11470. if (DVar.CKind != OMPC_shared) {
  11471. Diag(ELoc, diag::err_omp_required_access)
  11472. << getOpenMPClauseName(OMPC_lastprivate)
  11473. << getOpenMPClauseName(OMPC_shared);
  11474. reportOriginalDsa(*this, DSAStack, D, DVar);
  11475. continue;
  11476. }
  11477. }
  11478. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  11479. // A variable of class type (or array thereof) that appears in a
  11480. // lastprivate clause requires an accessible, unambiguous default
  11481. // constructor for the class type, unless the list item is also specified
  11482. // in a firstprivate clause.
  11483. // A variable of class type (or array thereof) that appears in a
  11484. // lastprivate clause requires an accessible, unambiguous copy assignment
  11485. // operator for the class type.
  11486. Type = Context.getBaseElementType(Type).getNonReferenceType();
  11487. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  11488. Type.getUnqualifiedType(), ".lastprivate.src",
  11489. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11490. DeclRefExpr *PseudoSrcExpr =
  11491. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  11492. VarDecl *DstVD =
  11493. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  11494. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11495. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11496. // For arrays generate assignment operation for single element and replace
  11497. // it by the original array element in CodeGen.
  11498. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  11499. PseudoDstExpr, PseudoSrcExpr);
  11500. if (AssignmentOp.isInvalid())
  11501. continue;
  11502. AssignmentOp =
  11503. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11504. if (AssignmentOp.isInvalid())
  11505. continue;
  11506. DeclRefExpr *Ref = nullptr;
  11507. if (!VD && !CurContext->isDependentContext()) {
  11508. if (TopDVar.CKind == OMPC_firstprivate) {
  11509. Ref = TopDVar.PrivateCopy;
  11510. } else {
  11511. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11512. if (!isOpenMPCapturedDecl(D))
  11513. ExprCaptures.push_back(Ref->getDecl());
  11514. }
  11515. if (TopDVar.CKind == OMPC_firstprivate ||
  11516. (!isOpenMPCapturedDecl(D) &&
  11517. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  11518. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11519. if (!RefRes.isUsable())
  11520. continue;
  11521. ExprResult PostUpdateRes =
  11522. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11523. RefRes.get());
  11524. if (!PostUpdateRes.isUsable())
  11525. continue;
  11526. ExprPostUpdates.push_back(
  11527. IgnoredValueConversions(PostUpdateRes.get()).get());
  11528. }
  11529. }
  11530. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  11531. Vars.push_back((VD || CurContext->isDependentContext())
  11532. ? RefExpr->IgnoreParens()
  11533. : Ref);
  11534. SrcExprs.push_back(PseudoSrcExpr);
  11535. DstExprs.push_back(PseudoDstExpr);
  11536. AssignmentOps.push_back(AssignmentOp.get());
  11537. }
  11538. if (Vars.empty())
  11539. return nullptr;
  11540. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11541. Vars, SrcExprs, DstExprs, AssignmentOps,
  11542. buildPreInits(Context, ExprCaptures),
  11543. buildPostUpdate(*this, ExprPostUpdates));
  11544. }
  11545. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  11546. SourceLocation StartLoc,
  11547. SourceLocation LParenLoc,
  11548. SourceLocation EndLoc) {
  11549. SmallVector<Expr *, 8> Vars;
  11550. for (Expr *RefExpr : VarList) {
  11551. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  11552. SourceLocation ELoc;
  11553. SourceRange ERange;
  11554. Expr *SimpleRefExpr = RefExpr;
  11555. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11556. if (Res.second) {
  11557. // It will be analyzed later.
  11558. Vars.push_back(RefExpr);
  11559. }
  11560. ValueDecl *D = Res.first;
  11561. if (!D)
  11562. continue;
  11563. auto *VD = dyn_cast<VarDecl>(D);
  11564. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  11565. // in a Construct]
  11566. // Variables with the predetermined data-sharing attributes may not be
  11567. // listed in data-sharing attributes clauses, except for the cases
  11568. // listed below. For these exceptions only, listing a predetermined
  11569. // variable in a data-sharing attribute clause is allowed and overrides
  11570. // the variable's predetermined data-sharing attributes.
  11571. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11572. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  11573. DVar.RefExpr) {
  11574. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11575. << getOpenMPClauseName(OMPC_shared);
  11576. reportOriginalDsa(*this, DSAStack, D, DVar);
  11577. continue;
  11578. }
  11579. DeclRefExpr *Ref = nullptr;
  11580. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  11581. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11582. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  11583. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  11584. ? RefExpr->IgnoreParens()
  11585. : Ref);
  11586. }
  11587. if (Vars.empty())
  11588. return nullptr;
  11589. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  11590. }
  11591. namespace {
  11592. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  11593. DSAStackTy *Stack;
  11594. public:
  11595. bool VisitDeclRefExpr(DeclRefExpr *E) {
  11596. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  11597. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  11598. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  11599. return false;
  11600. if (DVar.CKind != OMPC_unknown)
  11601. return true;
  11602. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  11603. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  11604. /*FromParent=*/true);
  11605. return DVarPrivate.CKind != OMPC_unknown;
  11606. }
  11607. return false;
  11608. }
  11609. bool VisitStmt(Stmt *S) {
  11610. for (Stmt *Child : S->children()) {
  11611. if (Child && Visit(Child))
  11612. return true;
  11613. }
  11614. return false;
  11615. }
  11616. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  11617. };
  11618. } // namespace
  11619. namespace {
  11620. // Transform MemberExpression for specified FieldDecl of current class to
  11621. // DeclRefExpr to specified OMPCapturedExprDecl.
  11622. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  11623. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  11624. ValueDecl *Field = nullptr;
  11625. DeclRefExpr *CapturedExpr = nullptr;
  11626. public:
  11627. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  11628. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  11629. ExprResult TransformMemberExpr(MemberExpr *E) {
  11630. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  11631. E->getMemberDecl() == Field) {
  11632. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  11633. return CapturedExpr;
  11634. }
  11635. return BaseTransform::TransformMemberExpr(E);
  11636. }
  11637. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  11638. };
  11639. } // namespace
  11640. template <typename T, typename U>
  11641. static T filterLookupForUDReductionAndMapper(
  11642. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  11643. for (U &Set : Lookups) {
  11644. for (auto *D : Set) {
  11645. if (T Res = Gen(cast<ValueDecl>(D)))
  11646. return Res;
  11647. }
  11648. }
  11649. return T();
  11650. }
  11651. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  11652. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  11653. for (auto RD : D->redecls()) {
  11654. // Don't bother with extra checks if we already know this one isn't visible.
  11655. if (RD == D)
  11656. continue;
  11657. auto ND = cast<NamedDecl>(RD);
  11658. if (LookupResult::isVisible(SemaRef, ND))
  11659. return ND;
  11660. }
  11661. return nullptr;
  11662. }
  11663. static void
  11664. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  11665. SourceLocation Loc, QualType Ty,
  11666. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  11667. // Find all of the associated namespaces and classes based on the
  11668. // arguments we have.
  11669. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  11670. Sema::AssociatedClassSet AssociatedClasses;
  11671. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  11672. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  11673. AssociatedClasses);
  11674. // C++ [basic.lookup.argdep]p3:
  11675. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  11676. // and let Y be the lookup set produced by argument dependent
  11677. // lookup (defined as follows). If X contains [...] then Y is
  11678. // empty. Otherwise Y is the set of declarations found in the
  11679. // namespaces associated with the argument types as described
  11680. // below. The set of declarations found by the lookup of the name
  11681. // is the union of X and Y.
  11682. //
  11683. // Here, we compute Y and add its members to the overloaded
  11684. // candidate set.
  11685. for (auto *NS : AssociatedNamespaces) {
  11686. // When considering an associated namespace, the lookup is the
  11687. // same as the lookup performed when the associated namespace is
  11688. // used as a qualifier (3.4.3.2) except that:
  11689. //
  11690. // -- Any using-directives in the associated namespace are
  11691. // ignored.
  11692. //
  11693. // -- Any namespace-scope friend functions declared in
  11694. // associated classes are visible within their respective
  11695. // namespaces even if they are not visible during an ordinary
  11696. // lookup (11.4).
  11697. DeclContext::lookup_result R = NS->lookup(Id.getName());
  11698. for (auto *D : R) {
  11699. auto *Underlying = D;
  11700. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11701. Underlying = USD->getTargetDecl();
  11702. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  11703. !isa<OMPDeclareMapperDecl>(Underlying))
  11704. continue;
  11705. if (!SemaRef.isVisible(D)) {
  11706. D = findAcceptableDecl(SemaRef, D);
  11707. if (!D)
  11708. continue;
  11709. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  11710. Underlying = USD->getTargetDecl();
  11711. }
  11712. Lookups.emplace_back();
  11713. Lookups.back().addDecl(Underlying);
  11714. }
  11715. }
  11716. }
  11717. static ExprResult
  11718. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  11719. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  11720. const DeclarationNameInfo &ReductionId, QualType Ty,
  11721. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  11722. if (ReductionIdScopeSpec.isInvalid())
  11723. return ExprError();
  11724. SmallVector<UnresolvedSet<8>, 4> Lookups;
  11725. if (S) {
  11726. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11727. Lookup.suppressDiagnostics();
  11728. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  11729. NamedDecl *D = Lookup.getRepresentativeDecl();
  11730. do {
  11731. S = S->getParent();
  11732. } while (S && !S->isDeclScope(D));
  11733. if (S)
  11734. S = S->getParent();
  11735. Lookups.emplace_back();
  11736. Lookups.back().append(Lookup.begin(), Lookup.end());
  11737. Lookup.clear();
  11738. }
  11739. } else if (auto *ULE =
  11740. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  11741. Lookups.push_back(UnresolvedSet<8>());
  11742. Decl *PrevD = nullptr;
  11743. for (NamedDecl *D : ULE->decls()) {
  11744. if (D == PrevD)
  11745. Lookups.push_back(UnresolvedSet<8>());
  11746. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  11747. Lookups.back().addDecl(DRD);
  11748. PrevD = D;
  11749. }
  11750. }
  11751. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  11752. Ty->isInstantiationDependentType() ||
  11753. Ty->containsUnexpandedParameterPack() ||
  11754. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  11755. return !D->isInvalidDecl() &&
  11756. (D->getType()->isDependentType() ||
  11757. D->getType()->isInstantiationDependentType() ||
  11758. D->getType()->containsUnexpandedParameterPack());
  11759. })) {
  11760. UnresolvedSet<8> ResSet;
  11761. for (const UnresolvedSet<8> &Set : Lookups) {
  11762. if (Set.empty())
  11763. continue;
  11764. ResSet.append(Set.begin(), Set.end());
  11765. // The last item marks the end of all declarations at the specified scope.
  11766. ResSet.addDecl(Set[Set.size() - 1]);
  11767. }
  11768. return UnresolvedLookupExpr::Create(
  11769. SemaRef.Context, /*NamingClass=*/nullptr,
  11770. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  11771. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  11772. }
  11773. // Lookup inside the classes.
  11774. // C++ [over.match.oper]p3:
  11775. // For a unary operator @ with an operand of a type whose
  11776. // cv-unqualified version is T1, and for a binary operator @ with
  11777. // a left operand of a type whose cv-unqualified version is T1 and
  11778. // a right operand of a type whose cv-unqualified version is T2,
  11779. // three sets of candidate functions, designated member
  11780. // candidates, non-member candidates and built-in candidates, are
  11781. // constructed as follows:
  11782. // -- If T1 is a complete class type or a class currently being
  11783. // defined, the set of member candidates is the result of the
  11784. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  11785. // the set of member candidates is empty.
  11786. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  11787. Lookup.suppressDiagnostics();
  11788. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  11789. // Complete the type if it can be completed.
  11790. // If the type is neither complete nor being defined, bail out now.
  11791. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  11792. TyRec->getDecl()->getDefinition()) {
  11793. Lookup.clear();
  11794. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  11795. if (Lookup.empty()) {
  11796. Lookups.emplace_back();
  11797. Lookups.back().append(Lookup.begin(), Lookup.end());
  11798. }
  11799. }
  11800. }
  11801. // Perform ADL.
  11802. if (SemaRef.getLangOpts().CPlusPlus)
  11803. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  11804. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11805. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  11806. if (!D->isInvalidDecl() &&
  11807. SemaRef.Context.hasSameType(D->getType(), Ty))
  11808. return D;
  11809. return nullptr;
  11810. }))
  11811. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  11812. VK_LValue, Loc);
  11813. if (SemaRef.getLangOpts().CPlusPlus) {
  11814. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  11815. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  11816. if (!D->isInvalidDecl() &&
  11817. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  11818. !Ty.isMoreQualifiedThan(D->getType()))
  11819. return D;
  11820. return nullptr;
  11821. })) {
  11822. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  11823. /*DetectVirtual=*/false);
  11824. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  11825. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  11826. VD->getType().getUnqualifiedType()))) {
  11827. if (SemaRef.CheckBaseClassAccess(
  11828. Loc, VD->getType(), Ty, Paths.front(),
  11829. /*DiagID=*/0) != Sema::AR_inaccessible) {
  11830. SemaRef.BuildBasePathArray(Paths, BasePath);
  11831. return SemaRef.BuildDeclRefExpr(
  11832. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  11833. }
  11834. }
  11835. }
  11836. }
  11837. }
  11838. if (ReductionIdScopeSpec.isSet()) {
  11839. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  11840. return ExprError();
  11841. }
  11842. return ExprEmpty();
  11843. }
  11844. namespace {
  11845. /// Data for the reduction-based clauses.
  11846. struct ReductionData {
  11847. /// List of original reduction items.
  11848. SmallVector<Expr *, 8> Vars;
  11849. /// List of private copies of the reduction items.
  11850. SmallVector<Expr *, 8> Privates;
  11851. /// LHS expressions for the reduction_op expressions.
  11852. SmallVector<Expr *, 8> LHSs;
  11853. /// RHS expressions for the reduction_op expressions.
  11854. SmallVector<Expr *, 8> RHSs;
  11855. /// Reduction operation expression.
  11856. SmallVector<Expr *, 8> ReductionOps;
  11857. /// Taskgroup descriptors for the corresponding reduction items in
  11858. /// in_reduction clauses.
  11859. SmallVector<Expr *, 8> TaskgroupDescriptors;
  11860. /// List of captures for clause.
  11861. SmallVector<Decl *, 4> ExprCaptures;
  11862. /// List of postupdate expressions.
  11863. SmallVector<Expr *, 4> ExprPostUpdates;
  11864. ReductionData() = delete;
  11865. /// Reserves required memory for the reduction data.
  11866. ReductionData(unsigned Size) {
  11867. Vars.reserve(Size);
  11868. Privates.reserve(Size);
  11869. LHSs.reserve(Size);
  11870. RHSs.reserve(Size);
  11871. ReductionOps.reserve(Size);
  11872. TaskgroupDescriptors.reserve(Size);
  11873. ExprCaptures.reserve(Size);
  11874. ExprPostUpdates.reserve(Size);
  11875. }
  11876. /// Stores reduction item and reduction operation only (required for dependent
  11877. /// reduction item).
  11878. void push(Expr *Item, Expr *ReductionOp) {
  11879. Vars.emplace_back(Item);
  11880. Privates.emplace_back(nullptr);
  11881. LHSs.emplace_back(nullptr);
  11882. RHSs.emplace_back(nullptr);
  11883. ReductionOps.emplace_back(ReductionOp);
  11884. TaskgroupDescriptors.emplace_back(nullptr);
  11885. }
  11886. /// Stores reduction data.
  11887. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  11888. Expr *TaskgroupDescriptor) {
  11889. Vars.emplace_back(Item);
  11890. Privates.emplace_back(Private);
  11891. LHSs.emplace_back(LHS);
  11892. RHSs.emplace_back(RHS);
  11893. ReductionOps.emplace_back(ReductionOp);
  11894. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  11895. }
  11896. };
  11897. } // namespace
  11898. static bool checkOMPArraySectionConstantForReduction(
  11899. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  11900. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  11901. const Expr *Length = OASE->getLength();
  11902. if (Length == nullptr) {
  11903. // For array sections of the form [1:] or [:], we would need to analyze
  11904. // the lower bound...
  11905. if (OASE->getColonLoc().isValid())
  11906. return false;
  11907. // This is an array subscript which has implicit length 1!
  11908. SingleElement = true;
  11909. ArraySizes.push_back(llvm::APSInt::get(1));
  11910. } else {
  11911. Expr::EvalResult Result;
  11912. if (!Length->EvaluateAsInt(Result, Context))
  11913. return false;
  11914. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11915. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  11916. ArraySizes.push_back(ConstantLengthValue);
  11917. }
  11918. // Get the base of this array section and walk up from there.
  11919. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  11920. // We require length = 1 for all array sections except the right-most to
  11921. // guarantee that the memory region is contiguous and has no holes in it.
  11922. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  11923. Length = TempOASE->getLength();
  11924. if (Length == nullptr) {
  11925. // For array sections of the form [1:] or [:], we would need to analyze
  11926. // the lower bound...
  11927. if (OASE->getColonLoc().isValid())
  11928. return false;
  11929. // This is an array subscript which has implicit length 1!
  11930. ArraySizes.push_back(llvm::APSInt::get(1));
  11931. } else {
  11932. Expr::EvalResult Result;
  11933. if (!Length->EvaluateAsInt(Result, Context))
  11934. return false;
  11935. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  11936. if (ConstantLengthValue.getSExtValue() != 1)
  11937. return false;
  11938. ArraySizes.push_back(ConstantLengthValue);
  11939. }
  11940. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  11941. }
  11942. // If we have a single element, we don't need to add the implicit lengths.
  11943. if (!SingleElement) {
  11944. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  11945. // Has implicit length 1!
  11946. ArraySizes.push_back(llvm::APSInt::get(1));
  11947. Base = TempASE->getBase()->IgnoreParenImpCasts();
  11948. }
  11949. }
  11950. // This array section can be privatized as a single value or as a constant
  11951. // sized array.
  11952. return true;
  11953. }
  11954. static bool actOnOMPReductionKindClause(
  11955. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  11956. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11957. SourceLocation ColonLoc, SourceLocation EndLoc,
  11958. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11959. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  11960. DeclarationName DN = ReductionId.getName();
  11961. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  11962. BinaryOperatorKind BOK = BO_Comma;
  11963. ASTContext &Context = S.Context;
  11964. // OpenMP [2.14.3.6, reduction clause]
  11965. // C
  11966. // reduction-identifier is either an identifier or one of the following
  11967. // operators: +, -, *, &, |, ^, && and ||
  11968. // C++
  11969. // reduction-identifier is either an id-expression or one of the following
  11970. // operators: +, -, *, &, |, ^, && and ||
  11971. switch (OOK) {
  11972. case OO_Plus:
  11973. case OO_Minus:
  11974. BOK = BO_Add;
  11975. break;
  11976. case OO_Star:
  11977. BOK = BO_Mul;
  11978. break;
  11979. case OO_Amp:
  11980. BOK = BO_And;
  11981. break;
  11982. case OO_Pipe:
  11983. BOK = BO_Or;
  11984. break;
  11985. case OO_Caret:
  11986. BOK = BO_Xor;
  11987. break;
  11988. case OO_AmpAmp:
  11989. BOK = BO_LAnd;
  11990. break;
  11991. case OO_PipePipe:
  11992. BOK = BO_LOr;
  11993. break;
  11994. case OO_New:
  11995. case OO_Delete:
  11996. case OO_Array_New:
  11997. case OO_Array_Delete:
  11998. case OO_Slash:
  11999. case OO_Percent:
  12000. case OO_Tilde:
  12001. case OO_Exclaim:
  12002. case OO_Equal:
  12003. case OO_Less:
  12004. case OO_Greater:
  12005. case OO_LessEqual:
  12006. case OO_GreaterEqual:
  12007. case OO_PlusEqual:
  12008. case OO_MinusEqual:
  12009. case OO_StarEqual:
  12010. case OO_SlashEqual:
  12011. case OO_PercentEqual:
  12012. case OO_CaretEqual:
  12013. case OO_AmpEqual:
  12014. case OO_PipeEqual:
  12015. case OO_LessLess:
  12016. case OO_GreaterGreater:
  12017. case OO_LessLessEqual:
  12018. case OO_GreaterGreaterEqual:
  12019. case OO_EqualEqual:
  12020. case OO_ExclaimEqual:
  12021. case OO_Spaceship:
  12022. case OO_PlusPlus:
  12023. case OO_MinusMinus:
  12024. case OO_Comma:
  12025. case OO_ArrowStar:
  12026. case OO_Arrow:
  12027. case OO_Call:
  12028. case OO_Subscript:
  12029. case OO_Conditional:
  12030. case OO_Coawait:
  12031. case NUM_OVERLOADED_OPERATORS:
  12032. llvm_unreachable("Unexpected reduction identifier");
  12033. case OO_None:
  12034. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  12035. if (II->isStr("max"))
  12036. BOK = BO_GT;
  12037. else if (II->isStr("min"))
  12038. BOK = BO_LT;
  12039. }
  12040. break;
  12041. }
  12042. SourceRange ReductionIdRange;
  12043. if (ReductionIdScopeSpec.isValid())
  12044. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  12045. else
  12046. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  12047. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  12048. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  12049. bool FirstIter = true;
  12050. for (Expr *RefExpr : VarList) {
  12051. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  12052. // OpenMP [2.1, C/C++]
  12053. // A list item is a variable or array section, subject to the restrictions
  12054. // specified in Section 2.4 on page 42 and in each of the sections
  12055. // describing clauses and directives for which a list appears.
  12056. // OpenMP [2.14.3.3, Restrictions, p.1]
  12057. // A variable that is part of another variable (as an array or
  12058. // structure element) cannot appear in a private clause.
  12059. if (!FirstIter && IR != ER)
  12060. ++IR;
  12061. FirstIter = false;
  12062. SourceLocation ELoc;
  12063. SourceRange ERange;
  12064. Expr *SimpleRefExpr = RefExpr;
  12065. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  12066. /*AllowArraySection=*/true);
  12067. if (Res.second) {
  12068. // Try to find 'declare reduction' corresponding construct before using
  12069. // builtin/overloaded operators.
  12070. QualType Type = Context.DependentTy;
  12071. CXXCastPath BasePath;
  12072. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12073. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12074. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12075. Expr *ReductionOp = nullptr;
  12076. if (S.CurContext->isDependentContext() &&
  12077. (DeclareReductionRef.isUnset() ||
  12078. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  12079. ReductionOp = DeclareReductionRef.get();
  12080. // It will be analyzed later.
  12081. RD.push(RefExpr, ReductionOp);
  12082. }
  12083. ValueDecl *D = Res.first;
  12084. if (!D)
  12085. continue;
  12086. Expr *TaskgroupDescriptor = nullptr;
  12087. QualType Type;
  12088. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  12089. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  12090. if (ASE) {
  12091. Type = ASE->getType().getNonReferenceType();
  12092. } else if (OASE) {
  12093. QualType BaseType =
  12094. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  12095. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  12096. Type = ATy->getElementType();
  12097. else
  12098. Type = BaseType->getPointeeType();
  12099. Type = Type.getNonReferenceType();
  12100. } else {
  12101. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  12102. }
  12103. auto *VD = dyn_cast<VarDecl>(D);
  12104. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  12105. // A variable that appears in a private clause must not have an incomplete
  12106. // type or a reference type.
  12107. if (S.RequireCompleteType(ELoc, D->getType(),
  12108. diag::err_omp_reduction_incomplete_type))
  12109. continue;
  12110. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12111. // A list item that appears in a reduction clause must not be
  12112. // const-qualified.
  12113. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  12114. /*AcceptIfMutable*/ false, ASE || OASE))
  12115. continue;
  12116. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  12117. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  12118. // If a list-item is a reference type then it must bind to the same object
  12119. // for all threads of the team.
  12120. if (!ASE && !OASE) {
  12121. if (VD) {
  12122. VarDecl *VDDef = VD->getDefinition();
  12123. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  12124. DSARefChecker Check(Stack);
  12125. if (Check.Visit(VDDef->getInit())) {
  12126. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  12127. << getOpenMPClauseName(ClauseKind) << ERange;
  12128. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  12129. continue;
  12130. }
  12131. }
  12132. }
  12133. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  12134. // in a Construct]
  12135. // Variables with the predetermined data-sharing attributes may not be
  12136. // listed in data-sharing attributes clauses, except for the cases
  12137. // listed below. For these exceptions only, listing a predetermined
  12138. // variable in a data-sharing attribute clause is allowed and overrides
  12139. // the variable's predetermined data-sharing attributes.
  12140. // OpenMP [2.14.3.6, Restrictions, p.3]
  12141. // Any number of reduction clauses can be specified on the directive,
  12142. // but a list item can appear only once in the reduction clauses for that
  12143. // directive.
  12144. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  12145. if (DVar.CKind == OMPC_reduction) {
  12146. S.Diag(ELoc, diag::err_omp_once_referenced)
  12147. << getOpenMPClauseName(ClauseKind);
  12148. if (DVar.RefExpr)
  12149. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  12150. continue;
  12151. }
  12152. if (DVar.CKind != OMPC_unknown) {
  12153. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  12154. << getOpenMPClauseName(DVar.CKind)
  12155. << getOpenMPClauseName(OMPC_reduction);
  12156. reportOriginalDsa(S, Stack, D, DVar);
  12157. continue;
  12158. }
  12159. // OpenMP [2.14.3.6, Restrictions, p.1]
  12160. // A list item that appears in a reduction clause of a worksharing
  12161. // construct must be shared in the parallel regions to which any of the
  12162. // worksharing regions arising from the worksharing construct bind.
  12163. if (isOpenMPWorksharingDirective(CurrDir) &&
  12164. !isOpenMPParallelDirective(CurrDir) &&
  12165. !isOpenMPTeamsDirective(CurrDir)) {
  12166. DVar = Stack->getImplicitDSA(D, true);
  12167. if (DVar.CKind != OMPC_shared) {
  12168. S.Diag(ELoc, diag::err_omp_required_access)
  12169. << getOpenMPClauseName(OMPC_reduction)
  12170. << getOpenMPClauseName(OMPC_shared);
  12171. reportOriginalDsa(S, Stack, D, DVar);
  12172. continue;
  12173. }
  12174. }
  12175. }
  12176. // Try to find 'declare reduction' corresponding construct before using
  12177. // builtin/overloaded operators.
  12178. CXXCastPath BasePath;
  12179. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  12180. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  12181. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  12182. if (DeclareReductionRef.isInvalid())
  12183. continue;
  12184. if (S.CurContext->isDependentContext() &&
  12185. (DeclareReductionRef.isUnset() ||
  12186. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  12187. RD.push(RefExpr, DeclareReductionRef.get());
  12188. continue;
  12189. }
  12190. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  12191. // Not allowed reduction identifier is found.
  12192. S.Diag(ReductionId.getBeginLoc(),
  12193. diag::err_omp_unknown_reduction_identifier)
  12194. << Type << ReductionIdRange;
  12195. continue;
  12196. }
  12197. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  12198. // The type of a list item that appears in a reduction clause must be valid
  12199. // for the reduction-identifier. For a max or min reduction in C, the type
  12200. // of the list item must be an allowed arithmetic data type: char, int,
  12201. // float, double, or _Bool, possibly modified with long, short, signed, or
  12202. // unsigned. For a max or min reduction in C++, the type of the list item
  12203. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  12204. // double, or bool, possibly modified with long, short, signed, or unsigned.
  12205. if (DeclareReductionRef.isUnset()) {
  12206. if ((BOK == BO_GT || BOK == BO_LT) &&
  12207. !(Type->isScalarType() ||
  12208. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  12209. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  12210. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  12211. if (!ASE && !OASE) {
  12212. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12213. VarDecl::DeclarationOnly;
  12214. S.Diag(D->getLocation(),
  12215. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12216. << D;
  12217. }
  12218. continue;
  12219. }
  12220. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  12221. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  12222. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  12223. << getOpenMPClauseName(ClauseKind);
  12224. if (!ASE && !OASE) {
  12225. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12226. VarDecl::DeclarationOnly;
  12227. S.Diag(D->getLocation(),
  12228. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12229. << D;
  12230. }
  12231. continue;
  12232. }
  12233. }
  12234. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  12235. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  12236. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12237. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  12238. D->hasAttrs() ? &D->getAttrs() : nullptr);
  12239. QualType PrivateTy = Type;
  12240. // Try if we can determine constant lengths for all array sections and avoid
  12241. // the VLA.
  12242. bool ConstantLengthOASE = false;
  12243. if (OASE) {
  12244. bool SingleElement;
  12245. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  12246. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  12247. Context, OASE, SingleElement, ArraySizes);
  12248. // If we don't have a single element, we must emit a constant array type.
  12249. if (ConstantLengthOASE && !SingleElement) {
  12250. for (llvm::APSInt &Size : ArraySizes)
  12251. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  12252. ArrayType::Normal,
  12253. /*IndexTypeQuals=*/0);
  12254. }
  12255. }
  12256. if ((OASE && !ConstantLengthOASE) ||
  12257. (!OASE && !ASE &&
  12258. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  12259. if (!Context.getTargetInfo().isVLASupported()) {
  12260. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  12261. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12262. S.Diag(ELoc, diag::note_vla_unsupported);
  12263. } else {
  12264. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  12265. S.targetDiag(ELoc, diag::note_vla_unsupported);
  12266. }
  12267. continue;
  12268. }
  12269. // For arrays/array sections only:
  12270. // Create pseudo array type for private copy. The size for this array will
  12271. // be generated during codegen.
  12272. // For array subscripts or single variables Private Ty is the same as Type
  12273. // (type of the variable or single array element).
  12274. PrivateTy = Context.getVariableArrayType(
  12275. Type,
  12276. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  12277. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  12278. } else if (!ASE && !OASE &&
  12279. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  12280. PrivateTy = D->getType().getNonReferenceType();
  12281. }
  12282. // Private copy.
  12283. VarDecl *PrivateVD =
  12284. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  12285. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12286. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12287. // Add initializer for private variable.
  12288. Expr *Init = nullptr;
  12289. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  12290. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  12291. if (DeclareReductionRef.isUsable()) {
  12292. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  12293. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  12294. if (DRD->getInitializer()) {
  12295. Init = DRDRef;
  12296. RHSVD->setInit(DRDRef);
  12297. RHSVD->setInitStyle(VarDecl::CallInit);
  12298. }
  12299. } else {
  12300. switch (BOK) {
  12301. case BO_Add:
  12302. case BO_Xor:
  12303. case BO_Or:
  12304. case BO_LOr:
  12305. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  12306. if (Type->isScalarType() || Type->isAnyComplexType())
  12307. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  12308. break;
  12309. case BO_Mul:
  12310. case BO_LAnd:
  12311. if (Type->isScalarType() || Type->isAnyComplexType()) {
  12312. // '*' and '&&' reduction ops - initializer is '1'.
  12313. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  12314. }
  12315. break;
  12316. case BO_And: {
  12317. // '&' reduction op - initializer is '~0'.
  12318. QualType OrigType = Type;
  12319. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  12320. Type = ComplexTy->getElementType();
  12321. if (Type->isRealFloatingType()) {
  12322. llvm::APFloat InitValue =
  12323. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  12324. /*isIEEE=*/true);
  12325. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12326. Type, ELoc);
  12327. } else if (Type->isScalarType()) {
  12328. uint64_t Size = Context.getTypeSize(Type);
  12329. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  12330. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  12331. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12332. }
  12333. if (Init && OrigType->isAnyComplexType()) {
  12334. // Init = 0xFFFF + 0xFFFFi;
  12335. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  12336. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  12337. }
  12338. Type = OrigType;
  12339. break;
  12340. }
  12341. case BO_LT:
  12342. case BO_GT: {
  12343. // 'min' reduction op - initializer is 'Largest representable number in
  12344. // the reduction list item type'.
  12345. // 'max' reduction op - initializer is 'Least representable number in
  12346. // the reduction list item type'.
  12347. if (Type->isIntegerType() || Type->isPointerType()) {
  12348. bool IsSigned = Type->hasSignedIntegerRepresentation();
  12349. uint64_t Size = Context.getTypeSize(Type);
  12350. QualType IntTy =
  12351. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  12352. llvm::APInt InitValue =
  12353. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  12354. : llvm::APInt::getMinValue(Size)
  12355. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  12356. : llvm::APInt::getMaxValue(Size);
  12357. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  12358. if (Type->isPointerType()) {
  12359. // Cast to pointer type.
  12360. ExprResult CastExpr = S.BuildCStyleCastExpr(
  12361. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  12362. if (CastExpr.isInvalid())
  12363. continue;
  12364. Init = CastExpr.get();
  12365. }
  12366. } else if (Type->isRealFloatingType()) {
  12367. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  12368. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  12369. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  12370. Type, ELoc);
  12371. }
  12372. break;
  12373. }
  12374. case BO_PtrMemD:
  12375. case BO_PtrMemI:
  12376. case BO_MulAssign:
  12377. case BO_Div:
  12378. case BO_Rem:
  12379. case BO_Sub:
  12380. case BO_Shl:
  12381. case BO_Shr:
  12382. case BO_LE:
  12383. case BO_GE:
  12384. case BO_EQ:
  12385. case BO_NE:
  12386. case BO_Cmp:
  12387. case BO_AndAssign:
  12388. case BO_XorAssign:
  12389. case BO_OrAssign:
  12390. case BO_Assign:
  12391. case BO_AddAssign:
  12392. case BO_SubAssign:
  12393. case BO_DivAssign:
  12394. case BO_RemAssign:
  12395. case BO_ShlAssign:
  12396. case BO_ShrAssign:
  12397. case BO_Comma:
  12398. llvm_unreachable("Unexpected reduction operation");
  12399. }
  12400. }
  12401. if (Init && DeclareReductionRef.isUnset())
  12402. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  12403. else if (!Init)
  12404. S.ActOnUninitializedDecl(RHSVD);
  12405. if (RHSVD->isInvalidDecl())
  12406. continue;
  12407. if (!RHSVD->hasInit() &&
  12408. (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
  12409. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  12410. << Type << ReductionIdRange;
  12411. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  12412. VarDecl::DeclarationOnly;
  12413. S.Diag(D->getLocation(),
  12414. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12415. << D;
  12416. continue;
  12417. }
  12418. // Store initializer for single element in private copy. Will be used during
  12419. // codegen.
  12420. PrivateVD->setInit(RHSVD->getInit());
  12421. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  12422. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  12423. ExprResult ReductionOp;
  12424. if (DeclareReductionRef.isUsable()) {
  12425. QualType RedTy = DeclareReductionRef.get()->getType();
  12426. QualType PtrRedTy = Context.getPointerType(RedTy);
  12427. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  12428. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  12429. if (!BasePath.empty()) {
  12430. LHS = S.DefaultLvalueConversion(LHS.get());
  12431. RHS = S.DefaultLvalueConversion(RHS.get());
  12432. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12433. CK_UncheckedDerivedToBase, LHS.get(),
  12434. &BasePath, LHS.get()->getValueKind());
  12435. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  12436. CK_UncheckedDerivedToBase, RHS.get(),
  12437. &BasePath, RHS.get()->getValueKind());
  12438. }
  12439. FunctionProtoType::ExtProtoInfo EPI;
  12440. QualType Params[] = {PtrRedTy, PtrRedTy};
  12441. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  12442. auto *OVE = new (Context) OpaqueValueExpr(
  12443. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  12444. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  12445. Expr *Args[] = {LHS.get(), RHS.get()};
  12446. ReductionOp =
  12447. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  12448. } else {
  12449. ReductionOp = S.BuildBinOp(
  12450. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  12451. if (ReductionOp.isUsable()) {
  12452. if (BOK != BO_LT && BOK != BO_GT) {
  12453. ReductionOp =
  12454. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12455. BO_Assign, LHSDRE, ReductionOp.get());
  12456. } else {
  12457. auto *ConditionalOp = new (Context)
  12458. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  12459. Type, VK_LValue, OK_Ordinary);
  12460. ReductionOp =
  12461. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  12462. BO_Assign, LHSDRE, ConditionalOp);
  12463. }
  12464. if (ReductionOp.isUsable())
  12465. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  12466. /*DiscardedValue*/ false);
  12467. }
  12468. if (!ReductionOp.isUsable())
  12469. continue;
  12470. }
  12471. // OpenMP [2.15.4.6, Restrictions, p.2]
  12472. // A list item that appears in an in_reduction clause of a task construct
  12473. // must appear in a task_reduction clause of a construct associated with a
  12474. // taskgroup region that includes the participating task in its taskgroup
  12475. // set. The construct associated with the innermost region that meets this
  12476. // condition must specify the same reduction-identifier as the in_reduction
  12477. // clause.
  12478. if (ClauseKind == OMPC_in_reduction) {
  12479. SourceRange ParentSR;
  12480. BinaryOperatorKind ParentBOK;
  12481. const Expr *ParentReductionOp;
  12482. Expr *ParentBOKTD, *ParentReductionOpTD;
  12483. DSAStackTy::DSAVarData ParentBOKDSA =
  12484. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  12485. ParentBOKTD);
  12486. DSAStackTy::DSAVarData ParentReductionOpDSA =
  12487. Stack->getTopMostTaskgroupReductionData(
  12488. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  12489. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  12490. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  12491. if (!IsParentBOK && !IsParentReductionOp) {
  12492. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  12493. continue;
  12494. }
  12495. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  12496. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  12497. IsParentReductionOp) {
  12498. bool EmitError = true;
  12499. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  12500. llvm::FoldingSetNodeID RedId, ParentRedId;
  12501. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  12502. DeclareReductionRef.get()->Profile(RedId, Context,
  12503. /*Canonical=*/true);
  12504. EmitError = RedId != ParentRedId;
  12505. }
  12506. if (EmitError) {
  12507. S.Diag(ReductionId.getBeginLoc(),
  12508. diag::err_omp_reduction_identifier_mismatch)
  12509. << ReductionIdRange << RefExpr->getSourceRange();
  12510. S.Diag(ParentSR.getBegin(),
  12511. diag::note_omp_previous_reduction_identifier)
  12512. << ParentSR
  12513. << (IsParentBOK ? ParentBOKDSA.RefExpr
  12514. : ParentReductionOpDSA.RefExpr)
  12515. ->getSourceRange();
  12516. continue;
  12517. }
  12518. }
  12519. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  12520. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  12521. }
  12522. DeclRefExpr *Ref = nullptr;
  12523. Expr *VarsExpr = RefExpr->IgnoreParens();
  12524. if (!VD && !S.CurContext->isDependentContext()) {
  12525. if (ASE || OASE) {
  12526. TransformExprToCaptures RebuildToCapture(S, D);
  12527. VarsExpr =
  12528. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  12529. Ref = RebuildToCapture.getCapturedExpr();
  12530. } else {
  12531. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  12532. }
  12533. if (!S.isOpenMPCapturedDecl(D)) {
  12534. RD.ExprCaptures.emplace_back(Ref->getDecl());
  12535. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12536. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  12537. if (!RefRes.isUsable())
  12538. continue;
  12539. ExprResult PostUpdateRes =
  12540. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  12541. RefRes.get());
  12542. if (!PostUpdateRes.isUsable())
  12543. continue;
  12544. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  12545. Stack->getCurrentDirective() == OMPD_taskgroup) {
  12546. S.Diag(RefExpr->getExprLoc(),
  12547. diag::err_omp_reduction_non_addressable_expression)
  12548. << RefExpr->getSourceRange();
  12549. continue;
  12550. }
  12551. RD.ExprPostUpdates.emplace_back(
  12552. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  12553. }
  12554. }
  12555. }
  12556. // All reduction items are still marked as reduction (to do not increase
  12557. // code base size).
  12558. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  12559. if (CurrDir == OMPD_taskgroup) {
  12560. if (DeclareReductionRef.isUsable())
  12561. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  12562. DeclareReductionRef.get());
  12563. else
  12564. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  12565. }
  12566. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  12567. TaskgroupDescriptor);
  12568. }
  12569. return RD.Vars.empty();
  12570. }
  12571. OMPClause *Sema::ActOnOpenMPReductionClause(
  12572. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12573. SourceLocation ColonLoc, SourceLocation EndLoc,
  12574. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12575. ArrayRef<Expr *> UnresolvedReductions) {
  12576. ReductionData RD(VarList.size());
  12577. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  12578. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12579. ReductionIdScopeSpec, ReductionId,
  12580. UnresolvedReductions, RD))
  12581. return nullptr;
  12582. return OMPReductionClause::Create(
  12583. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12584. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12585. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12586. buildPreInits(Context, RD.ExprCaptures),
  12587. buildPostUpdate(*this, RD.ExprPostUpdates));
  12588. }
  12589. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  12590. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12591. SourceLocation ColonLoc, SourceLocation EndLoc,
  12592. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12593. ArrayRef<Expr *> UnresolvedReductions) {
  12594. ReductionData RD(VarList.size());
  12595. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  12596. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12597. ReductionIdScopeSpec, ReductionId,
  12598. UnresolvedReductions, RD))
  12599. return nullptr;
  12600. return OMPTaskReductionClause::Create(
  12601. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12602. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12603. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  12604. buildPreInits(Context, RD.ExprCaptures),
  12605. buildPostUpdate(*this, RD.ExprPostUpdates));
  12606. }
  12607. OMPClause *Sema::ActOnOpenMPInReductionClause(
  12608. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  12609. SourceLocation ColonLoc, SourceLocation EndLoc,
  12610. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  12611. ArrayRef<Expr *> UnresolvedReductions) {
  12612. ReductionData RD(VarList.size());
  12613. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  12614. StartLoc, LParenLoc, ColonLoc, EndLoc,
  12615. ReductionIdScopeSpec, ReductionId,
  12616. UnresolvedReductions, RD))
  12617. return nullptr;
  12618. return OMPInReductionClause::Create(
  12619. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  12620. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  12621. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  12622. buildPreInits(Context, RD.ExprCaptures),
  12623. buildPostUpdate(*this, RD.ExprPostUpdates));
  12624. }
  12625. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  12626. SourceLocation LinLoc) {
  12627. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  12628. LinKind == OMPC_LINEAR_unknown) {
  12629. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  12630. return true;
  12631. }
  12632. return false;
  12633. }
  12634. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  12635. OpenMPLinearClauseKind LinKind,
  12636. QualType Type) {
  12637. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  12638. // A variable must not have an incomplete type or a reference type.
  12639. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  12640. return true;
  12641. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  12642. !Type->isReferenceType()) {
  12643. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  12644. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  12645. return true;
  12646. }
  12647. Type = Type.getNonReferenceType();
  12648. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  12649. // A variable that is privatized must not have a const-qualified type
  12650. // unless it is of class type with a mutable member. This restriction does
  12651. // not apply to the firstprivate clause.
  12652. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  12653. return true;
  12654. // A list item must be of integral or pointer type.
  12655. Type = Type.getUnqualifiedType().getCanonicalType();
  12656. const auto *Ty = Type.getTypePtrOrNull();
  12657. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  12658. !Ty->isPointerType())) {
  12659. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  12660. if (D) {
  12661. bool IsDecl =
  12662. !VD ||
  12663. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12664. Diag(D->getLocation(),
  12665. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12666. << D;
  12667. }
  12668. return true;
  12669. }
  12670. return false;
  12671. }
  12672. OMPClause *Sema::ActOnOpenMPLinearClause(
  12673. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  12674. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  12675. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12676. SmallVector<Expr *, 8> Vars;
  12677. SmallVector<Expr *, 8> Privates;
  12678. SmallVector<Expr *, 8> Inits;
  12679. SmallVector<Decl *, 4> ExprCaptures;
  12680. SmallVector<Expr *, 4> ExprPostUpdates;
  12681. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  12682. LinKind = OMPC_LINEAR_val;
  12683. for (Expr *RefExpr : VarList) {
  12684. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12685. SourceLocation ELoc;
  12686. SourceRange ERange;
  12687. Expr *SimpleRefExpr = RefExpr;
  12688. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12689. if (Res.second) {
  12690. // It will be analyzed later.
  12691. Vars.push_back(RefExpr);
  12692. Privates.push_back(nullptr);
  12693. Inits.push_back(nullptr);
  12694. }
  12695. ValueDecl *D = Res.first;
  12696. if (!D)
  12697. continue;
  12698. QualType Type = D->getType();
  12699. auto *VD = dyn_cast<VarDecl>(D);
  12700. // OpenMP [2.14.3.7, linear clause]
  12701. // A list-item cannot appear in more than one linear clause.
  12702. // A list-item that appears in a linear clause cannot appear in any
  12703. // other data-sharing attribute clause.
  12704. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12705. if (DVar.RefExpr) {
  12706. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  12707. << getOpenMPClauseName(OMPC_linear);
  12708. reportOriginalDsa(*this, DSAStack, D, DVar);
  12709. continue;
  12710. }
  12711. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  12712. continue;
  12713. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12714. // Build private copy of original var.
  12715. VarDecl *Private =
  12716. buildVarDecl(*this, ELoc, Type, D->getName(),
  12717. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12718. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12719. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  12720. // Build var to save initial value.
  12721. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  12722. Expr *InitExpr;
  12723. DeclRefExpr *Ref = nullptr;
  12724. if (!VD && !CurContext->isDependentContext()) {
  12725. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  12726. if (!isOpenMPCapturedDecl(D)) {
  12727. ExprCaptures.push_back(Ref->getDecl());
  12728. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  12729. ExprResult RefRes = DefaultLvalueConversion(Ref);
  12730. if (!RefRes.isUsable())
  12731. continue;
  12732. ExprResult PostUpdateRes =
  12733. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  12734. SimpleRefExpr, RefRes.get());
  12735. if (!PostUpdateRes.isUsable())
  12736. continue;
  12737. ExprPostUpdates.push_back(
  12738. IgnoredValueConversions(PostUpdateRes.get()).get());
  12739. }
  12740. }
  12741. }
  12742. if (LinKind == OMPC_LINEAR_uval)
  12743. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  12744. else
  12745. InitExpr = VD ? SimpleRefExpr : Ref;
  12746. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  12747. /*DirectInit=*/false);
  12748. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  12749. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  12750. Vars.push_back((VD || CurContext->isDependentContext())
  12751. ? RefExpr->IgnoreParens()
  12752. : Ref);
  12753. Privates.push_back(PrivateRef);
  12754. Inits.push_back(InitRef);
  12755. }
  12756. if (Vars.empty())
  12757. return nullptr;
  12758. Expr *StepExpr = Step;
  12759. Expr *CalcStepExpr = nullptr;
  12760. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  12761. !Step->isInstantiationDependent() &&
  12762. !Step->containsUnexpandedParameterPack()) {
  12763. SourceLocation StepLoc = Step->getBeginLoc();
  12764. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  12765. if (Val.isInvalid())
  12766. return nullptr;
  12767. StepExpr = Val.get();
  12768. // Build var to save the step value.
  12769. VarDecl *SaveVar =
  12770. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  12771. ExprResult SaveRef =
  12772. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  12773. ExprResult CalcStep =
  12774. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  12775. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  12776. // Warn about zero linear step (it would be probably better specified as
  12777. // making corresponding variables 'const').
  12778. llvm::APSInt Result;
  12779. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  12780. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  12781. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  12782. << (Vars.size() > 1);
  12783. if (!IsConstant && CalcStep.isUsable()) {
  12784. // Calculate the step beforehand instead of doing this on each iteration.
  12785. // (This is not used if the number of iterations may be kfold-ed).
  12786. CalcStepExpr = CalcStep.get();
  12787. }
  12788. }
  12789. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  12790. ColonLoc, EndLoc, Vars, Privates, Inits,
  12791. StepExpr, CalcStepExpr,
  12792. buildPreInits(Context, ExprCaptures),
  12793. buildPostUpdate(*this, ExprPostUpdates));
  12794. }
  12795. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  12796. Expr *NumIterations, Sema &SemaRef,
  12797. Scope *S, DSAStackTy *Stack) {
  12798. // Walk the vars and build update/final expressions for the CodeGen.
  12799. SmallVector<Expr *, 8> Updates;
  12800. SmallVector<Expr *, 8> Finals;
  12801. SmallVector<Expr *, 8> UsedExprs;
  12802. Expr *Step = Clause.getStep();
  12803. Expr *CalcStep = Clause.getCalcStep();
  12804. // OpenMP [2.14.3.7, linear clause]
  12805. // If linear-step is not specified it is assumed to be 1.
  12806. if (!Step)
  12807. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  12808. else if (CalcStep)
  12809. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  12810. bool HasErrors = false;
  12811. auto CurInit = Clause.inits().begin();
  12812. auto CurPrivate = Clause.privates().begin();
  12813. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  12814. for (Expr *RefExpr : Clause.varlists()) {
  12815. SourceLocation ELoc;
  12816. SourceRange ERange;
  12817. Expr *SimpleRefExpr = RefExpr;
  12818. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  12819. ValueDecl *D = Res.first;
  12820. if (Res.second || !D) {
  12821. Updates.push_back(nullptr);
  12822. Finals.push_back(nullptr);
  12823. HasErrors = true;
  12824. continue;
  12825. }
  12826. auto &&Info = Stack->isLoopControlVariable(D);
  12827. // OpenMP [2.15.11, distribute simd Construct]
  12828. // A list item may not appear in a linear clause, unless it is the loop
  12829. // iteration variable.
  12830. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  12831. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  12832. SemaRef.Diag(ELoc,
  12833. diag::err_omp_linear_distribute_var_non_loop_iteration);
  12834. Updates.push_back(nullptr);
  12835. Finals.push_back(nullptr);
  12836. HasErrors = true;
  12837. continue;
  12838. }
  12839. Expr *InitExpr = *CurInit;
  12840. // Build privatized reference to the current linear var.
  12841. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  12842. Expr *CapturedRef;
  12843. if (LinKind == OMPC_LINEAR_uval)
  12844. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  12845. else
  12846. CapturedRef =
  12847. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  12848. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  12849. /*RefersToCapture=*/true);
  12850. // Build update: Var = InitExpr + IV * Step
  12851. ExprResult Update;
  12852. if (!Info.first)
  12853. Update = buildCounterUpdate(
  12854. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  12855. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  12856. else
  12857. Update = *CurPrivate;
  12858. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  12859. /*DiscardedValue*/ false);
  12860. // Build final: Var = InitExpr + NumIterations * Step
  12861. ExprResult Final;
  12862. if (!Info.first)
  12863. Final =
  12864. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  12865. InitExpr, NumIterations, Step, /*Subtract=*/false,
  12866. /*IsNonRectangularLB=*/false);
  12867. else
  12868. Final = *CurPrivate;
  12869. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  12870. /*DiscardedValue*/ false);
  12871. if (!Update.isUsable() || !Final.isUsable()) {
  12872. Updates.push_back(nullptr);
  12873. Finals.push_back(nullptr);
  12874. UsedExprs.push_back(nullptr);
  12875. HasErrors = true;
  12876. } else {
  12877. Updates.push_back(Update.get());
  12878. Finals.push_back(Final.get());
  12879. if (!Info.first)
  12880. UsedExprs.push_back(SimpleRefExpr);
  12881. }
  12882. ++CurInit;
  12883. ++CurPrivate;
  12884. }
  12885. if (Expr *S = Clause.getStep())
  12886. UsedExprs.push_back(S);
  12887. // Fill the remaining part with the nullptr.
  12888. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  12889. Clause.setUpdates(Updates);
  12890. Clause.setFinals(Finals);
  12891. Clause.setUsedExprs(UsedExprs);
  12892. return HasErrors;
  12893. }
  12894. OMPClause *Sema::ActOnOpenMPAlignedClause(
  12895. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  12896. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  12897. SmallVector<Expr *, 8> Vars;
  12898. for (Expr *RefExpr : VarList) {
  12899. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  12900. SourceLocation ELoc;
  12901. SourceRange ERange;
  12902. Expr *SimpleRefExpr = RefExpr;
  12903. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12904. if (Res.second) {
  12905. // It will be analyzed later.
  12906. Vars.push_back(RefExpr);
  12907. }
  12908. ValueDecl *D = Res.first;
  12909. if (!D)
  12910. continue;
  12911. QualType QType = D->getType();
  12912. auto *VD = dyn_cast<VarDecl>(D);
  12913. // OpenMP [2.8.1, simd construct, Restrictions]
  12914. // The type of list items appearing in the aligned clause must be
  12915. // array, pointer, reference to array, or reference to pointer.
  12916. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  12917. const Type *Ty = QType.getTypePtrOrNull();
  12918. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  12919. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  12920. << QType << getLangOpts().CPlusPlus << ERange;
  12921. bool IsDecl =
  12922. !VD ||
  12923. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  12924. Diag(D->getLocation(),
  12925. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  12926. << D;
  12927. continue;
  12928. }
  12929. // OpenMP [2.8.1, simd construct, Restrictions]
  12930. // A list-item cannot appear in more than one aligned clause.
  12931. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  12932. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  12933. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  12934. << getOpenMPClauseName(OMPC_aligned);
  12935. continue;
  12936. }
  12937. DeclRefExpr *Ref = nullptr;
  12938. if (!VD && isOpenMPCapturedDecl(D))
  12939. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12940. Vars.push_back(DefaultFunctionArrayConversion(
  12941. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  12942. .get());
  12943. }
  12944. // OpenMP [2.8.1, simd construct, Description]
  12945. // The parameter of the aligned clause, alignment, must be a constant
  12946. // positive integer expression.
  12947. // If no optional parameter is specified, implementation-defined default
  12948. // alignments for SIMD instructions on the target platforms are assumed.
  12949. if (Alignment != nullptr) {
  12950. ExprResult AlignResult =
  12951. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  12952. if (AlignResult.isInvalid())
  12953. return nullptr;
  12954. Alignment = AlignResult.get();
  12955. }
  12956. if (Vars.empty())
  12957. return nullptr;
  12958. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  12959. EndLoc, Vars, Alignment);
  12960. }
  12961. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  12962. SourceLocation StartLoc,
  12963. SourceLocation LParenLoc,
  12964. SourceLocation EndLoc) {
  12965. SmallVector<Expr *, 8> Vars;
  12966. SmallVector<Expr *, 8> SrcExprs;
  12967. SmallVector<Expr *, 8> DstExprs;
  12968. SmallVector<Expr *, 8> AssignmentOps;
  12969. for (Expr *RefExpr : VarList) {
  12970. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  12971. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  12972. // It will be analyzed later.
  12973. Vars.push_back(RefExpr);
  12974. SrcExprs.push_back(nullptr);
  12975. DstExprs.push_back(nullptr);
  12976. AssignmentOps.push_back(nullptr);
  12977. continue;
  12978. }
  12979. SourceLocation ELoc = RefExpr->getExprLoc();
  12980. // OpenMP [2.1, C/C++]
  12981. // A list item is a variable name.
  12982. // OpenMP [2.14.4.1, Restrictions, p.1]
  12983. // A list item that appears in a copyin clause must be threadprivate.
  12984. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  12985. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  12986. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  12987. << 0 << RefExpr->getSourceRange();
  12988. continue;
  12989. }
  12990. Decl *D = DE->getDecl();
  12991. auto *VD = cast<VarDecl>(D);
  12992. QualType Type = VD->getType();
  12993. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  12994. // It will be analyzed later.
  12995. Vars.push_back(DE);
  12996. SrcExprs.push_back(nullptr);
  12997. DstExprs.push_back(nullptr);
  12998. AssignmentOps.push_back(nullptr);
  12999. continue;
  13000. }
  13001. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  13002. // A list item that appears in a copyin clause must be threadprivate.
  13003. if (!DSAStack->isThreadPrivate(VD)) {
  13004. Diag(ELoc, diag::err_omp_required_access)
  13005. << getOpenMPClauseName(OMPC_copyin)
  13006. << getOpenMPDirectiveName(OMPD_threadprivate);
  13007. continue;
  13008. }
  13009. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13010. // A variable of class type (or array thereof) that appears in a
  13011. // copyin clause requires an accessible, unambiguous copy assignment
  13012. // operator for the class type.
  13013. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  13014. VarDecl *SrcVD =
  13015. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  13016. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  13017. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  13018. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  13019. VarDecl *DstVD =
  13020. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  13021. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  13022. DeclRefExpr *PseudoDstExpr =
  13023. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  13024. // For arrays generate assignment operation for single element and replace
  13025. // it by the original array element in CodeGen.
  13026. ExprResult AssignmentOp =
  13027. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  13028. PseudoSrcExpr);
  13029. if (AssignmentOp.isInvalid())
  13030. continue;
  13031. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  13032. /*DiscardedValue*/ false);
  13033. if (AssignmentOp.isInvalid())
  13034. continue;
  13035. DSAStack->addDSA(VD, DE, OMPC_copyin);
  13036. Vars.push_back(DE);
  13037. SrcExprs.push_back(PseudoSrcExpr);
  13038. DstExprs.push_back(PseudoDstExpr);
  13039. AssignmentOps.push_back(AssignmentOp.get());
  13040. }
  13041. if (Vars.empty())
  13042. return nullptr;
  13043. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  13044. SrcExprs, DstExprs, AssignmentOps);
  13045. }
  13046. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  13047. SourceLocation StartLoc,
  13048. SourceLocation LParenLoc,
  13049. SourceLocation EndLoc) {
  13050. SmallVector<Expr *, 8> Vars;
  13051. SmallVector<Expr *, 8> SrcExprs;
  13052. SmallVector<Expr *, 8> DstExprs;
  13053. SmallVector<Expr *, 8> AssignmentOps;
  13054. for (Expr *RefExpr : VarList) {
  13055. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  13056. SourceLocation ELoc;
  13057. SourceRange ERange;
  13058. Expr *SimpleRefExpr = RefExpr;
  13059. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13060. if (Res.second) {
  13061. // It will be analyzed later.
  13062. Vars.push_back(RefExpr);
  13063. SrcExprs.push_back(nullptr);
  13064. DstExprs.push_back(nullptr);
  13065. AssignmentOps.push_back(nullptr);
  13066. }
  13067. ValueDecl *D = Res.first;
  13068. if (!D)
  13069. continue;
  13070. QualType Type = D->getType();
  13071. auto *VD = dyn_cast<VarDecl>(D);
  13072. // OpenMP [2.14.4.2, Restrictions, p.2]
  13073. // A list item that appears in a copyprivate clause may not appear in a
  13074. // private or firstprivate clause on the single construct.
  13075. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  13076. DSAStackTy::DSAVarData DVar =
  13077. DSAStack->getTopDSA(D, /*FromParent=*/false);
  13078. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  13079. DVar.RefExpr) {
  13080. Diag(ELoc, diag::err_omp_wrong_dsa)
  13081. << getOpenMPClauseName(DVar.CKind)
  13082. << getOpenMPClauseName(OMPC_copyprivate);
  13083. reportOriginalDsa(*this, DSAStack, D, DVar);
  13084. continue;
  13085. }
  13086. // OpenMP [2.11.4.2, Restrictions, p.1]
  13087. // All list items that appear in a copyprivate clause must be either
  13088. // threadprivate or private in the enclosing context.
  13089. if (DVar.CKind == OMPC_unknown) {
  13090. DVar = DSAStack->getImplicitDSA(D, false);
  13091. if (DVar.CKind == OMPC_shared) {
  13092. Diag(ELoc, diag::err_omp_required_access)
  13093. << getOpenMPClauseName(OMPC_copyprivate)
  13094. << "threadprivate or private in the enclosing context";
  13095. reportOriginalDsa(*this, DSAStack, D, DVar);
  13096. continue;
  13097. }
  13098. }
  13099. }
  13100. // Variably modified types are not supported.
  13101. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  13102. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  13103. << getOpenMPClauseName(OMPC_copyprivate) << Type
  13104. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13105. bool IsDecl =
  13106. !VD ||
  13107. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  13108. Diag(D->getLocation(),
  13109. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  13110. << D;
  13111. continue;
  13112. }
  13113. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  13114. // A variable of class type (or array thereof) that appears in a
  13115. // copyin clause requires an accessible, unambiguous copy assignment
  13116. // operator for the class type.
  13117. Type = Context.getBaseElementType(Type.getNonReferenceType())
  13118. .getUnqualifiedType();
  13119. VarDecl *SrcVD =
  13120. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  13121. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13122. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  13123. VarDecl *DstVD =
  13124. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  13125. D->hasAttrs() ? &D->getAttrs() : nullptr);
  13126. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  13127. ExprResult AssignmentOp = BuildBinOp(
  13128. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  13129. if (AssignmentOp.isInvalid())
  13130. continue;
  13131. AssignmentOp =
  13132. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  13133. if (AssignmentOp.isInvalid())
  13134. continue;
  13135. // No need to mark vars as copyprivate, they are already threadprivate or
  13136. // implicitly private.
  13137. assert(VD || isOpenMPCapturedDecl(D));
  13138. Vars.push_back(
  13139. VD ? RefExpr->IgnoreParens()
  13140. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  13141. SrcExprs.push_back(PseudoSrcExpr);
  13142. DstExprs.push_back(PseudoDstExpr);
  13143. AssignmentOps.push_back(AssignmentOp.get());
  13144. }
  13145. if (Vars.empty())
  13146. return nullptr;
  13147. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13148. Vars, SrcExprs, DstExprs, AssignmentOps);
  13149. }
  13150. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  13151. SourceLocation StartLoc,
  13152. SourceLocation LParenLoc,
  13153. SourceLocation EndLoc) {
  13154. if (VarList.empty())
  13155. return nullptr;
  13156. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  13157. }
  13158. OMPClause *
  13159. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  13160. SourceLocation DepLoc, SourceLocation ColonLoc,
  13161. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13162. SourceLocation LParenLoc, SourceLocation EndLoc) {
  13163. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  13164. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  13165. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13166. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  13167. return nullptr;
  13168. }
  13169. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  13170. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  13171. DepKind == OMPC_DEPEND_sink)) {
  13172. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  13173. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  13174. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  13175. /*Last=*/OMPC_DEPEND_unknown, Except)
  13176. << getOpenMPClauseName(OMPC_depend);
  13177. return nullptr;
  13178. }
  13179. SmallVector<Expr *, 8> Vars;
  13180. DSAStackTy::OperatorOffsetTy OpsOffs;
  13181. llvm::APSInt DepCounter(/*BitWidth=*/32);
  13182. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  13183. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  13184. if (const Expr *OrderedCountExpr =
  13185. DSAStack->getParentOrderedRegionParam().first) {
  13186. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  13187. TotalDepCount.setIsUnsigned(/*Val=*/true);
  13188. }
  13189. }
  13190. for (Expr *RefExpr : VarList) {
  13191. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  13192. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  13193. // It will be analyzed later.
  13194. Vars.push_back(RefExpr);
  13195. continue;
  13196. }
  13197. SourceLocation ELoc = RefExpr->getExprLoc();
  13198. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  13199. if (DepKind == OMPC_DEPEND_sink) {
  13200. if (DSAStack->getParentOrderedRegionParam().first &&
  13201. DepCounter >= TotalDepCount) {
  13202. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  13203. continue;
  13204. }
  13205. ++DepCounter;
  13206. // OpenMP [2.13.9, Summary]
  13207. // depend(dependence-type : vec), where dependence-type is:
  13208. // 'sink' and where vec is the iteration vector, which has the form:
  13209. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  13210. // where n is the value specified by the ordered clause in the loop
  13211. // directive, xi denotes the loop iteration variable of the i-th nested
  13212. // loop associated with the loop directive, and di is a constant
  13213. // non-negative integer.
  13214. if (CurContext->isDependentContext()) {
  13215. // It will be analyzed later.
  13216. Vars.push_back(RefExpr);
  13217. continue;
  13218. }
  13219. SimpleExpr = SimpleExpr->IgnoreImplicit();
  13220. OverloadedOperatorKind OOK = OO_None;
  13221. SourceLocation OOLoc;
  13222. Expr *LHS = SimpleExpr;
  13223. Expr *RHS = nullptr;
  13224. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  13225. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  13226. OOLoc = BO->getOperatorLoc();
  13227. LHS = BO->getLHS()->IgnoreParenImpCasts();
  13228. RHS = BO->getRHS()->IgnoreParenImpCasts();
  13229. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  13230. OOK = OCE->getOperator();
  13231. OOLoc = OCE->getOperatorLoc();
  13232. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13233. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  13234. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  13235. OOK = MCE->getMethodDecl()
  13236. ->getNameInfo()
  13237. .getName()
  13238. .getCXXOverloadedOperator();
  13239. OOLoc = MCE->getCallee()->getExprLoc();
  13240. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  13241. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  13242. }
  13243. SourceLocation ELoc;
  13244. SourceRange ERange;
  13245. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  13246. if (Res.second) {
  13247. // It will be analyzed later.
  13248. Vars.push_back(RefExpr);
  13249. }
  13250. ValueDecl *D = Res.first;
  13251. if (!D)
  13252. continue;
  13253. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  13254. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  13255. continue;
  13256. }
  13257. if (RHS) {
  13258. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  13259. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  13260. if (RHSRes.isInvalid())
  13261. continue;
  13262. }
  13263. if (!CurContext->isDependentContext() &&
  13264. DSAStack->getParentOrderedRegionParam().first &&
  13265. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  13266. const ValueDecl *VD =
  13267. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  13268. if (VD)
  13269. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13270. << 1 << VD;
  13271. else
  13272. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  13273. continue;
  13274. }
  13275. OpsOffs.emplace_back(RHS, OOK);
  13276. } else {
  13277. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  13278. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  13279. (ASE &&
  13280. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  13281. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  13282. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13283. << RefExpr->getSourceRange();
  13284. continue;
  13285. }
  13286. ExprResult Res;
  13287. {
  13288. Sema::TentativeAnalysisScope Trap(*this);
  13289. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  13290. RefExpr->IgnoreParenImpCasts());
  13291. }
  13292. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  13293. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  13294. << RefExpr->getSourceRange();
  13295. continue;
  13296. }
  13297. }
  13298. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  13299. }
  13300. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  13301. TotalDepCount > VarList.size() &&
  13302. DSAStack->getParentOrderedRegionParam().first &&
  13303. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  13304. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  13305. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  13306. }
  13307. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  13308. Vars.empty())
  13309. return nullptr;
  13310. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  13311. DepKind, DepLoc, ColonLoc, Vars,
  13312. TotalDepCount.getZExtValue());
  13313. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  13314. DSAStack->isParentOrderedRegion())
  13315. DSAStack->addDoacrossDependClause(C, OpsOffs);
  13316. return C;
  13317. }
  13318. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  13319. SourceLocation LParenLoc,
  13320. SourceLocation EndLoc) {
  13321. Expr *ValExpr = Device;
  13322. Stmt *HelperValStmt = nullptr;
  13323. // OpenMP [2.9.1, Restrictions]
  13324. // The device expression must evaluate to a non-negative integer value.
  13325. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  13326. /*StrictlyPositive=*/false))
  13327. return nullptr;
  13328. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13329. OpenMPDirectiveKind CaptureRegion =
  13330. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  13331. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13332. ValExpr = MakeFullExpr(ValExpr).get();
  13333. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13334. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13335. HelperValStmt = buildPreInits(Context, Captures);
  13336. }
  13337. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  13338. StartLoc, LParenLoc, EndLoc);
  13339. }
  13340. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  13341. DSAStackTy *Stack, QualType QTy,
  13342. bool FullCheck = true) {
  13343. NamedDecl *ND;
  13344. if (QTy->isIncompleteType(&ND)) {
  13345. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  13346. return false;
  13347. }
  13348. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  13349. !QTy.isTrivialType(SemaRef.Context))
  13350. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  13351. return true;
  13352. }
  13353. /// Return true if it can be proven that the provided array expression
  13354. /// (array section or array subscript) does NOT specify the whole size of the
  13355. /// array whose base type is \a BaseQTy.
  13356. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  13357. const Expr *E,
  13358. QualType BaseQTy) {
  13359. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13360. // If this is an array subscript, it refers to the whole size if the size of
  13361. // the dimension is constant and equals 1. Also, an array section assumes the
  13362. // format of an array subscript if no colon is used.
  13363. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  13364. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13365. return ATy->getSize().getSExtValue() != 1;
  13366. // Size can't be evaluated statically.
  13367. return false;
  13368. }
  13369. assert(OASE && "Expecting array section if not an array subscript.");
  13370. const Expr *LowerBound = OASE->getLowerBound();
  13371. const Expr *Length = OASE->getLength();
  13372. // If there is a lower bound that does not evaluates to zero, we are not
  13373. // covering the whole dimension.
  13374. if (LowerBound) {
  13375. Expr::EvalResult Result;
  13376. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13377. return false; // Can't get the integer value as a constant.
  13378. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  13379. if (ConstLowerBound.getSExtValue())
  13380. return true;
  13381. }
  13382. // If we don't have a length we covering the whole dimension.
  13383. if (!Length)
  13384. return false;
  13385. // If the base is a pointer, we don't have a way to get the size of the
  13386. // pointee.
  13387. if (BaseQTy->isPointerType())
  13388. return false;
  13389. // We can only check if the length is the same as the size of the dimension
  13390. // if we have a constant array.
  13391. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  13392. if (!CATy)
  13393. return false;
  13394. Expr::EvalResult Result;
  13395. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13396. return false; // Can't get the integer value as a constant.
  13397. llvm::APSInt ConstLength = Result.Val.getInt();
  13398. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  13399. }
  13400. // Return true if it can be proven that the provided array expression (array
  13401. // section or array subscript) does NOT specify a single element of the array
  13402. // whose base type is \a BaseQTy.
  13403. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  13404. const Expr *E,
  13405. QualType BaseQTy) {
  13406. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  13407. // An array subscript always refer to a single element. Also, an array section
  13408. // assumes the format of an array subscript if no colon is used.
  13409. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  13410. return false;
  13411. assert(OASE && "Expecting array section if not an array subscript.");
  13412. const Expr *Length = OASE->getLength();
  13413. // If we don't have a length we have to check if the array has unitary size
  13414. // for this dimension. Also, we should always expect a length if the base type
  13415. // is pointer.
  13416. if (!Length) {
  13417. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  13418. return ATy->getSize().getSExtValue() != 1;
  13419. // We cannot assume anything.
  13420. return false;
  13421. }
  13422. // Check if the length evaluates to 1.
  13423. Expr::EvalResult Result;
  13424. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  13425. return false; // Can't get the integer value as a constant.
  13426. llvm::APSInt ConstLength = Result.Val.getInt();
  13427. return ConstLength.getSExtValue() != 1;
  13428. }
  13429. // Return the expression of the base of the mappable expression or null if it
  13430. // cannot be determined and do all the necessary checks to see if the expression
  13431. // is valid as a standalone mappable expression. In the process, record all the
  13432. // components of the expression.
  13433. static const Expr *checkMapClauseExpressionBase(
  13434. Sema &SemaRef, Expr *E,
  13435. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  13436. OpenMPClauseKind CKind, bool NoDiagnose) {
  13437. SourceLocation ELoc = E->getExprLoc();
  13438. SourceRange ERange = E->getSourceRange();
  13439. // The base of elements of list in a map clause have to be either:
  13440. // - a reference to variable or field.
  13441. // - a member expression.
  13442. // - an array expression.
  13443. //
  13444. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  13445. // reference to 'r'.
  13446. //
  13447. // If we have:
  13448. //
  13449. // struct SS {
  13450. // Bla S;
  13451. // foo() {
  13452. // #pragma omp target map (S.Arr[:12]);
  13453. // }
  13454. // }
  13455. //
  13456. // We want to retrieve the member expression 'this->S';
  13457. const Expr *RelevantExpr = nullptr;
  13458. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  13459. // If a list item is an array section, it must specify contiguous storage.
  13460. //
  13461. // For this restriction it is sufficient that we make sure only references
  13462. // to variables or fields and array expressions, and that no array sections
  13463. // exist except in the rightmost expression (unless they cover the whole
  13464. // dimension of the array). E.g. these would be invalid:
  13465. //
  13466. // r.ArrS[3:5].Arr[6:7]
  13467. //
  13468. // r.ArrS[3:5].x
  13469. //
  13470. // but these would be valid:
  13471. // r.ArrS[3].Arr[6:7]
  13472. //
  13473. // r.ArrS[3].x
  13474. bool AllowUnitySizeArraySection = true;
  13475. bool AllowWholeSizeArraySection = true;
  13476. while (!RelevantExpr) {
  13477. E = E->IgnoreParenImpCasts();
  13478. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  13479. if (!isa<VarDecl>(CurE->getDecl()))
  13480. return nullptr;
  13481. RelevantExpr = CurE;
  13482. // If we got a reference to a declaration, we should not expect any array
  13483. // section before that.
  13484. AllowUnitySizeArraySection = false;
  13485. AllowWholeSizeArraySection = false;
  13486. // Record the component.
  13487. CurComponents.emplace_back(CurE, CurE->getDecl());
  13488. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  13489. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  13490. if (isa<CXXThisExpr>(BaseE))
  13491. // We found a base expression: this->Val.
  13492. RelevantExpr = CurE;
  13493. else
  13494. E = BaseE;
  13495. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  13496. if (!NoDiagnose) {
  13497. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  13498. << CurE->getSourceRange();
  13499. return nullptr;
  13500. }
  13501. if (RelevantExpr)
  13502. return nullptr;
  13503. continue;
  13504. }
  13505. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  13506. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  13507. // A bit-field cannot appear in a map clause.
  13508. //
  13509. if (FD->isBitField()) {
  13510. if (!NoDiagnose) {
  13511. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  13512. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  13513. return nullptr;
  13514. }
  13515. if (RelevantExpr)
  13516. return nullptr;
  13517. continue;
  13518. }
  13519. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13520. // If the type of a list item is a reference to a type T then the type
  13521. // will be considered to be T for all purposes of this clause.
  13522. QualType CurType = BaseE->getType().getNonReferenceType();
  13523. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  13524. // A list item cannot be a variable that is a member of a structure with
  13525. // a union type.
  13526. //
  13527. if (CurType->isUnionType()) {
  13528. if (!NoDiagnose) {
  13529. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  13530. << CurE->getSourceRange();
  13531. return nullptr;
  13532. }
  13533. continue;
  13534. }
  13535. // If we got a member expression, we should not expect any array section
  13536. // before that:
  13537. //
  13538. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  13539. // If a list item is an element of a structure, only the rightmost symbol
  13540. // of the variable reference can be an array section.
  13541. //
  13542. AllowUnitySizeArraySection = false;
  13543. AllowWholeSizeArraySection = false;
  13544. // Record the component.
  13545. CurComponents.emplace_back(CurE, FD);
  13546. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  13547. E = CurE->getBase()->IgnoreParenImpCasts();
  13548. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  13549. if (!NoDiagnose) {
  13550. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13551. << 0 << CurE->getSourceRange();
  13552. return nullptr;
  13553. }
  13554. continue;
  13555. }
  13556. // If we got an array subscript that express the whole dimension we
  13557. // can have any array expressions before. If it only expressing part of
  13558. // the dimension, we can only have unitary-size array expressions.
  13559. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  13560. E->getType()))
  13561. AllowWholeSizeArraySection = false;
  13562. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13563. Expr::EvalResult Result;
  13564. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  13565. if (!Result.Val.getInt().isNullValue()) {
  13566. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13567. diag::err_omp_invalid_map_this_expr);
  13568. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  13569. diag::note_omp_invalid_subscript_on_this_ptr_map);
  13570. }
  13571. }
  13572. RelevantExpr = TE;
  13573. }
  13574. // Record the component - we don't have any declaration associated.
  13575. CurComponents.emplace_back(CurE, nullptr);
  13576. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  13577. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  13578. E = CurE->getBase()->IgnoreParenImpCasts();
  13579. QualType CurType =
  13580. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13581. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13582. // If the type of a list item is a reference to a type T then the type
  13583. // will be considered to be T for all purposes of this clause.
  13584. if (CurType->isReferenceType())
  13585. CurType = CurType->getPointeeType();
  13586. bool IsPointer = CurType->isAnyPointerType();
  13587. if (!IsPointer && !CurType->isArrayType()) {
  13588. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  13589. << 0 << CurE->getSourceRange();
  13590. return nullptr;
  13591. }
  13592. bool NotWhole =
  13593. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  13594. bool NotUnity =
  13595. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  13596. if (AllowWholeSizeArraySection) {
  13597. // Any array section is currently allowed. Allowing a whole size array
  13598. // section implies allowing a unity array section as well.
  13599. //
  13600. // If this array section refers to the whole dimension we can still
  13601. // accept other array sections before this one, except if the base is a
  13602. // pointer. Otherwise, only unitary sections are accepted.
  13603. if (NotWhole || IsPointer)
  13604. AllowWholeSizeArraySection = false;
  13605. } else if (AllowUnitySizeArraySection && NotUnity) {
  13606. // A unity or whole array section is not allowed and that is not
  13607. // compatible with the properties of the current array section.
  13608. SemaRef.Diag(
  13609. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  13610. << CurE->getSourceRange();
  13611. return nullptr;
  13612. }
  13613. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  13614. Expr::EvalResult ResultR;
  13615. Expr::EvalResult ResultL;
  13616. if (CurE->getLength()->EvaluateAsInt(ResultR,
  13617. SemaRef.getASTContext())) {
  13618. if (!ResultR.Val.getInt().isOneValue()) {
  13619. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13620. diag::err_omp_invalid_map_this_expr);
  13621. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  13622. diag::note_omp_invalid_length_on_this_ptr_mapping);
  13623. }
  13624. }
  13625. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  13626. ResultL, SemaRef.getASTContext())) {
  13627. if (!ResultL.Val.getInt().isNullValue()) {
  13628. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13629. diag::err_omp_invalid_map_this_expr);
  13630. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  13631. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  13632. }
  13633. }
  13634. RelevantExpr = TE;
  13635. }
  13636. // Record the component - we don't have any declaration associated.
  13637. CurComponents.emplace_back(CurE, nullptr);
  13638. } else {
  13639. if (!NoDiagnose) {
  13640. // If nothing else worked, this is not a valid map clause expression.
  13641. SemaRef.Diag(
  13642. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  13643. << ERange;
  13644. }
  13645. return nullptr;
  13646. }
  13647. }
  13648. return RelevantExpr;
  13649. }
  13650. // Return true if expression E associated with value VD has conflicts with other
  13651. // map information.
  13652. static bool checkMapConflicts(
  13653. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  13654. bool CurrentRegionOnly,
  13655. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  13656. OpenMPClauseKind CKind) {
  13657. assert(VD && E);
  13658. SourceLocation ELoc = E->getExprLoc();
  13659. SourceRange ERange = E->getSourceRange();
  13660. // In order to easily check the conflicts we need to match each component of
  13661. // the expression under test with the components of the expressions that are
  13662. // already in the stack.
  13663. assert(!CurComponents.empty() && "Map clause expression with no components!");
  13664. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  13665. "Map clause expression with unexpected base!");
  13666. // Variables to help detecting enclosing problems in data environment nests.
  13667. bool IsEnclosedByDataEnvironmentExpr = false;
  13668. const Expr *EnclosingExpr = nullptr;
  13669. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  13670. VD, CurrentRegionOnly,
  13671. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  13672. ERange, CKind, &EnclosingExpr,
  13673. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  13674. StackComponents,
  13675. OpenMPClauseKind) {
  13676. assert(!StackComponents.empty() &&
  13677. "Map clause expression with no components!");
  13678. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  13679. "Map clause expression with unexpected base!");
  13680. (void)VD;
  13681. // The whole expression in the stack.
  13682. const Expr *RE = StackComponents.front().getAssociatedExpression();
  13683. // Expressions must start from the same base. Here we detect at which
  13684. // point both expressions diverge from each other and see if we can
  13685. // detect if the memory referred to both expressions is contiguous and
  13686. // do not overlap.
  13687. auto CI = CurComponents.rbegin();
  13688. auto CE = CurComponents.rend();
  13689. auto SI = StackComponents.rbegin();
  13690. auto SE = StackComponents.rend();
  13691. for (; CI != CE && SI != SE; ++CI, ++SI) {
  13692. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  13693. // At most one list item can be an array item derived from a given
  13694. // variable in map clauses of the same construct.
  13695. if (CurrentRegionOnly &&
  13696. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  13697. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  13698. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  13699. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  13700. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  13701. diag::err_omp_multiple_array_items_in_map_clause)
  13702. << CI->getAssociatedExpression()->getSourceRange();
  13703. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  13704. diag::note_used_here)
  13705. << SI->getAssociatedExpression()->getSourceRange();
  13706. return true;
  13707. }
  13708. // Do both expressions have the same kind?
  13709. if (CI->getAssociatedExpression()->getStmtClass() !=
  13710. SI->getAssociatedExpression()->getStmtClass())
  13711. break;
  13712. // Are we dealing with different variables/fields?
  13713. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  13714. break;
  13715. }
  13716. // Check if the extra components of the expressions in the enclosing
  13717. // data environment are redundant for the current base declaration.
  13718. // If they are, the maps completely overlap, which is legal.
  13719. for (; SI != SE; ++SI) {
  13720. QualType Type;
  13721. if (const auto *ASE =
  13722. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  13723. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  13724. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  13725. SI->getAssociatedExpression())) {
  13726. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  13727. Type =
  13728. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  13729. }
  13730. if (Type.isNull() || Type->isAnyPointerType() ||
  13731. checkArrayExpressionDoesNotReferToWholeSize(
  13732. SemaRef, SI->getAssociatedExpression(), Type))
  13733. break;
  13734. }
  13735. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13736. // List items of map clauses in the same construct must not share
  13737. // original storage.
  13738. //
  13739. // If the expressions are exactly the same or one is a subset of the
  13740. // other, it means they are sharing storage.
  13741. if (CI == CE && SI == SE) {
  13742. if (CurrentRegionOnly) {
  13743. if (CKind == OMPC_map) {
  13744. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13745. } else {
  13746. assert(CKind == OMPC_to || CKind == OMPC_from);
  13747. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13748. << ERange;
  13749. }
  13750. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13751. << RE->getSourceRange();
  13752. return true;
  13753. }
  13754. // If we find the same expression in the enclosing data environment,
  13755. // that is legal.
  13756. IsEnclosedByDataEnvironmentExpr = true;
  13757. return false;
  13758. }
  13759. QualType DerivedType =
  13760. std::prev(CI)->getAssociatedDeclaration()->getType();
  13761. SourceLocation DerivedLoc =
  13762. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  13763. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  13764. // If the type of a list item is a reference to a type T then the type
  13765. // will be considered to be T for all purposes of this clause.
  13766. DerivedType = DerivedType.getNonReferenceType();
  13767. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  13768. // A variable for which the type is pointer and an array section
  13769. // derived from that variable must not appear as list items of map
  13770. // clauses of the same construct.
  13771. //
  13772. // Also, cover one of the cases in:
  13773. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13774. // If any part of the original storage of a list item has corresponding
  13775. // storage in the device data environment, all of the original storage
  13776. // must have corresponding storage in the device data environment.
  13777. //
  13778. if (DerivedType->isAnyPointerType()) {
  13779. if (CI == CE || SI == SE) {
  13780. SemaRef.Diag(
  13781. DerivedLoc,
  13782. diag::err_omp_pointer_mapped_along_with_derived_section)
  13783. << DerivedLoc;
  13784. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13785. << RE->getSourceRange();
  13786. return true;
  13787. }
  13788. if (CI->getAssociatedExpression()->getStmtClass() !=
  13789. SI->getAssociatedExpression()->getStmtClass() ||
  13790. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  13791. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  13792. assert(CI != CE && SI != SE);
  13793. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  13794. << DerivedLoc;
  13795. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13796. << RE->getSourceRange();
  13797. return true;
  13798. }
  13799. }
  13800. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  13801. // List items of map clauses in the same construct must not share
  13802. // original storage.
  13803. //
  13804. // An expression is a subset of the other.
  13805. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  13806. if (CKind == OMPC_map) {
  13807. if (CI != CE || SI != SE) {
  13808. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  13809. // a pointer.
  13810. auto Begin =
  13811. CI != CE ? CurComponents.begin() : StackComponents.begin();
  13812. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  13813. auto It = Begin;
  13814. while (It != End && !It->getAssociatedDeclaration())
  13815. std::advance(It, 1);
  13816. assert(It != End &&
  13817. "Expected at least one component with the declaration.");
  13818. if (It != Begin && It->getAssociatedDeclaration()
  13819. ->getType()
  13820. .getCanonicalType()
  13821. ->isAnyPointerType()) {
  13822. IsEnclosedByDataEnvironmentExpr = false;
  13823. EnclosingExpr = nullptr;
  13824. return false;
  13825. }
  13826. }
  13827. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  13828. } else {
  13829. assert(CKind == OMPC_to || CKind == OMPC_from);
  13830. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  13831. << ERange;
  13832. }
  13833. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  13834. << RE->getSourceRange();
  13835. return true;
  13836. }
  13837. // The current expression uses the same base as other expression in the
  13838. // data environment but does not contain it completely.
  13839. if (!CurrentRegionOnly && SI != SE)
  13840. EnclosingExpr = RE;
  13841. // The current expression is a subset of the expression in the data
  13842. // environment.
  13843. IsEnclosedByDataEnvironmentExpr |=
  13844. (!CurrentRegionOnly && CI != CE && SI == SE);
  13845. return false;
  13846. });
  13847. if (CurrentRegionOnly)
  13848. return FoundError;
  13849. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  13850. // If any part of the original storage of a list item has corresponding
  13851. // storage in the device data environment, all of the original storage must
  13852. // have corresponding storage in the device data environment.
  13853. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  13854. // If a list item is an element of a structure, and a different element of
  13855. // the structure has a corresponding list item in the device data environment
  13856. // prior to a task encountering the construct associated with the map clause,
  13857. // then the list item must also have a corresponding list item in the device
  13858. // data environment prior to the task encountering the construct.
  13859. //
  13860. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  13861. SemaRef.Diag(ELoc,
  13862. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  13863. << ERange;
  13864. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  13865. << EnclosingExpr->getSourceRange();
  13866. return true;
  13867. }
  13868. return FoundError;
  13869. }
  13870. // Look up the user-defined mapper given the mapper name and mapped type, and
  13871. // build a reference to it.
  13872. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  13873. CXXScopeSpec &MapperIdScopeSpec,
  13874. const DeclarationNameInfo &MapperId,
  13875. QualType Type,
  13876. Expr *UnresolvedMapper) {
  13877. if (MapperIdScopeSpec.isInvalid())
  13878. return ExprError();
  13879. // Get the actual type for the array type.
  13880. if (Type->isArrayType()) {
  13881. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  13882. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  13883. }
  13884. // Find all user-defined mappers with the given MapperId.
  13885. SmallVector<UnresolvedSet<8>, 4> Lookups;
  13886. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  13887. Lookup.suppressDiagnostics();
  13888. if (S) {
  13889. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  13890. NamedDecl *D = Lookup.getRepresentativeDecl();
  13891. while (S && !S->isDeclScope(D))
  13892. S = S->getParent();
  13893. if (S)
  13894. S = S->getParent();
  13895. Lookups.emplace_back();
  13896. Lookups.back().append(Lookup.begin(), Lookup.end());
  13897. Lookup.clear();
  13898. }
  13899. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  13900. // Extract the user-defined mappers with the given MapperId.
  13901. Lookups.push_back(UnresolvedSet<8>());
  13902. for (NamedDecl *D : ULE->decls()) {
  13903. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  13904. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  13905. Lookups.back().addDecl(DMD);
  13906. }
  13907. }
  13908. // Defer the lookup for dependent types. The results will be passed through
  13909. // UnresolvedMapper on instantiation.
  13910. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  13911. Type->isInstantiationDependentType() ||
  13912. Type->containsUnexpandedParameterPack() ||
  13913. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  13914. return !D->isInvalidDecl() &&
  13915. (D->getType()->isDependentType() ||
  13916. D->getType()->isInstantiationDependentType() ||
  13917. D->getType()->containsUnexpandedParameterPack());
  13918. })) {
  13919. UnresolvedSet<8> URS;
  13920. for (const UnresolvedSet<8> &Set : Lookups) {
  13921. if (Set.empty())
  13922. continue;
  13923. URS.append(Set.begin(), Set.end());
  13924. }
  13925. return UnresolvedLookupExpr::Create(
  13926. SemaRef.Context, /*NamingClass=*/nullptr,
  13927. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  13928. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  13929. }
  13930. SourceLocation Loc = MapperId.getLoc();
  13931. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13932. // The type must be of struct, union or class type in C and C++
  13933. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  13934. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  13935. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  13936. return ExprError();
  13937. }
  13938. // Perform argument dependent lookup.
  13939. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  13940. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  13941. // Return the first user-defined mapper with the desired type.
  13942. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13943. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  13944. if (!D->isInvalidDecl() &&
  13945. SemaRef.Context.hasSameType(D->getType(), Type))
  13946. return D;
  13947. return nullptr;
  13948. }))
  13949. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13950. // Find the first user-defined mapper with a type derived from the desired
  13951. // type.
  13952. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  13953. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  13954. if (!D->isInvalidDecl() &&
  13955. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  13956. !Type.isMoreQualifiedThan(D->getType()))
  13957. return D;
  13958. return nullptr;
  13959. })) {
  13960. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  13961. /*DetectVirtual=*/false);
  13962. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  13963. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  13964. VD->getType().getUnqualifiedType()))) {
  13965. if (SemaRef.CheckBaseClassAccess(
  13966. Loc, VD->getType(), Type, Paths.front(),
  13967. /*DiagID=*/0) != Sema::AR_inaccessible) {
  13968. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  13969. }
  13970. }
  13971. }
  13972. }
  13973. // Report error if a mapper is specified, but cannot be found.
  13974. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  13975. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  13976. << Type << MapperId.getName();
  13977. return ExprError();
  13978. }
  13979. return ExprEmpty();
  13980. }
  13981. namespace {
  13982. // Utility struct that gathers all the related lists associated with a mappable
  13983. // expression.
  13984. struct MappableVarListInfo {
  13985. // The list of expressions.
  13986. ArrayRef<Expr *> VarList;
  13987. // The list of processed expressions.
  13988. SmallVector<Expr *, 16> ProcessedVarList;
  13989. // The mappble components for each expression.
  13990. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  13991. // The base declaration of the variable.
  13992. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  13993. // The reference to the user-defined mapper associated with every expression.
  13994. SmallVector<Expr *, 16> UDMapperList;
  13995. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  13996. // We have a list of components and base declarations for each entry in the
  13997. // variable list.
  13998. VarComponents.reserve(VarList.size());
  13999. VarBaseDeclarations.reserve(VarList.size());
  14000. }
  14001. };
  14002. }
  14003. // Check the validity of the provided variable list for the provided clause kind
  14004. // \a CKind. In the check process the valid expressions, mappable expression
  14005. // components, variables, and user-defined mappers are extracted and used to
  14006. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  14007. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  14008. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  14009. static void checkMappableExpressionList(
  14010. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  14011. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  14012. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  14013. ArrayRef<Expr *> UnresolvedMappers,
  14014. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  14015. bool IsMapTypeImplicit = false) {
  14016. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  14017. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  14018. "Unexpected clause kind with mappable expressions!");
  14019. // If the identifier of user-defined mapper is not specified, it is "default".
  14020. // We do not change the actual name in this clause to distinguish whether a
  14021. // mapper is specified explicitly, i.e., it is not explicitly specified when
  14022. // MapperId.getName() is empty.
  14023. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  14024. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  14025. MapperId.setName(DeclNames.getIdentifier(
  14026. &SemaRef.getASTContext().Idents.get("default")));
  14027. }
  14028. // Iterators to find the current unresolved mapper expression.
  14029. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  14030. bool UpdateUMIt = false;
  14031. Expr *UnresolvedMapper = nullptr;
  14032. // Keep track of the mappable components and base declarations in this clause.
  14033. // Each entry in the list is going to have a list of components associated. We
  14034. // record each set of the components so that we can build the clause later on.
  14035. // In the end we should have the same amount of declarations and component
  14036. // lists.
  14037. for (Expr *RE : MVLI.VarList) {
  14038. assert(RE && "Null expr in omp to/from/map clause");
  14039. SourceLocation ELoc = RE->getExprLoc();
  14040. // Find the current unresolved mapper expression.
  14041. if (UpdateUMIt && UMIt != UMEnd) {
  14042. UMIt++;
  14043. assert(
  14044. UMIt != UMEnd &&
  14045. "Expect the size of UnresolvedMappers to match with that of VarList");
  14046. }
  14047. UpdateUMIt = true;
  14048. if (UMIt != UMEnd)
  14049. UnresolvedMapper = *UMIt;
  14050. const Expr *VE = RE->IgnoreParenLValueCasts();
  14051. if (VE->isValueDependent() || VE->isTypeDependent() ||
  14052. VE->isInstantiationDependent() ||
  14053. VE->containsUnexpandedParameterPack()) {
  14054. // Try to find the associated user-defined mapper.
  14055. ExprResult ER = buildUserDefinedMapperRef(
  14056. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14057. VE->getType().getCanonicalType(), UnresolvedMapper);
  14058. if (ER.isInvalid())
  14059. continue;
  14060. MVLI.UDMapperList.push_back(ER.get());
  14061. // We can only analyze this information once the missing information is
  14062. // resolved.
  14063. MVLI.ProcessedVarList.push_back(RE);
  14064. continue;
  14065. }
  14066. Expr *SimpleExpr = RE->IgnoreParenCasts();
  14067. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  14068. SemaRef.Diag(ELoc,
  14069. diag::err_omp_expected_named_var_member_or_array_expression)
  14070. << RE->getSourceRange();
  14071. continue;
  14072. }
  14073. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  14074. ValueDecl *CurDeclaration = nullptr;
  14075. // Obtain the array or member expression bases if required. Also, fill the
  14076. // components array with all the components identified in the process.
  14077. const Expr *BE = checkMapClauseExpressionBase(
  14078. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  14079. if (!BE)
  14080. continue;
  14081. assert(!CurComponents.empty() &&
  14082. "Invalid mappable expression information.");
  14083. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  14084. // Add store "this" pointer to class in DSAStackTy for future checking
  14085. DSAS->addMappedClassesQualTypes(TE->getType());
  14086. // Try to find the associated user-defined mapper.
  14087. ExprResult ER = buildUserDefinedMapperRef(
  14088. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14089. VE->getType().getCanonicalType(), UnresolvedMapper);
  14090. if (ER.isInvalid())
  14091. continue;
  14092. MVLI.UDMapperList.push_back(ER.get());
  14093. // Skip restriction checking for variable or field declarations
  14094. MVLI.ProcessedVarList.push_back(RE);
  14095. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14096. MVLI.VarComponents.back().append(CurComponents.begin(),
  14097. CurComponents.end());
  14098. MVLI.VarBaseDeclarations.push_back(nullptr);
  14099. continue;
  14100. }
  14101. // For the following checks, we rely on the base declaration which is
  14102. // expected to be associated with the last component. The declaration is
  14103. // expected to be a variable or a field (if 'this' is being mapped).
  14104. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  14105. assert(CurDeclaration && "Null decl on map clause.");
  14106. assert(
  14107. CurDeclaration->isCanonicalDecl() &&
  14108. "Expecting components to have associated only canonical declarations.");
  14109. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  14110. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  14111. assert((VD || FD) && "Only variables or fields are expected here!");
  14112. (void)FD;
  14113. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  14114. // threadprivate variables cannot appear in a map clause.
  14115. // OpenMP 4.5 [2.10.5, target update Construct]
  14116. // threadprivate variables cannot appear in a from clause.
  14117. if (VD && DSAS->isThreadPrivate(VD)) {
  14118. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14119. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  14120. << getOpenMPClauseName(CKind);
  14121. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  14122. continue;
  14123. }
  14124. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14125. // A list item cannot appear in both a map clause and a data-sharing
  14126. // attribute clause on the same construct.
  14127. // Check conflicts with other map clause expressions. We check the conflicts
  14128. // with the current construct separately from the enclosing data
  14129. // environment, because the restrictions are different. We only have to
  14130. // check conflicts across regions for the map clauses.
  14131. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14132. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  14133. break;
  14134. if (CKind == OMPC_map &&
  14135. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  14136. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  14137. break;
  14138. // OpenMP 4.5 [2.10.5, target update Construct]
  14139. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  14140. // If the type of a list item is a reference to a type T then the type will
  14141. // be considered to be T for all purposes of this clause.
  14142. auto I = llvm::find_if(
  14143. CurComponents,
  14144. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  14145. return MC.getAssociatedDeclaration();
  14146. });
  14147. assert(I != CurComponents.end() && "Null decl on map clause.");
  14148. QualType Type =
  14149. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  14150. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  14151. // A list item in a to or from clause must have a mappable type.
  14152. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  14153. // A list item must have a mappable type.
  14154. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  14155. DSAS, Type))
  14156. continue;
  14157. if (CKind == OMPC_map) {
  14158. // target enter data
  14159. // OpenMP [2.10.2, Restrictions, p. 99]
  14160. // A map-type must be specified in all map clauses and must be either
  14161. // to or alloc.
  14162. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  14163. if (DKind == OMPD_target_enter_data &&
  14164. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  14165. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14166. << (IsMapTypeImplicit ? 1 : 0)
  14167. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14168. << getOpenMPDirectiveName(DKind);
  14169. continue;
  14170. }
  14171. // target exit_data
  14172. // OpenMP [2.10.3, Restrictions, p. 102]
  14173. // A map-type must be specified in all map clauses and must be either
  14174. // from, release, or delete.
  14175. if (DKind == OMPD_target_exit_data &&
  14176. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  14177. MapType == OMPC_MAP_delete)) {
  14178. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  14179. << (IsMapTypeImplicit ? 1 : 0)
  14180. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  14181. << getOpenMPDirectiveName(DKind);
  14182. continue;
  14183. }
  14184. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  14185. // A list item cannot appear in both a map clause and a data-sharing
  14186. // attribute clause on the same construct
  14187. //
  14188. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  14189. // A list item cannot appear in both a map clause and a data-sharing
  14190. // attribute clause on the same construct unless the construct is a
  14191. // combined construct.
  14192. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  14193. isOpenMPTargetExecutionDirective(DKind)) ||
  14194. DKind == OMPD_target)) {
  14195. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  14196. if (isOpenMPPrivate(DVar.CKind)) {
  14197. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  14198. << getOpenMPClauseName(DVar.CKind)
  14199. << getOpenMPClauseName(OMPC_map)
  14200. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  14201. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  14202. continue;
  14203. }
  14204. }
  14205. }
  14206. // Try to find the associated user-defined mapper.
  14207. ExprResult ER = buildUserDefinedMapperRef(
  14208. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  14209. Type.getCanonicalType(), UnresolvedMapper);
  14210. if (ER.isInvalid())
  14211. continue;
  14212. MVLI.UDMapperList.push_back(ER.get());
  14213. // Save the current expression.
  14214. MVLI.ProcessedVarList.push_back(RE);
  14215. // Store the components in the stack so that they can be used to check
  14216. // against other clauses later on.
  14217. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  14218. /*WhereFoundClauseKind=*/OMPC_map);
  14219. // Save the components and declaration to create the clause. For purposes of
  14220. // the clause creation, any component list that has has base 'this' uses
  14221. // null as base declaration.
  14222. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  14223. MVLI.VarComponents.back().append(CurComponents.begin(),
  14224. CurComponents.end());
  14225. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  14226. : CurDeclaration);
  14227. }
  14228. }
  14229. OMPClause *Sema::ActOnOpenMPMapClause(
  14230. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  14231. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  14232. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  14233. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  14234. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  14235. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  14236. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  14237. OMPC_MAP_MODIFIER_unknown,
  14238. OMPC_MAP_MODIFIER_unknown};
  14239. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  14240. // Process map-type-modifiers, flag errors for duplicate modifiers.
  14241. unsigned Count = 0;
  14242. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  14243. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  14244. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  14245. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  14246. continue;
  14247. }
  14248. assert(Count < OMPMapClause::NumberOfModifiers &&
  14249. "Modifiers exceed the allowed number of map type modifiers");
  14250. Modifiers[Count] = MapTypeModifiers[I];
  14251. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  14252. ++Count;
  14253. }
  14254. MappableVarListInfo MVLI(VarList);
  14255. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  14256. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  14257. MapType, IsMapTypeImplicit);
  14258. // We need to produce a map clause even if we don't have variables so that
  14259. // other diagnostics related with non-existing map clauses are accurate.
  14260. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  14261. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  14262. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  14263. MapperIdScopeSpec.getWithLocInContext(Context),
  14264. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  14265. }
  14266. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  14267. TypeResult ParsedType) {
  14268. assert(ParsedType.isUsable());
  14269. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  14270. if (ReductionType.isNull())
  14271. return QualType();
  14272. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  14273. // A type name in a declare reduction directive cannot be a function type, an
  14274. // array type, a reference type, or a type qualified with const, volatile or
  14275. // restrict.
  14276. if (ReductionType.hasQualifiers()) {
  14277. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  14278. return QualType();
  14279. }
  14280. if (ReductionType->isFunctionType()) {
  14281. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  14282. return QualType();
  14283. }
  14284. if (ReductionType->isReferenceType()) {
  14285. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  14286. return QualType();
  14287. }
  14288. if (ReductionType->isArrayType()) {
  14289. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  14290. return QualType();
  14291. }
  14292. return ReductionType;
  14293. }
  14294. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  14295. Scope *S, DeclContext *DC, DeclarationName Name,
  14296. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  14297. AccessSpecifier AS, Decl *PrevDeclInScope) {
  14298. SmallVector<Decl *, 8> Decls;
  14299. Decls.reserve(ReductionTypes.size());
  14300. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  14301. forRedeclarationInCurContext());
  14302. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  14303. // A reduction-identifier may not be re-declared in the current scope for the
  14304. // same type or for a type that is compatible according to the base language
  14305. // rules.
  14306. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14307. OMPDeclareReductionDecl *PrevDRD = nullptr;
  14308. bool InCompoundScope = true;
  14309. if (S != nullptr) {
  14310. // Find previous declaration with the same name not referenced in other
  14311. // declarations.
  14312. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14313. InCompoundScope =
  14314. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14315. LookupName(Lookup, S);
  14316. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14317. /*AllowInlineNamespace=*/false);
  14318. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  14319. LookupResult::Filter Filter = Lookup.makeFilter();
  14320. while (Filter.hasNext()) {
  14321. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  14322. if (InCompoundScope) {
  14323. auto I = UsedAsPrevious.find(PrevDecl);
  14324. if (I == UsedAsPrevious.end())
  14325. UsedAsPrevious[PrevDecl] = false;
  14326. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  14327. UsedAsPrevious[D] = true;
  14328. }
  14329. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14330. PrevDecl->getLocation();
  14331. }
  14332. Filter.done();
  14333. if (InCompoundScope) {
  14334. for (const auto &PrevData : UsedAsPrevious) {
  14335. if (!PrevData.second) {
  14336. PrevDRD = PrevData.first;
  14337. break;
  14338. }
  14339. }
  14340. }
  14341. } else if (PrevDeclInScope != nullptr) {
  14342. auto *PrevDRDInScope = PrevDRD =
  14343. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  14344. do {
  14345. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  14346. PrevDRDInScope->getLocation();
  14347. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  14348. } while (PrevDRDInScope != nullptr);
  14349. }
  14350. for (const auto &TyData : ReductionTypes) {
  14351. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  14352. bool Invalid = false;
  14353. if (I != PreviousRedeclTypes.end()) {
  14354. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  14355. << TyData.first;
  14356. Diag(I->second, diag::note_previous_definition);
  14357. Invalid = true;
  14358. }
  14359. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  14360. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  14361. Name, TyData.first, PrevDRD);
  14362. DC->addDecl(DRD);
  14363. DRD->setAccess(AS);
  14364. Decls.push_back(DRD);
  14365. if (Invalid)
  14366. DRD->setInvalidDecl();
  14367. else
  14368. PrevDRD = DRD;
  14369. }
  14370. return DeclGroupPtrTy::make(
  14371. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  14372. }
  14373. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  14374. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14375. // Enter new function scope.
  14376. PushFunctionScope();
  14377. setFunctionHasBranchProtectedScope();
  14378. getCurFunction()->setHasOMPDeclareReductionCombiner();
  14379. if (S != nullptr)
  14380. PushDeclContext(S, DRD);
  14381. else
  14382. CurContext = DRD;
  14383. PushExpressionEvaluationContext(
  14384. ExpressionEvaluationContext::PotentiallyEvaluated);
  14385. QualType ReductionType = DRD->getType();
  14386. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  14387. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  14388. // uses semantics of argument handles by value, but it should be passed by
  14389. // reference. C lang does not support references, so pass all parameters as
  14390. // pointers.
  14391. // Create 'T omp_in;' variable.
  14392. VarDecl *OmpInParm =
  14393. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  14394. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  14395. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  14396. // uses semantics of argument handles by value, but it should be passed by
  14397. // reference. C lang does not support references, so pass all parameters as
  14398. // pointers.
  14399. // Create 'T omp_out;' variable.
  14400. VarDecl *OmpOutParm =
  14401. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  14402. if (S != nullptr) {
  14403. PushOnScopeChains(OmpInParm, S);
  14404. PushOnScopeChains(OmpOutParm, S);
  14405. } else {
  14406. DRD->addDecl(OmpInParm);
  14407. DRD->addDecl(OmpOutParm);
  14408. }
  14409. Expr *InE =
  14410. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  14411. Expr *OutE =
  14412. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  14413. DRD->setCombinerData(InE, OutE);
  14414. }
  14415. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  14416. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14417. DiscardCleanupsInEvaluationContext();
  14418. PopExpressionEvaluationContext();
  14419. PopDeclContext();
  14420. PopFunctionScopeInfo();
  14421. if (Combiner != nullptr)
  14422. DRD->setCombiner(Combiner);
  14423. else
  14424. DRD->setInvalidDecl();
  14425. }
  14426. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  14427. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14428. // Enter new function scope.
  14429. PushFunctionScope();
  14430. setFunctionHasBranchProtectedScope();
  14431. if (S != nullptr)
  14432. PushDeclContext(S, DRD);
  14433. else
  14434. CurContext = DRD;
  14435. PushExpressionEvaluationContext(
  14436. ExpressionEvaluationContext::PotentiallyEvaluated);
  14437. QualType ReductionType = DRD->getType();
  14438. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  14439. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  14440. // uses semantics of argument handles by value, but it should be passed by
  14441. // reference. C lang does not support references, so pass all parameters as
  14442. // pointers.
  14443. // Create 'T omp_priv;' variable.
  14444. VarDecl *OmpPrivParm =
  14445. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  14446. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  14447. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  14448. // uses semantics of argument handles by value, but it should be passed by
  14449. // reference. C lang does not support references, so pass all parameters as
  14450. // pointers.
  14451. // Create 'T omp_orig;' variable.
  14452. VarDecl *OmpOrigParm =
  14453. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  14454. if (S != nullptr) {
  14455. PushOnScopeChains(OmpPrivParm, S);
  14456. PushOnScopeChains(OmpOrigParm, S);
  14457. } else {
  14458. DRD->addDecl(OmpPrivParm);
  14459. DRD->addDecl(OmpOrigParm);
  14460. }
  14461. Expr *OrigE =
  14462. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  14463. Expr *PrivE =
  14464. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  14465. DRD->setInitializerData(OrigE, PrivE);
  14466. return OmpPrivParm;
  14467. }
  14468. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  14469. VarDecl *OmpPrivParm) {
  14470. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  14471. DiscardCleanupsInEvaluationContext();
  14472. PopExpressionEvaluationContext();
  14473. PopDeclContext();
  14474. PopFunctionScopeInfo();
  14475. if (Initializer != nullptr) {
  14476. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  14477. } else if (OmpPrivParm->hasInit()) {
  14478. DRD->setInitializer(OmpPrivParm->getInit(),
  14479. OmpPrivParm->isDirectInit()
  14480. ? OMPDeclareReductionDecl::DirectInit
  14481. : OMPDeclareReductionDecl::CopyInit);
  14482. } else {
  14483. DRD->setInvalidDecl();
  14484. }
  14485. }
  14486. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  14487. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  14488. for (Decl *D : DeclReductions.get()) {
  14489. if (IsValid) {
  14490. if (S)
  14491. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  14492. /*AddToContext=*/false);
  14493. } else {
  14494. D->setInvalidDecl();
  14495. }
  14496. }
  14497. return DeclReductions;
  14498. }
  14499. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  14500. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14501. QualType T = TInfo->getType();
  14502. if (D.isInvalidType())
  14503. return true;
  14504. if (getLangOpts().CPlusPlus) {
  14505. // Check that there are no default arguments (C++ only).
  14506. CheckExtraCXXDefaultArguments(D);
  14507. }
  14508. return CreateParsedType(T, TInfo);
  14509. }
  14510. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  14511. TypeResult ParsedType) {
  14512. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  14513. QualType MapperType = GetTypeFromParser(ParsedType.get());
  14514. assert(!MapperType.isNull() && "Expect valid mapper type");
  14515. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14516. // The type must be of struct, union or class type in C and C++
  14517. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  14518. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  14519. return QualType();
  14520. }
  14521. return MapperType;
  14522. }
  14523. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  14524. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  14525. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  14526. Decl *PrevDeclInScope) {
  14527. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  14528. forRedeclarationInCurContext());
  14529. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  14530. // A mapper-identifier may not be redeclared in the current scope for the
  14531. // same type or for a type that is compatible according to the base language
  14532. // rules.
  14533. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  14534. OMPDeclareMapperDecl *PrevDMD = nullptr;
  14535. bool InCompoundScope = true;
  14536. if (S != nullptr) {
  14537. // Find previous declaration with the same name not referenced in other
  14538. // declarations.
  14539. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  14540. InCompoundScope =
  14541. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  14542. LookupName(Lookup, S);
  14543. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  14544. /*AllowInlineNamespace=*/false);
  14545. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  14546. LookupResult::Filter Filter = Lookup.makeFilter();
  14547. while (Filter.hasNext()) {
  14548. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  14549. if (InCompoundScope) {
  14550. auto I = UsedAsPrevious.find(PrevDecl);
  14551. if (I == UsedAsPrevious.end())
  14552. UsedAsPrevious[PrevDecl] = false;
  14553. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  14554. UsedAsPrevious[D] = true;
  14555. }
  14556. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  14557. PrevDecl->getLocation();
  14558. }
  14559. Filter.done();
  14560. if (InCompoundScope) {
  14561. for (const auto &PrevData : UsedAsPrevious) {
  14562. if (!PrevData.second) {
  14563. PrevDMD = PrevData.first;
  14564. break;
  14565. }
  14566. }
  14567. }
  14568. } else if (PrevDeclInScope) {
  14569. auto *PrevDMDInScope = PrevDMD =
  14570. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  14571. do {
  14572. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  14573. PrevDMDInScope->getLocation();
  14574. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  14575. } while (PrevDMDInScope != nullptr);
  14576. }
  14577. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  14578. bool Invalid = false;
  14579. if (I != PreviousRedeclTypes.end()) {
  14580. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  14581. << MapperType << Name;
  14582. Diag(I->second, diag::note_previous_definition);
  14583. Invalid = true;
  14584. }
  14585. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  14586. MapperType, VN, PrevDMD);
  14587. DC->addDecl(DMD);
  14588. DMD->setAccess(AS);
  14589. if (Invalid)
  14590. DMD->setInvalidDecl();
  14591. // Enter new function scope.
  14592. PushFunctionScope();
  14593. setFunctionHasBranchProtectedScope();
  14594. CurContext = DMD;
  14595. return DMD;
  14596. }
  14597. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  14598. Scope *S,
  14599. QualType MapperType,
  14600. SourceLocation StartLoc,
  14601. DeclarationName VN) {
  14602. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  14603. if (S)
  14604. PushOnScopeChains(VD, S);
  14605. else
  14606. DMD->addDecl(VD);
  14607. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  14608. DMD->setMapperVarRef(MapperVarRefExpr);
  14609. }
  14610. Sema::DeclGroupPtrTy
  14611. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  14612. ArrayRef<OMPClause *> ClauseList) {
  14613. PopDeclContext();
  14614. PopFunctionScopeInfo();
  14615. if (D) {
  14616. if (S)
  14617. PushOnScopeChains(D, S, /*AddToContext=*/false);
  14618. D->CreateClauses(Context, ClauseList);
  14619. }
  14620. return DeclGroupPtrTy::make(DeclGroupRef(D));
  14621. }
  14622. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  14623. SourceLocation StartLoc,
  14624. SourceLocation LParenLoc,
  14625. SourceLocation EndLoc) {
  14626. Expr *ValExpr = NumTeams;
  14627. Stmt *HelperValStmt = nullptr;
  14628. // OpenMP [teams Constrcut, Restrictions]
  14629. // The num_teams expression must evaluate to a positive integer value.
  14630. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  14631. /*StrictlyPositive=*/true))
  14632. return nullptr;
  14633. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14634. OpenMPDirectiveKind CaptureRegion =
  14635. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  14636. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14637. ValExpr = MakeFullExpr(ValExpr).get();
  14638. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14639. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14640. HelperValStmt = buildPreInits(Context, Captures);
  14641. }
  14642. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  14643. StartLoc, LParenLoc, EndLoc);
  14644. }
  14645. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  14646. SourceLocation StartLoc,
  14647. SourceLocation LParenLoc,
  14648. SourceLocation EndLoc) {
  14649. Expr *ValExpr = ThreadLimit;
  14650. Stmt *HelperValStmt = nullptr;
  14651. // OpenMP [teams Constrcut, Restrictions]
  14652. // The thread_limit expression must evaluate to a positive integer value.
  14653. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  14654. /*StrictlyPositive=*/true))
  14655. return nullptr;
  14656. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  14657. OpenMPDirectiveKind CaptureRegion =
  14658. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  14659. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  14660. ValExpr = MakeFullExpr(ValExpr).get();
  14661. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14662. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14663. HelperValStmt = buildPreInits(Context, Captures);
  14664. }
  14665. return new (Context) OMPThreadLimitClause(
  14666. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  14667. }
  14668. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  14669. SourceLocation StartLoc,
  14670. SourceLocation LParenLoc,
  14671. SourceLocation EndLoc) {
  14672. Expr *ValExpr = Priority;
  14673. // OpenMP [2.9.1, task Constrcut]
  14674. // The priority-value is a non-negative numerical scalar expression.
  14675. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  14676. /*StrictlyPositive=*/false))
  14677. return nullptr;
  14678. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14679. }
  14680. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  14681. SourceLocation StartLoc,
  14682. SourceLocation LParenLoc,
  14683. SourceLocation EndLoc) {
  14684. Expr *ValExpr = Grainsize;
  14685. // OpenMP [2.9.2, taskloop Constrcut]
  14686. // The parameter of the grainsize clause must be a positive integer
  14687. // expression.
  14688. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  14689. /*StrictlyPositive=*/true))
  14690. return nullptr;
  14691. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14692. }
  14693. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  14694. SourceLocation StartLoc,
  14695. SourceLocation LParenLoc,
  14696. SourceLocation EndLoc) {
  14697. Expr *ValExpr = NumTasks;
  14698. // OpenMP [2.9.2, taskloop Constrcut]
  14699. // The parameter of the num_tasks clause must be a positive integer
  14700. // expression.
  14701. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  14702. /*StrictlyPositive=*/true))
  14703. return nullptr;
  14704. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  14705. }
  14706. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  14707. SourceLocation LParenLoc,
  14708. SourceLocation EndLoc) {
  14709. // OpenMP [2.13.2, critical construct, Description]
  14710. // ... where hint-expression is an integer constant expression that evaluates
  14711. // to a valid lock hint.
  14712. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  14713. if (HintExpr.isInvalid())
  14714. return nullptr;
  14715. return new (Context)
  14716. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  14717. }
  14718. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  14719. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  14720. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  14721. SourceLocation EndLoc) {
  14722. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  14723. std::string Values;
  14724. Values += "'";
  14725. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  14726. Values += "'";
  14727. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  14728. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  14729. return nullptr;
  14730. }
  14731. Expr *ValExpr = ChunkSize;
  14732. Stmt *HelperValStmt = nullptr;
  14733. if (ChunkSize) {
  14734. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  14735. !ChunkSize->isInstantiationDependent() &&
  14736. !ChunkSize->containsUnexpandedParameterPack()) {
  14737. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  14738. ExprResult Val =
  14739. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  14740. if (Val.isInvalid())
  14741. return nullptr;
  14742. ValExpr = Val.get();
  14743. // OpenMP [2.7.1, Restrictions]
  14744. // chunk_size must be a loop invariant integer expression with a positive
  14745. // value.
  14746. llvm::APSInt Result;
  14747. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  14748. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  14749. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  14750. << "dist_schedule" << ChunkSize->getSourceRange();
  14751. return nullptr;
  14752. }
  14753. } else if (getOpenMPCaptureRegionForClause(
  14754. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  14755. OMPD_unknown &&
  14756. !CurContext->isDependentContext()) {
  14757. ValExpr = MakeFullExpr(ValExpr).get();
  14758. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  14759. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  14760. HelperValStmt = buildPreInits(Context, Captures);
  14761. }
  14762. }
  14763. }
  14764. return new (Context)
  14765. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  14766. Kind, ValExpr, HelperValStmt);
  14767. }
  14768. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  14769. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  14770. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  14771. SourceLocation KindLoc, SourceLocation EndLoc) {
  14772. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  14773. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  14774. std::string Value;
  14775. SourceLocation Loc;
  14776. Value += "'";
  14777. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  14778. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14779. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  14780. Loc = MLoc;
  14781. } else {
  14782. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  14783. OMPC_DEFAULTMAP_scalar);
  14784. Loc = KindLoc;
  14785. }
  14786. Value += "'";
  14787. Diag(Loc, diag::err_omp_unexpected_clause_value)
  14788. << Value << getOpenMPClauseName(OMPC_defaultmap);
  14789. return nullptr;
  14790. }
  14791. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  14792. return new (Context)
  14793. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  14794. }
  14795. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  14796. DeclContext *CurLexicalContext = getCurLexicalContext();
  14797. if (!CurLexicalContext->isFileContext() &&
  14798. !CurLexicalContext->isExternCContext() &&
  14799. !CurLexicalContext->isExternCXXContext() &&
  14800. !isa<CXXRecordDecl>(CurLexicalContext) &&
  14801. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  14802. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  14803. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  14804. Diag(Loc, diag::err_omp_region_not_file_context);
  14805. return false;
  14806. }
  14807. ++DeclareTargetNestingLevel;
  14808. return true;
  14809. }
  14810. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  14811. assert(DeclareTargetNestingLevel > 0 &&
  14812. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  14813. --DeclareTargetNestingLevel;
  14814. }
  14815. NamedDecl *
  14816. Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
  14817. const DeclarationNameInfo &Id,
  14818. NamedDeclSetType &SameDirectiveDecls) {
  14819. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  14820. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  14821. if (Lookup.isAmbiguous())
  14822. return nullptr;
  14823. Lookup.suppressDiagnostics();
  14824. if (!Lookup.isSingleResult()) {
  14825. VarOrFuncDeclFilterCCC CCC(*this);
  14826. if (TypoCorrection Corrected =
  14827. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  14828. CTK_ErrorRecovery)) {
  14829. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  14830. << Id.getName());
  14831. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  14832. return nullptr;
  14833. }
  14834. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  14835. return nullptr;
  14836. }
  14837. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  14838. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  14839. !isa<FunctionTemplateDecl>(ND)) {
  14840. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  14841. return nullptr;
  14842. }
  14843. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  14844. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  14845. return ND;
  14846. }
  14847. void Sema::ActOnOpenMPDeclareTargetName(
  14848. NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
  14849. OMPDeclareTargetDeclAttr::DevTypeTy DT) {
  14850. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  14851. isa<FunctionTemplateDecl>(ND)) &&
  14852. "Expected variable, function or function template.");
  14853. // Diagnose marking after use as it may lead to incorrect diagnosis and
  14854. // codegen.
  14855. if (LangOpts.OpenMP >= 50 &&
  14856. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  14857. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  14858. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14859. OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
  14860. if (DevTy.hasValue() && *DevTy != DT) {
  14861. Diag(Loc, diag::err_omp_device_type_mismatch)
  14862. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
  14863. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
  14864. return;
  14865. }
  14866. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14867. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
  14868. if (!Res) {
  14869. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
  14870. SourceRange(Loc, Loc));
  14871. ND->addAttr(A);
  14872. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14873. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  14874. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  14875. } else if (*Res != MT) {
  14876. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  14877. }
  14878. }
  14879. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  14880. Sema &SemaRef, Decl *D) {
  14881. if (!D || !isa<VarDecl>(D))
  14882. return;
  14883. auto *VD = cast<VarDecl>(D);
  14884. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14885. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14886. if (SemaRef.LangOpts.OpenMP >= 50 &&
  14887. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  14888. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  14889. VD->hasGlobalStorage()) {
  14890. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  14891. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  14892. if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
  14893. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  14894. // If a lambda declaration and definition appears between a
  14895. // declare target directive and the matching end declare target
  14896. // directive, all variables that are captured by the lambda
  14897. // expression must also appear in a to clause.
  14898. SemaRef.Diag(VD->getLocation(),
  14899. diag::err_omp_lambda_capture_in_declare_target_not_to);
  14900. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  14901. << VD << 0 << SR;
  14902. return;
  14903. }
  14904. }
  14905. if (MapTy.hasValue())
  14906. return;
  14907. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  14908. SemaRef.Diag(SL, diag::note_used_here) << SR;
  14909. }
  14910. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  14911. Sema &SemaRef, DSAStackTy *Stack,
  14912. ValueDecl *VD) {
  14913. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  14914. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  14915. /*FullCheck=*/false);
  14916. }
  14917. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  14918. SourceLocation IdLoc) {
  14919. if (!D || D->isInvalidDecl())
  14920. return;
  14921. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  14922. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  14923. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14924. // Only global variables can be marked as declare target.
  14925. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  14926. !VD->isStaticDataMember())
  14927. return;
  14928. // 2.10.6: threadprivate variable cannot appear in a declare target
  14929. // directive.
  14930. if (DSAStack->isThreadPrivate(VD)) {
  14931. Diag(SL, diag::err_omp_threadprivate_in_target);
  14932. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  14933. return;
  14934. }
  14935. }
  14936. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  14937. D = FTD->getTemplatedDecl();
  14938. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14939. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  14940. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  14941. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  14942. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  14943. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  14944. return;
  14945. }
  14946. // Mark the function as must be emitted for the device.
  14947. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  14948. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  14949. if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14950. *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
  14951. checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
  14952. if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
  14953. *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
  14954. checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
  14955. }
  14956. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  14957. // Problem if any with var declared with incomplete type will be reported
  14958. // as normal, so no need to check it here.
  14959. if ((E || !VD->getType()->isIncompleteType()) &&
  14960. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  14961. return;
  14962. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  14963. // Checking declaration inside declare target region.
  14964. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  14965. isa<FunctionTemplateDecl>(D)) {
  14966. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  14967. Context, OMPDeclareTargetDeclAttr::MT_To,
  14968. OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
  14969. D->addAttr(A);
  14970. if (ASTMutationListener *ML = Context.getASTMutationListener())
  14971. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  14972. }
  14973. return;
  14974. }
  14975. }
  14976. if (!E)
  14977. return;
  14978. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  14979. }
  14980. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  14981. CXXScopeSpec &MapperIdScopeSpec,
  14982. DeclarationNameInfo &MapperId,
  14983. const OMPVarListLocTy &Locs,
  14984. ArrayRef<Expr *> UnresolvedMappers) {
  14985. MappableVarListInfo MVLI(VarList);
  14986. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  14987. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  14988. if (MVLI.ProcessedVarList.empty())
  14989. return nullptr;
  14990. return OMPToClause::Create(
  14991. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  14992. MVLI.VarComponents, MVLI.UDMapperList,
  14993. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  14994. }
  14995. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  14996. CXXScopeSpec &MapperIdScopeSpec,
  14997. DeclarationNameInfo &MapperId,
  14998. const OMPVarListLocTy &Locs,
  14999. ArrayRef<Expr *> UnresolvedMappers) {
  15000. MappableVarListInfo MVLI(VarList);
  15001. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  15002. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  15003. if (MVLI.ProcessedVarList.empty())
  15004. return nullptr;
  15005. return OMPFromClause::Create(
  15006. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  15007. MVLI.VarComponents, MVLI.UDMapperList,
  15008. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  15009. }
  15010. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  15011. const OMPVarListLocTy &Locs) {
  15012. MappableVarListInfo MVLI(VarList);
  15013. SmallVector<Expr *, 8> PrivateCopies;
  15014. SmallVector<Expr *, 8> Inits;
  15015. for (Expr *RefExpr : VarList) {
  15016. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  15017. SourceLocation ELoc;
  15018. SourceRange ERange;
  15019. Expr *SimpleRefExpr = RefExpr;
  15020. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15021. if (Res.second) {
  15022. // It will be analyzed later.
  15023. MVLI.ProcessedVarList.push_back(RefExpr);
  15024. PrivateCopies.push_back(nullptr);
  15025. Inits.push_back(nullptr);
  15026. }
  15027. ValueDecl *D = Res.first;
  15028. if (!D)
  15029. continue;
  15030. QualType Type = D->getType();
  15031. Type = Type.getNonReferenceType().getUnqualifiedType();
  15032. auto *VD = dyn_cast<VarDecl>(D);
  15033. // Item should be a pointer or reference to pointer.
  15034. if (!Type->isPointerType()) {
  15035. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  15036. << 0 << RefExpr->getSourceRange();
  15037. continue;
  15038. }
  15039. // Build the private variable and the expression that refers to it.
  15040. auto VDPrivate =
  15041. buildVarDecl(*this, ELoc, Type, D->getName(),
  15042. D->hasAttrs() ? &D->getAttrs() : nullptr,
  15043. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  15044. if (VDPrivate->isInvalidDecl())
  15045. continue;
  15046. CurContext->addDecl(VDPrivate);
  15047. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  15048. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  15049. // Add temporary variable to initialize the private copy of the pointer.
  15050. VarDecl *VDInit =
  15051. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  15052. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  15053. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  15054. AddInitializerToDecl(VDPrivate,
  15055. DefaultLvalueConversion(VDInitRefExpr).get(),
  15056. /*DirectInit=*/false);
  15057. // If required, build a capture to implement the privatization initialized
  15058. // with the current list item value.
  15059. DeclRefExpr *Ref = nullptr;
  15060. if (!VD)
  15061. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  15062. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  15063. PrivateCopies.push_back(VDPrivateRefExpr);
  15064. Inits.push_back(VDInitRefExpr);
  15065. // We need to add a data sharing attribute for this variable to make sure it
  15066. // is correctly captured. A variable that shows up in a use_device_ptr has
  15067. // similar properties of a first private variable.
  15068. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  15069. // Create a mappable component for the list item. List items in this clause
  15070. // only need a component.
  15071. MVLI.VarBaseDeclarations.push_back(D);
  15072. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15073. MVLI.VarComponents.back().push_back(
  15074. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  15075. }
  15076. if (MVLI.ProcessedVarList.empty())
  15077. return nullptr;
  15078. return OMPUseDevicePtrClause::Create(
  15079. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  15080. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  15081. }
  15082. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  15083. const OMPVarListLocTy &Locs) {
  15084. MappableVarListInfo MVLI(VarList);
  15085. for (Expr *RefExpr : VarList) {
  15086. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  15087. SourceLocation ELoc;
  15088. SourceRange ERange;
  15089. Expr *SimpleRefExpr = RefExpr;
  15090. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15091. if (Res.second) {
  15092. // It will be analyzed later.
  15093. MVLI.ProcessedVarList.push_back(RefExpr);
  15094. }
  15095. ValueDecl *D = Res.first;
  15096. if (!D)
  15097. continue;
  15098. QualType Type = D->getType();
  15099. // item should be a pointer or array or reference to pointer or array
  15100. if (!Type.getNonReferenceType()->isPointerType() &&
  15101. !Type.getNonReferenceType()->isArrayType()) {
  15102. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  15103. << 0 << RefExpr->getSourceRange();
  15104. continue;
  15105. }
  15106. // Check if the declaration in the clause does not show up in any data
  15107. // sharing attribute.
  15108. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  15109. if (isOpenMPPrivate(DVar.CKind)) {
  15110. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  15111. << getOpenMPClauseName(DVar.CKind)
  15112. << getOpenMPClauseName(OMPC_is_device_ptr)
  15113. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  15114. reportOriginalDsa(*this, DSAStack, D, DVar);
  15115. continue;
  15116. }
  15117. const Expr *ConflictExpr;
  15118. if (DSAStack->checkMappableExprComponentListsForDecl(
  15119. D, /*CurrentRegionOnly=*/true,
  15120. [&ConflictExpr](
  15121. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  15122. OpenMPClauseKind) -> bool {
  15123. ConflictExpr = R.front().getAssociatedExpression();
  15124. return true;
  15125. })) {
  15126. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  15127. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  15128. << ConflictExpr->getSourceRange();
  15129. continue;
  15130. }
  15131. // Store the components in the stack so that they can be used to check
  15132. // against other clauses later on.
  15133. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  15134. DSAStack->addMappableExpressionComponents(
  15135. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  15136. // Record the expression we've just processed.
  15137. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  15138. // Create a mappable component for the list item. List items in this clause
  15139. // only need a component. We use a null declaration to signal fields in
  15140. // 'this'.
  15141. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  15142. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  15143. "Unexpected device pointer expression!");
  15144. MVLI.VarBaseDeclarations.push_back(
  15145. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  15146. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  15147. MVLI.VarComponents.back().push_back(MC);
  15148. }
  15149. if (MVLI.ProcessedVarList.empty())
  15150. return nullptr;
  15151. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  15152. MVLI.VarBaseDeclarations,
  15153. MVLI.VarComponents);
  15154. }
  15155. OMPClause *Sema::ActOnOpenMPAllocateClause(
  15156. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  15157. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15158. if (Allocator) {
  15159. // OpenMP [2.11.4 allocate Clause, Description]
  15160. // allocator is an expression of omp_allocator_handle_t type.
  15161. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  15162. return nullptr;
  15163. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  15164. if (AllocatorRes.isInvalid())
  15165. return nullptr;
  15166. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  15167. DSAStack->getOMPAllocatorHandleT(),
  15168. Sema::AA_Initializing,
  15169. /*AllowExplicit=*/true);
  15170. if (AllocatorRes.isInvalid())
  15171. return nullptr;
  15172. Allocator = AllocatorRes.get();
  15173. } else {
  15174. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  15175. // allocate clauses that appear on a target construct or on constructs in a
  15176. // target region must specify an allocator expression unless a requires
  15177. // directive with the dynamic_allocators clause is present in the same
  15178. // compilation unit.
  15179. if (LangOpts.OpenMPIsDevice &&
  15180. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  15181. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  15182. }
  15183. // Analyze and build list of variables.
  15184. SmallVector<Expr *, 8> Vars;
  15185. for (Expr *RefExpr : VarList) {
  15186. assert(RefExpr && "NULL expr in OpenMP private clause.");
  15187. SourceLocation ELoc;
  15188. SourceRange ERange;
  15189. Expr *SimpleRefExpr = RefExpr;
  15190. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  15191. if (Res.second) {
  15192. // It will be analyzed later.
  15193. Vars.push_back(RefExpr);
  15194. }
  15195. ValueDecl *D = Res.first;
  15196. if (!D)
  15197. continue;
  15198. auto *VD = dyn_cast<VarDecl>(D);
  15199. DeclRefExpr *Ref = nullptr;
  15200. if (!VD && !CurContext->isDependentContext())
  15201. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  15202. Vars.push_back((VD || CurContext->isDependentContext())
  15203. ? RefExpr->IgnoreParens()
  15204. : Ref);
  15205. }
  15206. if (Vars.empty())
  15207. return nullptr;
  15208. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  15209. ColonLoc, EndLoc, Vars);
  15210. }