SemaOpenMP.cpp 510 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.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 Expr *CheckMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// \brief Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// \brief 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. /// \brief Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy final {
  54. public:
  55. struct DSAVarData final {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
  63. DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
  64. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  65. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  66. };
  67. typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
  68. OperatorOffsetTy;
  69. private:
  70. struct DSAInfo final {
  71. OpenMPClauseKind Attributes = OMPC_unknown;
  72. /// Pointer to a reference expression and a flag which shows that the
  73. /// variable is marked as lastprivate(true) or not (false).
  74. llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
  75. DeclRefExpr *PrivateCopy = nullptr;
  76. };
  77. typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
  78. typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
  79. typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
  80. typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
  81. /// Struct that associates a component with the clause kind where they are
  82. /// found.
  83. struct MappedExprComponentTy {
  84. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  85. OpenMPClauseKind Kind = OMPC_unknown;
  86. };
  87. typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
  88. MappedExprComponentsTy;
  89. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  90. CriticalsWithHintsTy;
  91. typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
  92. DoacrossDependMapTy;
  93. struct ReductionData {
  94. typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
  95. SourceRange ReductionRange;
  96. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  97. ReductionData() = default;
  98. void set(BinaryOperatorKind BO, SourceRange RR) {
  99. ReductionRange = RR;
  100. ReductionOp = BO;
  101. }
  102. void set(const Expr *RefExpr, SourceRange RR) {
  103. ReductionRange = RR;
  104. ReductionOp = RefExpr;
  105. }
  106. };
  107. typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
  108. struct SharingMapTy final {
  109. DeclSAMapTy SharingMap;
  110. DeclReductionMapTy ReductionMap;
  111. AlignedMapTy AlignedMap;
  112. MappedExprComponentsTy MappedExprComponents;
  113. LoopControlVariablesMapTy LCVMap;
  114. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  115. SourceLocation DefaultAttrLoc;
  116. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  117. SourceLocation DefaultMapAttrLoc;
  118. OpenMPDirectiveKind Directive = OMPD_unknown;
  119. DeclarationNameInfo DirectiveName;
  120. Scope *CurScope = nullptr;
  121. SourceLocation ConstructLoc;
  122. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  123. /// get the data (loop counters etc.) about enclosing loop-based construct.
  124. /// This data is required during codegen.
  125. DoacrossDependMapTy DoacrossDepends;
  126. /// \brief first argument (Expr *) contains optional argument of the
  127. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  128. /// clause, false otherwise.
  129. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  130. bool NowaitRegion = false;
  131. bool CancelRegion = false;
  132. unsigned AssociatedLoops = 1;
  133. SourceLocation InnerTeamsRegionLoc;
  134. /// Reference to the taskgroup task_reduction reference expression.
  135. Expr *TaskgroupReductionRef = nullptr;
  136. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  137. Scope *CurScope, SourceLocation Loc)
  138. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  139. ConstructLoc(Loc) {}
  140. SharingMapTy() = default;
  141. };
  142. typedef SmallVector<SharingMapTy, 4> StackTy;
  143. /// \brief Stack of used declaration and their data-sharing attributes.
  144. DeclSAMapTy Threadprivates;
  145. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  146. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  147. /// \brief true, if check for DSA must be from parent directive, false, if
  148. /// from current directive.
  149. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  150. Sema &SemaRef;
  151. bool ForceCapturing = false;
  152. CriticalsWithHintsTy Criticals;
  153. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  154. DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
  155. /// \brief Checks if the variable is a local for OpenMP region.
  156. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  157. bool isStackEmpty() const {
  158. return Stack.empty() ||
  159. Stack.back().second != CurrentNonCapturingFunctionScope ||
  160. Stack.back().first.empty();
  161. }
  162. public:
  163. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  164. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  165. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  166. bool isForceVarCapturing() const { return ForceCapturing; }
  167. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  168. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  169. Scope *CurScope, SourceLocation Loc) {
  170. if (Stack.empty() ||
  171. Stack.back().second != CurrentNonCapturingFunctionScope)
  172. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  173. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  174. Stack.back().first.back().DefaultAttrLoc = Loc;
  175. }
  176. void pop() {
  177. assert(!Stack.back().first.empty() &&
  178. "Data-sharing attributes stack is empty!");
  179. Stack.back().first.pop_back();
  180. }
  181. /// Start new OpenMP region stack in new non-capturing function.
  182. void pushFunction() {
  183. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  184. assert(!isa<CapturingScopeInfo>(CurFnScope));
  185. CurrentNonCapturingFunctionScope = CurFnScope;
  186. }
  187. /// Pop region stack for non-capturing function.
  188. void popFunction(const FunctionScopeInfo *OldFSI) {
  189. if (!Stack.empty() && Stack.back().second == OldFSI) {
  190. assert(Stack.back().first.empty());
  191. Stack.pop_back();
  192. }
  193. CurrentNonCapturingFunctionScope = nullptr;
  194. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  195. if (!isa<CapturingScopeInfo>(FSI)) {
  196. CurrentNonCapturingFunctionScope = FSI;
  197. break;
  198. }
  199. }
  200. }
  201. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  202. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  203. }
  204. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  205. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  206. auto I = Criticals.find(Name.getAsString());
  207. if (I != Criticals.end())
  208. return I->second;
  209. return std::make_pair(nullptr, llvm::APSInt());
  210. }
  211. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  212. /// add it and return NULL; otherwise return previous occurrence's expression
  213. /// for diagnostics.
  214. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  215. /// \brief Register specified variable as loop control variable.
  216. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
  217. /// \brief Check if the specified variable is a loop control variable for
  218. /// current region.
  219. /// \return The index of the loop control variable in the list of associated
  220. /// for-loops (from outer to inner).
  221. LCDeclInfo isLoopControlVariable(ValueDecl *D);
  222. /// \brief Check if the specified variable is a loop control variable for
  223. /// parent region.
  224. /// \return The index of the loop control variable in the list of associated
  225. /// for-loops (from outer to inner).
  226. LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
  227. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  228. /// parent directive.
  229. ValueDecl *getParentLoopControlVariable(unsigned I);
  230. /// \brief Adds explicit data sharing attribute to the specified declaration.
  231. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  232. DeclRefExpr *PrivateCopy = nullptr);
  233. /// Adds additional information for the reduction items with the reduction id
  234. /// represented as an operator.
  235. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  236. BinaryOperatorKind BOK);
  237. /// Adds additional information for the reduction items with the reduction id
  238. /// represented as reduction identifier.
  239. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  240. const Expr *ReductionRef);
  241. /// Returns the location and reduction operation from the innermost parent
  242. /// region for the given \p D.
  243. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  244. BinaryOperatorKind &BOK,
  245. Expr *&TaskgroupDescriptor);
  246. /// Returns the location and reduction operation from the innermost parent
  247. /// region for the given \p D.
  248. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  249. const Expr *&ReductionRef,
  250. Expr *&TaskgroupDescriptor);
  251. /// Return reduction reference expression for the current taskgroup.
  252. Expr *getTaskgroupReductionRef() const {
  253. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  254. "taskgroup reference expression requested for non taskgroup "
  255. "directive.");
  256. return Stack.back().first.back().TaskgroupReductionRef;
  257. }
  258. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  259. /// descriptor variable at the \p Level of OpenMP regions.
  260. bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
  261. return Stack.back().first[Level].TaskgroupReductionRef &&
  262. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  263. ->getDecl() == VD;
  264. }
  265. /// \brief Returns data sharing attributes from top of the stack for the
  266. /// specified declaration.
  267. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  268. /// \brief Returns data-sharing attributes for the specified declaration.
  269. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  270. /// \brief Checks if the specified variables has data-sharing attributes which
  271. /// match specified \a CPred predicate in any directive which matches \a DPred
  272. /// predicate.
  273. DSAVarData hasDSA(ValueDecl *D,
  274. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  275. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  276. bool FromParent);
  277. /// \brief Checks if the specified variables has data-sharing attributes which
  278. /// match specified \a CPred predicate in any innermost directive which
  279. /// matches \a DPred predicate.
  280. DSAVarData
  281. hasInnermostDSA(ValueDecl *D,
  282. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  283. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  284. bool FromParent);
  285. /// \brief Checks if the specified variables has explicit data-sharing
  286. /// attributes which match specified \a CPred predicate at the specified
  287. /// OpenMP region.
  288. bool hasExplicitDSA(ValueDecl *D,
  289. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  290. unsigned Level, bool NotLastprivate = false);
  291. /// \brief Returns true if the directive at level \Level matches in the
  292. /// specified \a DPred predicate.
  293. bool hasExplicitDirective(
  294. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  295. unsigned Level);
  296. /// \brief Finds a directive which matches specified \a DPred predicate.
  297. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
  298. const DeclarationNameInfo &,
  299. SourceLocation)> &DPred,
  300. bool FromParent);
  301. /// \brief Returns currently analyzed directive.
  302. OpenMPDirectiveKind getCurrentDirective() const {
  303. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  304. }
  305. /// \brief Returns directive kind at specified level.
  306. OpenMPDirectiveKind getDirective(unsigned Level) const {
  307. assert(!isStackEmpty() && "No directive at specified level.");
  308. return Stack.back().first[Level].Directive;
  309. }
  310. /// \brief Returns parent directive.
  311. OpenMPDirectiveKind getParentDirective() const {
  312. if (isStackEmpty() || Stack.back().first.size() == 1)
  313. return OMPD_unknown;
  314. return std::next(Stack.back().first.rbegin())->Directive;
  315. }
  316. /// \brief Set default data sharing attribute to none.
  317. void setDefaultDSANone(SourceLocation Loc) {
  318. assert(!isStackEmpty());
  319. Stack.back().first.back().DefaultAttr = DSA_none;
  320. Stack.back().first.back().DefaultAttrLoc = Loc;
  321. }
  322. /// \brief Set default data sharing attribute to shared.
  323. void setDefaultDSAShared(SourceLocation Loc) {
  324. assert(!isStackEmpty());
  325. Stack.back().first.back().DefaultAttr = DSA_shared;
  326. Stack.back().first.back().DefaultAttrLoc = Loc;
  327. }
  328. /// Set default data mapping attribute to 'tofrom:scalar'.
  329. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  330. assert(!isStackEmpty());
  331. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  332. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  333. }
  334. DefaultDataSharingAttributes getDefaultDSA() const {
  335. return isStackEmpty() ? DSA_unspecified
  336. : Stack.back().first.back().DefaultAttr;
  337. }
  338. SourceLocation getDefaultDSALocation() const {
  339. return isStackEmpty() ? SourceLocation()
  340. : Stack.back().first.back().DefaultAttrLoc;
  341. }
  342. DefaultMapAttributes getDefaultDMA() const {
  343. return isStackEmpty() ? DMA_unspecified
  344. : Stack.back().first.back().DefaultMapAttr;
  345. }
  346. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  347. return Stack.back().first[Level].DefaultMapAttr;
  348. }
  349. SourceLocation getDefaultDMALocation() const {
  350. return isStackEmpty() ? SourceLocation()
  351. : Stack.back().first.back().DefaultMapAttrLoc;
  352. }
  353. /// \brief Checks if the specified variable is a threadprivate.
  354. bool isThreadPrivate(VarDecl *D) {
  355. DSAVarData DVar = getTopDSA(D, false);
  356. return isOpenMPThreadPrivate(DVar.CKind);
  357. }
  358. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  359. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  360. assert(!isStackEmpty());
  361. Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
  362. Stack.back().first.back().OrderedRegion.setPointer(Param);
  363. }
  364. /// \brief Returns true, if parent region is ordered (has associated
  365. /// 'ordered' clause), false - otherwise.
  366. bool isParentOrderedRegion() const {
  367. if (isStackEmpty() || Stack.back().first.size() == 1)
  368. return false;
  369. return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
  370. }
  371. /// \brief Returns optional parameter for the ordered region.
  372. Expr *getParentOrderedRegionParam() const {
  373. if (isStackEmpty() || Stack.back().first.size() == 1)
  374. return nullptr;
  375. return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
  376. }
  377. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  378. void setNowaitRegion(bool IsNowait = true) {
  379. assert(!isStackEmpty());
  380. Stack.back().first.back().NowaitRegion = IsNowait;
  381. }
  382. /// \brief Returns true, if parent region is nowait (has associated
  383. /// 'nowait' clause), false - otherwise.
  384. bool isParentNowaitRegion() const {
  385. if (isStackEmpty() || Stack.back().first.size() == 1)
  386. return false;
  387. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  388. }
  389. /// \brief Marks parent region as cancel region.
  390. void setParentCancelRegion(bool Cancel = true) {
  391. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  392. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  393. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  394. }
  395. }
  396. /// \brief Return true if current region has inner cancel construct.
  397. bool isCancelRegion() const {
  398. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  399. }
  400. /// \brief Set collapse value for the region.
  401. void setAssociatedLoops(unsigned Val) {
  402. assert(!isStackEmpty());
  403. Stack.back().first.back().AssociatedLoops = Val;
  404. }
  405. /// \brief Return collapse value for region.
  406. unsigned getAssociatedLoops() const {
  407. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  408. }
  409. /// \brief Marks current target region as one with closely nested teams
  410. /// region.
  411. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  412. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  413. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  414. TeamsRegionLoc;
  415. }
  416. }
  417. /// \brief Returns true, if current region has closely nested teams region.
  418. bool hasInnerTeamsRegion() const {
  419. return getInnerTeamsRegionLoc().isValid();
  420. }
  421. /// \brief Returns location of the nested teams region (if any).
  422. SourceLocation getInnerTeamsRegionLoc() const {
  423. return isStackEmpty() ? SourceLocation()
  424. : Stack.back().first.back().InnerTeamsRegionLoc;
  425. }
  426. Scope *getCurScope() const {
  427. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  428. }
  429. Scope *getCurScope() {
  430. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  431. }
  432. SourceLocation getConstructLoc() {
  433. return isStackEmpty() ? SourceLocation()
  434. : Stack.back().first.back().ConstructLoc;
  435. }
  436. /// Do the check specified in \a Check to all component lists and return true
  437. /// if any issue is found.
  438. bool checkMappableExprComponentListsForDecl(
  439. ValueDecl *VD, bool CurrentRegionOnly,
  440. const llvm::function_ref<
  441. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  442. OpenMPClauseKind)> &Check) {
  443. if (isStackEmpty())
  444. return false;
  445. auto SI = Stack.back().first.rbegin();
  446. auto SE = Stack.back().first.rend();
  447. if (SI == SE)
  448. return false;
  449. if (CurrentRegionOnly) {
  450. SE = std::next(SI);
  451. } else {
  452. ++SI;
  453. }
  454. for (; SI != SE; ++SI) {
  455. auto MI = SI->MappedExprComponents.find(VD);
  456. if (MI != SI->MappedExprComponents.end())
  457. for (auto &L : MI->second.Components)
  458. if (Check(L, MI->second.Kind))
  459. return true;
  460. }
  461. return false;
  462. }
  463. /// Do the check specified in \a Check to all component lists at a given level
  464. /// and return true if any issue is found.
  465. bool checkMappableExprComponentListsForDeclAtLevel(
  466. ValueDecl *VD, unsigned Level,
  467. const llvm::function_ref<
  468. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  469. OpenMPClauseKind)> &Check) {
  470. if (isStackEmpty())
  471. return false;
  472. auto StartI = Stack.back().first.begin();
  473. auto EndI = Stack.back().first.end();
  474. if (std::distance(StartI, EndI) <= (int)Level)
  475. return false;
  476. std::advance(StartI, Level);
  477. auto MI = StartI->MappedExprComponents.find(VD);
  478. if (MI != StartI->MappedExprComponents.end())
  479. for (auto &L : MI->second.Components)
  480. if (Check(L, MI->second.Kind))
  481. return true;
  482. return false;
  483. }
  484. /// Create a new mappable expression component list associated with a given
  485. /// declaration and initialize it with the provided list of components.
  486. void addMappableExpressionComponents(
  487. ValueDecl *VD,
  488. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  489. OpenMPClauseKind WhereFoundClauseKind) {
  490. assert(!isStackEmpty() &&
  491. "Not expecting to retrieve components from a empty stack!");
  492. auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
  493. // Create new entry and append the new components there.
  494. MEC.Components.resize(MEC.Components.size() + 1);
  495. MEC.Components.back().append(Components.begin(), Components.end());
  496. MEC.Kind = WhereFoundClauseKind;
  497. }
  498. unsigned getNestingLevel() const {
  499. assert(!isStackEmpty());
  500. return Stack.back().first.size() - 1;
  501. }
  502. void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
  503. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  504. auto &StackElem = *std::next(Stack.back().first.rbegin());
  505. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  506. StackElem.DoacrossDepends.insert({C, OpsOffs});
  507. }
  508. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  509. getDoacrossDependClauses() const {
  510. assert(!isStackEmpty());
  511. auto &StackElem = Stack.back().first.back();
  512. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  513. auto &Ref = StackElem.DoacrossDepends;
  514. return llvm::make_range(Ref.begin(), Ref.end());
  515. }
  516. return llvm::make_range(StackElem.DoacrossDepends.end(),
  517. StackElem.DoacrossDepends.end());
  518. }
  519. };
  520. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  521. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  522. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  523. }
  524. } // namespace
  525. static Expr *getExprAsWritten(Expr *E) {
  526. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  527. E = ExprTemp->getSubExpr();
  528. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  529. E = MTE->GetTemporaryExpr();
  530. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  531. E = Binder->getSubExpr();
  532. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  533. E = ICE->getSubExprAsWritten();
  534. return E->IgnoreParens();
  535. }
  536. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  537. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  538. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  539. D = ME->getMemberDecl();
  540. auto *VD = dyn_cast<VarDecl>(D);
  541. auto *FD = dyn_cast<FieldDecl>(D);
  542. if (VD != nullptr) {
  543. VD = VD->getCanonicalDecl();
  544. D = VD;
  545. } else {
  546. assert(FD);
  547. FD = FD->getCanonicalDecl();
  548. D = FD;
  549. }
  550. return D;
  551. }
  552. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
  553. ValueDecl *D) {
  554. D = getCanonicalDecl(D);
  555. auto *VD = dyn_cast<VarDecl>(D);
  556. auto *FD = dyn_cast<FieldDecl>(D);
  557. DSAVarData DVar;
  558. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  559. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  560. // in a region but not in construct]
  561. // File-scope or namespace-scope variables referenced in called routines
  562. // in the region are shared unless they appear in a threadprivate
  563. // directive.
  564. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  565. DVar.CKind = OMPC_shared;
  566. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  567. // in a region but not in construct]
  568. // Variables with static storage duration that are declared in called
  569. // routines in the region are shared.
  570. if (VD && VD->hasGlobalStorage())
  571. DVar.CKind = OMPC_shared;
  572. // Non-static data members are shared by default.
  573. if (FD)
  574. DVar.CKind = OMPC_shared;
  575. return DVar;
  576. }
  577. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  578. // in a Construct, C/C++, predetermined, p.1]
  579. // Variables with automatic storage duration that are declared in a scope
  580. // inside the construct are private.
  581. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  582. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  583. DVar.CKind = OMPC_private;
  584. return DVar;
  585. }
  586. DVar.DKind = Iter->Directive;
  587. // Explicitly specified attributes and local variables with predetermined
  588. // attributes.
  589. if (Iter->SharingMap.count(D)) {
  590. DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
  591. DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
  592. DVar.CKind = Iter->SharingMap[D].Attributes;
  593. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  594. return DVar;
  595. }
  596. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  597. // in a Construct, C/C++, implicitly determined, p.1]
  598. // In a parallel or task construct, the data-sharing attributes of these
  599. // variables are determined by the default clause, if present.
  600. switch (Iter->DefaultAttr) {
  601. case DSA_shared:
  602. DVar.CKind = OMPC_shared;
  603. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  604. return DVar;
  605. case DSA_none:
  606. return DVar;
  607. case DSA_unspecified:
  608. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  609. // in a Construct, implicitly determined, p.2]
  610. // In a parallel construct, if no default clause is present, these
  611. // variables are shared.
  612. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  613. if (isOpenMPParallelDirective(DVar.DKind) ||
  614. isOpenMPTeamsDirective(DVar.DKind)) {
  615. DVar.CKind = OMPC_shared;
  616. return DVar;
  617. }
  618. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  619. // in a Construct, implicitly determined, p.4]
  620. // In a task construct, if no default clause is present, a variable that in
  621. // the enclosing context is determined to be shared by all implicit tasks
  622. // bound to the current team is shared.
  623. if (isOpenMPTaskingDirective(DVar.DKind)) {
  624. DSAVarData DVarTemp;
  625. auto I = Iter, E = Stack.back().first.rend();
  626. do {
  627. ++I;
  628. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  629. // Referenced in a Construct, implicitly determined, p.6]
  630. // In a task construct, if no default clause is present, a variable
  631. // whose data-sharing attribute is not determined by the rules above is
  632. // firstprivate.
  633. DVarTemp = getDSA(I, D);
  634. if (DVarTemp.CKind != OMPC_shared) {
  635. DVar.RefExpr = nullptr;
  636. DVar.CKind = OMPC_firstprivate;
  637. return DVar;
  638. }
  639. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  640. DVar.CKind =
  641. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  642. return DVar;
  643. }
  644. }
  645. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  646. // in a Construct, implicitly determined, p.3]
  647. // For constructs other than task, if no default clause is present, these
  648. // variables inherit their data-sharing attributes from the enclosing
  649. // context.
  650. return getDSA(++Iter, D);
  651. }
  652. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  653. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  654. D = getCanonicalDecl(D);
  655. auto &StackElem = Stack.back().first.back();
  656. auto It = StackElem.AlignedMap.find(D);
  657. if (It == StackElem.AlignedMap.end()) {
  658. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  659. StackElem.AlignedMap[D] = NewDE;
  660. return nullptr;
  661. } else {
  662. assert(It->second && "Unexpected nullptr expr in the aligned map");
  663. return It->second;
  664. }
  665. return nullptr;
  666. }
  667. void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
  668. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  669. D = getCanonicalDecl(D);
  670. auto &StackElem = Stack.back().first.back();
  671. StackElem.LCVMap.insert(
  672. {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
  673. }
  674. DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  675. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  676. D = getCanonicalDecl(D);
  677. auto &StackElem = Stack.back().first.back();
  678. auto It = StackElem.LCVMap.find(D);
  679. if (It != StackElem.LCVMap.end())
  680. return It->second;
  681. return {0, nullptr};
  682. }
  683. DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  684. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  685. "Data-sharing attributes stack is empty");
  686. D = getCanonicalDecl(D);
  687. auto &StackElem = *std::next(Stack.back().first.rbegin());
  688. auto It = StackElem.LCVMap.find(D);
  689. if (It != StackElem.LCVMap.end())
  690. return It->second;
  691. return {0, nullptr};
  692. }
  693. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  694. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  695. "Data-sharing attributes stack is empty");
  696. auto &StackElem = *std::next(Stack.back().first.rbegin());
  697. if (StackElem.LCVMap.size() < I)
  698. return nullptr;
  699. for (auto &Pair : StackElem.LCVMap)
  700. if (Pair.second.first == I)
  701. return Pair.first;
  702. return nullptr;
  703. }
  704. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  705. DeclRefExpr *PrivateCopy) {
  706. D = getCanonicalDecl(D);
  707. if (A == OMPC_threadprivate) {
  708. auto &Data = Threadprivates[D];
  709. Data.Attributes = A;
  710. Data.RefExpr.setPointer(E);
  711. Data.PrivateCopy = nullptr;
  712. } else {
  713. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  714. auto &Data = Stack.back().first.back().SharingMap[D];
  715. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  716. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  717. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  718. (isLoopControlVariable(D).first && A == OMPC_private));
  719. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  720. Data.RefExpr.setInt(/*IntVal=*/true);
  721. return;
  722. }
  723. const bool IsLastprivate =
  724. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  725. Data.Attributes = A;
  726. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  727. Data.PrivateCopy = PrivateCopy;
  728. if (PrivateCopy) {
  729. auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  730. Data.Attributes = A;
  731. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  732. Data.PrivateCopy = nullptr;
  733. }
  734. }
  735. }
  736. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  737. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  738. StringRef Name, const AttrVec *Attrs = nullptr) {
  739. DeclContext *DC = SemaRef.CurContext;
  740. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  741. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  742. VarDecl *Decl =
  743. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  744. if (Attrs) {
  745. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  746. I != E; ++I)
  747. Decl->addAttr(*I);
  748. }
  749. Decl->setImplicit();
  750. return Decl;
  751. }
  752. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  753. SourceLocation Loc,
  754. bool RefersToCapture = false) {
  755. D->setReferenced();
  756. D->markUsed(S.Context);
  757. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  758. SourceLocation(), D, RefersToCapture, Loc, Ty,
  759. VK_LValue);
  760. }
  761. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  762. BinaryOperatorKind BOK) {
  763. D = getCanonicalDecl(D);
  764. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  765. assert(
  766. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  767. "Additional reduction info may be specified only for reduction items.");
  768. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  769. assert(ReductionData.ReductionRange.isInvalid() &&
  770. Stack.back().first.back().Directive == OMPD_taskgroup &&
  771. "Additional reduction info may be specified only once for reduction "
  772. "items.");
  773. ReductionData.set(BOK, SR);
  774. Expr *&TaskgroupReductionRef =
  775. Stack.back().first.back().TaskgroupReductionRef;
  776. if (!TaskgroupReductionRef) {
  777. auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
  778. SemaRef.Context.VoidPtrTy, ".task_red.");
  779. TaskgroupReductionRef =
  780. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  781. }
  782. }
  783. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  784. const Expr *ReductionRef) {
  785. D = getCanonicalDecl(D);
  786. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  787. assert(
  788. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  789. "Additional reduction info may be specified only for reduction items.");
  790. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  791. assert(ReductionData.ReductionRange.isInvalid() &&
  792. Stack.back().first.back().Directive == OMPD_taskgroup &&
  793. "Additional reduction info may be specified only once for reduction "
  794. "items.");
  795. ReductionData.set(ReductionRef, SR);
  796. Expr *&TaskgroupReductionRef =
  797. Stack.back().first.back().TaskgroupReductionRef;
  798. if (!TaskgroupReductionRef) {
  799. auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
  800. ".task_red.");
  801. TaskgroupReductionRef =
  802. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  803. }
  804. }
  805. DSAStackTy::DSAVarData
  806. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  807. BinaryOperatorKind &BOK,
  808. Expr *&TaskgroupDescriptor) {
  809. D = getCanonicalDecl(D);
  810. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  811. if (Stack.back().first.empty())
  812. return DSAVarData();
  813. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  814. E = Stack.back().first.rend();
  815. I != E; std::advance(I, 1)) {
  816. auto &Data = I->SharingMap[D];
  817. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  818. continue;
  819. auto &ReductionData = I->ReductionMap[D];
  820. if (!ReductionData.ReductionOp ||
  821. ReductionData.ReductionOp.is<const Expr *>())
  822. return DSAVarData();
  823. SR = ReductionData.ReductionRange;
  824. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  825. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  826. "expression for the descriptor is not "
  827. "set.");
  828. TaskgroupDescriptor = I->TaskgroupReductionRef;
  829. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  830. Data.PrivateCopy, I->DefaultAttrLoc);
  831. }
  832. return DSAVarData();
  833. }
  834. DSAStackTy::DSAVarData
  835. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  836. const Expr *&ReductionRef,
  837. Expr *&TaskgroupDescriptor) {
  838. D = getCanonicalDecl(D);
  839. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  840. if (Stack.back().first.empty())
  841. return DSAVarData();
  842. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  843. E = Stack.back().first.rend();
  844. I != E; std::advance(I, 1)) {
  845. auto &Data = I->SharingMap[D];
  846. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  847. continue;
  848. auto &ReductionData = I->ReductionMap[D];
  849. if (!ReductionData.ReductionOp ||
  850. !ReductionData.ReductionOp.is<const Expr *>())
  851. return DSAVarData();
  852. SR = ReductionData.ReductionRange;
  853. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  854. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  855. "expression for the descriptor is not "
  856. "set.");
  857. TaskgroupDescriptor = I->TaskgroupReductionRef;
  858. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  859. Data.PrivateCopy, I->DefaultAttrLoc);
  860. }
  861. return DSAVarData();
  862. }
  863. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  864. D = D->getCanonicalDecl();
  865. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  866. reverse_iterator I = Iter, E = Stack.back().first.rend();
  867. Scope *TopScope = nullptr;
  868. while (I != E && !isParallelOrTaskRegion(I->Directive))
  869. ++I;
  870. if (I == E)
  871. return false;
  872. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  873. Scope *CurScope = getCurScope();
  874. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  875. CurScope = CurScope->getParent();
  876. return CurScope != TopScope;
  877. }
  878. return false;
  879. }
  880. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  881. D = getCanonicalDecl(D);
  882. DSAVarData DVar;
  883. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  884. // in a Construct, C/C++, predetermined, p.1]
  885. // Variables appearing in threadprivate directives are threadprivate.
  886. auto *VD = dyn_cast<VarDecl>(D);
  887. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  888. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  889. SemaRef.getLangOpts().OpenMPUseTLS &&
  890. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  891. (VD && VD->getStorageClass() == SC_Register &&
  892. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  893. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  894. D->getLocation()),
  895. OMPC_threadprivate);
  896. }
  897. auto TI = Threadprivates.find(D);
  898. if (TI != Threadprivates.end()) {
  899. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  900. DVar.CKind = OMPC_threadprivate;
  901. return DVar;
  902. } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  903. DVar.RefExpr = buildDeclRefExpr(
  904. SemaRef, VD, D->getType().getNonReferenceType(),
  905. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  906. DVar.CKind = OMPC_threadprivate;
  907. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  908. }
  909. if (isStackEmpty())
  910. // Not in OpenMP execution region and top scope was already checked.
  911. return DVar;
  912. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  913. // in a Construct, C/C++, predetermined, p.4]
  914. // Static data members are shared.
  915. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  916. // in a Construct, C/C++, predetermined, p.7]
  917. // Variables with static storage duration that are declared in a scope
  918. // inside the construct are shared.
  919. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  920. if (VD && VD->isStaticDataMember()) {
  921. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  922. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  923. return DVar;
  924. DVar.CKind = OMPC_shared;
  925. return DVar;
  926. }
  927. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  928. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  929. Type = SemaRef.getASTContext().getBaseElementType(Type);
  930. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  931. // in a Construct, C/C++, predetermined, p.6]
  932. // Variables with const qualified type having no mutable member are
  933. // shared.
  934. CXXRecordDecl *RD =
  935. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  936. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  937. if (auto *CTD = CTSD->getSpecializedTemplate())
  938. RD = CTD->getTemplatedDecl();
  939. if (IsConstant &&
  940. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  941. RD->hasMutableFields())) {
  942. // Variables with const-qualified type having no mutable member may be
  943. // listed in a firstprivate clause, even if they are static data members.
  944. DSAVarData DVarTemp = hasDSA(
  945. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  946. MatchesAlways, FromParent);
  947. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  948. return DVar;
  949. DVar.CKind = OMPC_shared;
  950. return DVar;
  951. }
  952. // Explicitly specified attributes and local variables with predetermined
  953. // attributes.
  954. auto I = Stack.back().first.rbegin();
  955. auto EndI = Stack.back().first.rend();
  956. if (FromParent && I != EndI)
  957. std::advance(I, 1);
  958. if (I->SharingMap.count(D)) {
  959. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  960. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  961. DVar.CKind = I->SharingMap[D].Attributes;
  962. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  963. DVar.DKind = I->Directive;
  964. }
  965. return DVar;
  966. }
  967. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  968. bool FromParent) {
  969. if (isStackEmpty()) {
  970. StackTy::reverse_iterator I;
  971. return getDSA(I, D);
  972. }
  973. D = getCanonicalDecl(D);
  974. auto StartI = Stack.back().first.rbegin();
  975. auto EndI = Stack.back().first.rend();
  976. if (FromParent && StartI != EndI)
  977. std::advance(StartI, 1);
  978. return getDSA(StartI, D);
  979. }
  980. DSAStackTy::DSAVarData
  981. DSAStackTy::hasDSA(ValueDecl *D,
  982. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  983. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  984. bool FromParent) {
  985. if (isStackEmpty())
  986. return {};
  987. D = getCanonicalDecl(D);
  988. auto I = Stack.back().first.rbegin();
  989. auto EndI = Stack.back().first.rend();
  990. if (FromParent && I != EndI)
  991. std::advance(I, 1);
  992. for (; I != EndI; std::advance(I, 1)) {
  993. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  994. continue;
  995. auto NewI = I;
  996. DSAVarData DVar = getDSA(NewI, D);
  997. if (I == NewI && CPred(DVar.CKind))
  998. return DVar;
  999. }
  1000. return {};
  1001. }
  1002. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1003. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1004. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1005. bool FromParent) {
  1006. if (isStackEmpty())
  1007. return {};
  1008. D = getCanonicalDecl(D);
  1009. auto StartI = Stack.back().first.rbegin();
  1010. auto EndI = Stack.back().first.rend();
  1011. if (FromParent && StartI != EndI)
  1012. std::advance(StartI, 1);
  1013. if (StartI == EndI || !DPred(StartI->Directive))
  1014. return {};
  1015. auto NewI = StartI;
  1016. DSAVarData DVar = getDSA(NewI, D);
  1017. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1018. }
  1019. bool DSAStackTy::hasExplicitDSA(
  1020. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1021. unsigned Level, bool NotLastprivate) {
  1022. if (CPred(ClauseKindMode))
  1023. return true;
  1024. if (isStackEmpty())
  1025. return false;
  1026. D = getCanonicalDecl(D);
  1027. auto StartI = Stack.back().first.begin();
  1028. auto EndI = Stack.back().first.end();
  1029. if (std::distance(StartI, EndI) <= (int)Level)
  1030. return false;
  1031. std::advance(StartI, Level);
  1032. return (StartI->SharingMap.count(D) > 0) &&
  1033. StartI->SharingMap[D].RefExpr.getPointer() &&
  1034. CPred(StartI->SharingMap[D].Attributes) &&
  1035. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  1036. }
  1037. bool DSAStackTy::hasExplicitDirective(
  1038. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1039. unsigned Level) {
  1040. if (isStackEmpty())
  1041. return false;
  1042. auto StartI = Stack.back().first.begin();
  1043. auto EndI = Stack.back().first.end();
  1044. if (std::distance(StartI, EndI) <= (int)Level)
  1045. return false;
  1046. std::advance(StartI, Level);
  1047. return DPred(StartI->Directive);
  1048. }
  1049. bool DSAStackTy::hasDirective(
  1050. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1051. const DeclarationNameInfo &, SourceLocation)>
  1052. &DPred,
  1053. bool FromParent) {
  1054. // We look only in the enclosing region.
  1055. if (isStackEmpty())
  1056. return false;
  1057. auto StartI = std::next(Stack.back().first.rbegin());
  1058. auto EndI = Stack.back().first.rend();
  1059. if (FromParent && StartI != EndI)
  1060. StartI = std::next(StartI);
  1061. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1062. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1063. return true;
  1064. }
  1065. return false;
  1066. }
  1067. void Sema::InitDataSharingAttributesStack() {
  1068. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1069. }
  1070. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1071. void Sema::pushOpenMPFunctionRegion() {
  1072. DSAStack->pushFunction();
  1073. }
  1074. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1075. DSAStack->popFunction(OldFSI);
  1076. }
  1077. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  1078. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1079. auto &Ctx = getASTContext();
  1080. bool IsByRef = true;
  1081. // Find the directive that is associated with the provided scope.
  1082. D = cast<ValueDecl>(D->getCanonicalDecl());
  1083. auto Ty = D->getType();
  1084. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1085. // This table summarizes how a given variable should be passed to the device
  1086. // given its type and the clauses where it appears. This table is based on
  1087. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1088. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1089. //
  1090. // =========================================================================
  1091. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1092. // | |(tofrom:scalar)| | pvt | | | |
  1093. // =========================================================================
  1094. // | scl | | | | - | | bycopy|
  1095. // | scl | | - | x | - | - | bycopy|
  1096. // | scl | | x | - | - | - | null |
  1097. // | scl | x | | | - | | byref |
  1098. // | scl | x | - | x | - | - | bycopy|
  1099. // | scl | x | x | - | - | - | null |
  1100. // | scl | | - | - | - | x | byref |
  1101. // | scl | x | - | - | - | x | byref |
  1102. //
  1103. // | agg | n.a. | | | - | | byref |
  1104. // | agg | n.a. | - | x | - | - | byref |
  1105. // | agg | n.a. | x | - | - | - | null |
  1106. // | agg | n.a. | - | - | - | x | byref |
  1107. // | agg | n.a. | - | - | - | x[] | byref |
  1108. //
  1109. // | ptr | n.a. | | | - | | bycopy|
  1110. // | ptr | n.a. | - | x | - | - | bycopy|
  1111. // | ptr | n.a. | x | - | - | - | null |
  1112. // | ptr | n.a. | - | - | - | x | byref |
  1113. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1114. // | ptr | n.a. | - | - | x | | bycopy|
  1115. // | ptr | n.a. | - | - | x | x | bycopy|
  1116. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1117. // =========================================================================
  1118. // Legend:
  1119. // scl - scalar
  1120. // ptr - pointer
  1121. // agg - aggregate
  1122. // x - applies
  1123. // - - invalid in this combination
  1124. // [] - mapped with an array section
  1125. // byref - should be mapped by reference
  1126. // byval - should be mapped by value
  1127. // null - initialize a local variable to null on the device
  1128. //
  1129. // Observations:
  1130. // - All scalar declarations that show up in a map clause have to be passed
  1131. // by reference, because they may have been mapped in the enclosing data
  1132. // environment.
  1133. // - If the scalar value does not fit the size of uintptr, it has to be
  1134. // passed by reference, regardless the result in the table above.
  1135. // - For pointers mapped by value that have either an implicit map or an
  1136. // array section, the runtime library may pass the NULL value to the
  1137. // device instead of the value passed to it by the compiler.
  1138. if (Ty->isReferenceType())
  1139. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1140. // Locate map clauses and see if the variable being captured is referred to
  1141. // in any of those clauses. Here we only care about variables, not fields,
  1142. // because fields are part of aggregates.
  1143. bool IsVariableUsedInMapClause = false;
  1144. bool IsVariableAssociatedWithSection = false;
  1145. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1146. D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1147. MapExprComponents,
  1148. OpenMPClauseKind WhereFoundClauseKind) {
  1149. // Only the map clause information influences how a variable is
  1150. // captured. E.g. is_device_ptr does not require changing the default
  1151. // behavior.
  1152. if (WhereFoundClauseKind != OMPC_map)
  1153. return false;
  1154. auto EI = MapExprComponents.rbegin();
  1155. auto EE = MapExprComponents.rend();
  1156. assert(EI != EE && "Invalid map expression!");
  1157. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1158. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1159. ++EI;
  1160. if (EI == EE)
  1161. return false;
  1162. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1163. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1164. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1165. IsVariableAssociatedWithSection = true;
  1166. // There is nothing more we need to know about this variable.
  1167. return true;
  1168. }
  1169. // Keep looking for more map info.
  1170. return false;
  1171. });
  1172. if (IsVariableUsedInMapClause) {
  1173. // If variable is identified in a map clause it is always captured by
  1174. // reference except if it is a pointer that is dereferenced somehow.
  1175. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1176. } else {
  1177. // By default, all the data that has a scalar type is mapped by copy.
  1178. IsByRef = !Ty->isScalarType() ||
  1179. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
  1180. }
  1181. }
  1182. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1183. IsByRef = !DSAStack->hasExplicitDSA(
  1184. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1185. Level, /*NotLastprivate=*/true);
  1186. }
  1187. // When passing data by copy, we need to make sure it fits the uintptr size
  1188. // and alignment, because the runtime library only deals with uintptr types.
  1189. // If it does not fit the uintptr size, we need to pass the data by reference
  1190. // instead.
  1191. if (!IsByRef &&
  1192. (Ctx.getTypeSizeInChars(Ty) >
  1193. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1194. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1195. IsByRef = true;
  1196. }
  1197. return IsByRef;
  1198. }
  1199. unsigned Sema::getOpenMPNestingLevel() const {
  1200. assert(getLangOpts().OpenMP);
  1201. return DSAStack->getNestingLevel();
  1202. }
  1203. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1204. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1205. !DSAStack->isClauseParsingMode()) ||
  1206. DSAStack->hasDirective(
  1207. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1208. SourceLocation) -> bool {
  1209. return isOpenMPTargetExecutionDirective(K);
  1210. },
  1211. false);
  1212. }
  1213. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  1214. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1215. D = getCanonicalDecl(D);
  1216. // If we are attempting to capture a global variable in a directive with
  1217. // 'target' we return true so that this global is also mapped to the device.
  1218. //
  1219. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  1220. // then it should not be captured. Therefore, an extra check has to be
  1221. // inserted here once support for 'declare target' is added.
  1222. //
  1223. auto *VD = dyn_cast<VarDecl>(D);
  1224. if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
  1225. return VD;
  1226. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1227. (!DSAStack->isClauseParsingMode() ||
  1228. DSAStack->getParentDirective() != OMPD_unknown)) {
  1229. auto &&Info = DSAStack->isLoopControlVariable(D);
  1230. if (Info.first ||
  1231. (VD && VD->hasLocalStorage() &&
  1232. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1233. (VD && DSAStack->isForceVarCapturing()))
  1234. return VD ? VD : Info.second;
  1235. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1236. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1237. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1238. DVarPrivate = DSAStack->hasDSA(
  1239. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  1240. DSAStack->isClauseParsingMode());
  1241. if (DVarPrivate.CKind != OMPC_unknown)
  1242. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1243. }
  1244. return nullptr;
  1245. }
  1246. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1247. unsigned Level) const {
  1248. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1249. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1250. FunctionScopesIndex -= Regions.size();
  1251. }
  1252. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  1253. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1254. return DSAStack->hasExplicitDSA(
  1255. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
  1256. Level) ||
  1257. // Consider taskgroup reduction descriptor variable a private to avoid
  1258. // possible capture in the region.
  1259. (DSAStack->hasExplicitDirective(
  1260. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1261. Level) &&
  1262. DSAStack->isTaskgroupReductionRef(D, Level));
  1263. }
  1264. void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
  1265. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1266. D = getCanonicalDecl(D);
  1267. OpenMPClauseKind OMPC = OMPC_unknown;
  1268. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1269. const unsigned NewLevel = I - 1;
  1270. if (DSAStack->hasExplicitDSA(D,
  1271. [&OMPC](const OpenMPClauseKind K) {
  1272. if (isOpenMPPrivate(K)) {
  1273. OMPC = K;
  1274. return true;
  1275. }
  1276. return false;
  1277. },
  1278. NewLevel))
  1279. break;
  1280. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1281. D, NewLevel,
  1282. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1283. OpenMPClauseKind) { return true; })) {
  1284. OMPC = OMPC_map;
  1285. break;
  1286. }
  1287. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1288. NewLevel)) {
  1289. OMPC = OMPC_firstprivate;
  1290. break;
  1291. }
  1292. }
  1293. if (OMPC != OMPC_unknown)
  1294. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1295. }
  1296. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  1297. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1298. // Return true if the current level is no longer enclosed in a target region.
  1299. auto *VD = dyn_cast<VarDecl>(D);
  1300. return VD && !VD->hasLocalStorage() &&
  1301. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1302. Level);
  1303. }
  1304. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1305. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1306. const DeclarationNameInfo &DirName,
  1307. Scope *CurScope, SourceLocation Loc) {
  1308. DSAStack->push(DKind, DirName, CurScope, Loc);
  1309. PushExpressionEvaluationContext(
  1310. ExpressionEvaluationContext::PotentiallyEvaluated);
  1311. }
  1312. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1313. DSAStack->setClauseParsingMode(K);
  1314. }
  1315. void Sema::EndOpenMPClause() {
  1316. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1317. }
  1318. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1319. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1320. // A variable of class type (or array thereof) that appears in a lastprivate
  1321. // clause requires an accessible, unambiguous default constructor for the
  1322. // class type, unless the list item is also specified in a firstprivate
  1323. // clause.
  1324. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1325. for (auto *C : D->clauses()) {
  1326. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1327. SmallVector<Expr *, 8> PrivateCopies;
  1328. for (auto *DE : Clause->varlists()) {
  1329. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1330. PrivateCopies.push_back(nullptr);
  1331. continue;
  1332. }
  1333. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1334. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  1335. QualType Type = VD->getType().getNonReferenceType();
  1336. auto DVar = DSAStack->getTopDSA(VD, false);
  1337. if (DVar.CKind == OMPC_lastprivate) {
  1338. // Generate helper private variable and initialize it with the
  1339. // default value. The address of the original variable is replaced
  1340. // by the address of the new private variable in CodeGen. This new
  1341. // variable is not added to IdResolver, so the code in the OpenMP
  1342. // region uses original variable for proper diagnostics.
  1343. auto *VDPrivate = buildVarDecl(
  1344. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1345. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  1346. ActOnUninitializedDecl(VDPrivate);
  1347. if (VDPrivate->isInvalidDecl())
  1348. continue;
  1349. PrivateCopies.push_back(buildDeclRefExpr(
  1350. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1351. } else {
  1352. // The variable is also a firstprivate, so initialization sequence
  1353. // for private copy is generated already.
  1354. PrivateCopies.push_back(nullptr);
  1355. }
  1356. }
  1357. // Set initializers to private copies if no errors were found.
  1358. if (PrivateCopies.size() == Clause->varlist_size())
  1359. Clause->setPrivateCopies(PrivateCopies);
  1360. }
  1361. }
  1362. }
  1363. DSAStack->pop();
  1364. DiscardCleanupsInEvaluationContext();
  1365. PopExpressionEvaluationContext();
  1366. }
  1367. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1368. Expr *NumIterations, Sema &SemaRef,
  1369. Scope *S, DSAStackTy *Stack);
  1370. namespace {
  1371. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1372. private:
  1373. Sema &SemaRef;
  1374. public:
  1375. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1376. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1377. NamedDecl *ND = Candidate.getCorrectionDecl();
  1378. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1379. return VD->hasGlobalStorage() &&
  1380. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1381. SemaRef.getCurScope());
  1382. }
  1383. return false;
  1384. }
  1385. };
  1386. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1387. private:
  1388. Sema &SemaRef;
  1389. public:
  1390. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1391. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1392. NamedDecl *ND = Candidate.getCorrectionDecl();
  1393. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1394. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1395. SemaRef.getCurScope());
  1396. }
  1397. return false;
  1398. }
  1399. };
  1400. } // namespace
  1401. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1402. CXXScopeSpec &ScopeSpec,
  1403. const DeclarationNameInfo &Id) {
  1404. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1405. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1406. if (Lookup.isAmbiguous())
  1407. return ExprError();
  1408. VarDecl *VD;
  1409. if (!Lookup.isSingleResult()) {
  1410. if (TypoCorrection Corrected = CorrectTypo(
  1411. Id, LookupOrdinaryName, CurScope, nullptr,
  1412. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1413. diagnoseTypo(Corrected,
  1414. PDiag(Lookup.empty()
  1415. ? diag::err_undeclared_var_use_suggest
  1416. : diag::err_omp_expected_var_arg_suggest)
  1417. << Id.getName());
  1418. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1419. } else {
  1420. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1421. : diag::err_omp_expected_var_arg)
  1422. << Id.getName();
  1423. return ExprError();
  1424. }
  1425. } else {
  1426. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1427. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1428. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1429. return ExprError();
  1430. }
  1431. }
  1432. Lookup.suppressDiagnostics();
  1433. // OpenMP [2.9.2, Syntax, C/C++]
  1434. // Variables must be file-scope, namespace-scope, or static block-scope.
  1435. if (!VD->hasGlobalStorage()) {
  1436. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1437. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1438. bool IsDecl =
  1439. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1440. Diag(VD->getLocation(),
  1441. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1442. << VD;
  1443. return ExprError();
  1444. }
  1445. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1446. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1447. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1448. // A threadprivate directive for file-scope variables must appear outside
  1449. // any definition or declaration.
  1450. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1451. !getCurLexicalContext()->isTranslationUnit()) {
  1452. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1453. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1454. bool IsDecl =
  1455. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1456. Diag(VD->getLocation(),
  1457. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1458. << VD;
  1459. return ExprError();
  1460. }
  1461. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1462. // A threadprivate directive for static class member variables must appear
  1463. // in the class definition, in the same scope in which the member
  1464. // variables are declared.
  1465. if (CanonicalVD->isStaticDataMember() &&
  1466. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1467. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1468. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1469. bool IsDecl =
  1470. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1471. Diag(VD->getLocation(),
  1472. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1473. << VD;
  1474. return ExprError();
  1475. }
  1476. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1477. // A threadprivate directive for namespace-scope variables must appear
  1478. // outside any definition or declaration other than the namespace
  1479. // definition itself.
  1480. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1481. (!getCurLexicalContext()->isFileContext() ||
  1482. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1483. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1484. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1485. bool IsDecl =
  1486. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1487. Diag(VD->getLocation(),
  1488. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1489. << VD;
  1490. return ExprError();
  1491. }
  1492. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1493. // A threadprivate directive for static block-scope variables must appear
  1494. // in the scope of the variable and not in a nested scope.
  1495. if (CanonicalVD->isStaticLocal() && CurScope &&
  1496. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1497. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1498. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1499. bool IsDecl =
  1500. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1501. Diag(VD->getLocation(),
  1502. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1503. << VD;
  1504. return ExprError();
  1505. }
  1506. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1507. // A threadprivate directive must lexically precede all references to any
  1508. // of the variables in its list.
  1509. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1510. Diag(Id.getLoc(), diag::err_omp_var_used)
  1511. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1512. return ExprError();
  1513. }
  1514. QualType ExprType = VD->getType().getNonReferenceType();
  1515. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1516. SourceLocation(), VD,
  1517. /*RefersToEnclosingVariableOrCapture=*/false,
  1518. Id.getLoc(), ExprType, VK_LValue);
  1519. }
  1520. Sema::DeclGroupPtrTy
  1521. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1522. ArrayRef<Expr *> VarList) {
  1523. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1524. CurContext->addDecl(D);
  1525. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1526. }
  1527. return nullptr;
  1528. }
  1529. namespace {
  1530. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1531. Sema &SemaRef;
  1532. public:
  1533. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1534. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1535. if (VD->hasLocalStorage()) {
  1536. SemaRef.Diag(E->getLocStart(),
  1537. diag::err_omp_local_var_in_threadprivate_init)
  1538. << E->getSourceRange();
  1539. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1540. << VD << VD->getSourceRange();
  1541. return true;
  1542. }
  1543. }
  1544. return false;
  1545. }
  1546. bool VisitStmt(const Stmt *S) {
  1547. for (auto Child : S->children()) {
  1548. if (Child && Visit(Child))
  1549. return true;
  1550. }
  1551. return false;
  1552. }
  1553. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1554. };
  1555. } // namespace
  1556. OMPThreadPrivateDecl *
  1557. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1558. SmallVector<Expr *, 8> Vars;
  1559. for (auto &RefExpr : VarList) {
  1560. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1561. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1562. SourceLocation ILoc = DE->getExprLoc();
  1563. // Mark variable as used.
  1564. VD->setReferenced();
  1565. VD->markUsed(Context);
  1566. QualType QType = VD->getType();
  1567. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1568. // It will be analyzed later.
  1569. Vars.push_back(DE);
  1570. continue;
  1571. }
  1572. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1573. // A threadprivate variable must not have an incomplete type.
  1574. if (RequireCompleteType(ILoc, VD->getType(),
  1575. diag::err_omp_threadprivate_incomplete_type)) {
  1576. continue;
  1577. }
  1578. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1579. // A threadprivate variable must not have a reference type.
  1580. if (VD->getType()->isReferenceType()) {
  1581. Diag(ILoc, diag::err_omp_ref_type_arg)
  1582. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1583. bool IsDecl =
  1584. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1585. Diag(VD->getLocation(),
  1586. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1587. << VD;
  1588. continue;
  1589. }
  1590. // Check if this is a TLS variable. If TLS is not being supported, produce
  1591. // the corresponding diagnostic.
  1592. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1593. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1594. getLangOpts().OpenMPUseTLS &&
  1595. getASTContext().getTargetInfo().isTLSSupported())) ||
  1596. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1597. !VD->isLocalVarDecl())) {
  1598. Diag(ILoc, diag::err_omp_var_thread_local)
  1599. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1600. bool IsDecl =
  1601. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1602. Diag(VD->getLocation(),
  1603. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1604. << VD;
  1605. continue;
  1606. }
  1607. // Check if initial value of threadprivate variable reference variable with
  1608. // local storage (it is not supported by runtime).
  1609. if (auto Init = VD->getAnyInitializer()) {
  1610. LocalVarRefChecker Checker(*this);
  1611. if (Checker.Visit(Init))
  1612. continue;
  1613. }
  1614. Vars.push_back(RefExpr);
  1615. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1616. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1617. Context, SourceRange(Loc, Loc)));
  1618. if (auto *ML = Context.getASTMutationListener())
  1619. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1620. }
  1621. OMPThreadPrivateDecl *D = nullptr;
  1622. if (!Vars.empty()) {
  1623. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1624. Vars);
  1625. D->setAccess(AS_public);
  1626. }
  1627. return D;
  1628. }
  1629. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1630. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1631. bool IsLoopIterVar = false) {
  1632. if (DVar.RefExpr) {
  1633. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1634. << getOpenMPClauseName(DVar.CKind);
  1635. return;
  1636. }
  1637. enum {
  1638. PDSA_StaticMemberShared,
  1639. PDSA_StaticLocalVarShared,
  1640. PDSA_LoopIterVarPrivate,
  1641. PDSA_LoopIterVarLinear,
  1642. PDSA_LoopIterVarLastprivate,
  1643. PDSA_ConstVarShared,
  1644. PDSA_GlobalVarShared,
  1645. PDSA_TaskVarFirstprivate,
  1646. PDSA_LocalVarPrivate,
  1647. PDSA_Implicit
  1648. } Reason = PDSA_Implicit;
  1649. bool ReportHint = false;
  1650. auto ReportLoc = D->getLocation();
  1651. auto *VD = dyn_cast<VarDecl>(D);
  1652. if (IsLoopIterVar) {
  1653. if (DVar.CKind == OMPC_private)
  1654. Reason = PDSA_LoopIterVarPrivate;
  1655. else if (DVar.CKind == OMPC_lastprivate)
  1656. Reason = PDSA_LoopIterVarLastprivate;
  1657. else
  1658. Reason = PDSA_LoopIterVarLinear;
  1659. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1660. DVar.CKind == OMPC_firstprivate) {
  1661. Reason = PDSA_TaskVarFirstprivate;
  1662. ReportLoc = DVar.ImplicitDSALoc;
  1663. } else if (VD && VD->isStaticLocal())
  1664. Reason = PDSA_StaticLocalVarShared;
  1665. else if (VD && VD->isStaticDataMember())
  1666. Reason = PDSA_StaticMemberShared;
  1667. else if (VD && VD->isFileVarDecl())
  1668. Reason = PDSA_GlobalVarShared;
  1669. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1670. Reason = PDSA_ConstVarShared;
  1671. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1672. ReportHint = true;
  1673. Reason = PDSA_LocalVarPrivate;
  1674. }
  1675. if (Reason != PDSA_Implicit) {
  1676. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1677. << Reason << ReportHint
  1678. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1679. } else if (DVar.ImplicitDSALoc.isValid()) {
  1680. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1681. << getOpenMPClauseName(DVar.CKind);
  1682. }
  1683. }
  1684. namespace {
  1685. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1686. DSAStackTy *Stack;
  1687. Sema &SemaRef;
  1688. bool ErrorFound;
  1689. CapturedStmt *CS;
  1690. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1691. llvm::SmallVector<Expr *, 8> ImplicitMap;
  1692. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1693. llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
  1694. public:
  1695. void VisitDeclRefExpr(DeclRefExpr *E) {
  1696. if (E->isTypeDependent() || E->isValueDependent() ||
  1697. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1698. return;
  1699. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1700. VD = VD->getCanonicalDecl();
  1701. // Skip internally declared variables.
  1702. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1703. return;
  1704. auto DVar = Stack->getTopDSA(VD, false);
  1705. // Check if the variable has explicit DSA set and stop analysis if it so.
  1706. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1707. return;
  1708. // Skip internally declared static variables.
  1709. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
  1710. return;
  1711. auto ELoc = E->getExprLoc();
  1712. auto DKind = Stack->getCurrentDirective();
  1713. // The default(none) clause requires that each variable that is referenced
  1714. // in the construct, and does not have a predetermined data-sharing
  1715. // attribute, must have its data-sharing attribute explicitly determined
  1716. // by being listed in a data-sharing attribute clause.
  1717. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1718. isParallelOrTaskRegion(DKind) &&
  1719. VarsWithInheritedDSA.count(VD) == 0) {
  1720. VarsWithInheritedDSA[VD] = E;
  1721. return;
  1722. }
  1723. if (isOpenMPTargetExecutionDirective(DKind) &&
  1724. !Stack->isLoopControlVariable(VD).first) {
  1725. if (!Stack->checkMappableExprComponentListsForDecl(
  1726. VD, /*CurrentRegionOnly=*/true,
  1727. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1728. StackComponents,
  1729. OpenMPClauseKind) {
  1730. // Variable is used if it has been marked as an array, array
  1731. // section or the variable iself.
  1732. return StackComponents.size() == 1 ||
  1733. std::all_of(
  1734. std::next(StackComponents.rbegin()),
  1735. StackComponents.rend(),
  1736. [](const OMPClauseMappableExprCommon::
  1737. MappableComponent &MC) {
  1738. return MC.getAssociatedDeclaration() ==
  1739. nullptr &&
  1740. (isa<OMPArraySectionExpr>(
  1741. MC.getAssociatedExpression()) ||
  1742. isa<ArraySubscriptExpr>(
  1743. MC.getAssociatedExpression()));
  1744. });
  1745. })) {
  1746. bool IsFirstprivate = false;
  1747. // By default lambdas are captured as firstprivates.
  1748. if (const auto *RD =
  1749. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1750. IsFirstprivate = RD->isLambda();
  1751. IsFirstprivate =
  1752. IsFirstprivate ||
  1753. (VD->getType().getNonReferenceType()->isScalarType() &&
  1754. Stack->getDefaultDMA() != DMA_tofrom_scalar);
  1755. if (IsFirstprivate)
  1756. ImplicitFirstprivate.emplace_back(E);
  1757. else
  1758. ImplicitMap.emplace_back(E);
  1759. return;
  1760. }
  1761. }
  1762. // OpenMP [2.9.3.6, Restrictions, p.2]
  1763. // A list item that appears in a reduction clause of the innermost
  1764. // enclosing worksharing or parallel construct may not be accessed in an
  1765. // explicit task.
  1766. DVar = Stack->hasInnermostDSA(
  1767. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1768. [](OpenMPDirectiveKind K) -> bool {
  1769. return isOpenMPParallelDirective(K) ||
  1770. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1771. },
  1772. /*FromParent=*/true);
  1773. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1774. ErrorFound = true;
  1775. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1776. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1777. return;
  1778. }
  1779. // Define implicit data-sharing attributes for task.
  1780. DVar = Stack->getImplicitDSA(VD, false);
  1781. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1782. !Stack->isLoopControlVariable(VD).first)
  1783. ImplicitFirstprivate.push_back(E);
  1784. }
  1785. }
  1786. void VisitMemberExpr(MemberExpr *E) {
  1787. if (E->isTypeDependent() || E->isValueDependent() ||
  1788. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1789. return;
  1790. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1791. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1792. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1793. if (!FD)
  1794. return;
  1795. auto DVar = Stack->getTopDSA(FD, false);
  1796. // Check if the variable has explicit DSA set and stop analysis if it
  1797. // so.
  1798. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1799. return;
  1800. if (isOpenMPTargetExecutionDirective(DKind) &&
  1801. !Stack->isLoopControlVariable(FD).first &&
  1802. !Stack->checkMappableExprComponentListsForDecl(
  1803. FD, /*CurrentRegionOnly=*/true,
  1804. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1805. StackComponents,
  1806. OpenMPClauseKind) {
  1807. return isa<CXXThisExpr>(
  1808. cast<MemberExpr>(
  1809. StackComponents.back().getAssociatedExpression())
  1810. ->getBase()
  1811. ->IgnoreParens());
  1812. })) {
  1813. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1814. // A bit-field cannot appear in a map clause.
  1815. //
  1816. if (FD->isBitField())
  1817. return;
  1818. ImplicitMap.emplace_back(E);
  1819. return;
  1820. }
  1821. auto ELoc = E->getExprLoc();
  1822. // OpenMP [2.9.3.6, Restrictions, p.2]
  1823. // A list item that appears in a reduction clause of the innermost
  1824. // enclosing worksharing or parallel construct may not be accessed in
  1825. // an explicit task.
  1826. DVar = Stack->hasInnermostDSA(
  1827. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1828. [](OpenMPDirectiveKind K) -> bool {
  1829. return isOpenMPParallelDirective(K) ||
  1830. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1831. },
  1832. /*FromParent=*/true);
  1833. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1834. ErrorFound = true;
  1835. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1836. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1837. return;
  1838. }
  1839. // Define implicit data-sharing attributes for task.
  1840. DVar = Stack->getImplicitDSA(FD, false);
  1841. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1842. !Stack->isLoopControlVariable(FD).first)
  1843. ImplicitFirstprivate.push_back(E);
  1844. return;
  1845. }
  1846. if (isOpenMPTargetExecutionDirective(DKind)) {
  1847. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1848. if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  1849. /*NoDiagnose=*/true))
  1850. return;
  1851. auto *VD = cast<ValueDecl>(
  1852. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1853. if (!Stack->checkMappableExprComponentListsForDecl(
  1854. VD, /*CurrentRegionOnly=*/true,
  1855. [&CurComponents](
  1856. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1857. StackComponents,
  1858. OpenMPClauseKind) {
  1859. auto CCI = CurComponents.rbegin();
  1860. auto CCE = CurComponents.rend();
  1861. for (const auto &SC : llvm::reverse(StackComponents)) {
  1862. // Do both expressions have the same kind?
  1863. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1864. SC.getAssociatedExpression()->getStmtClass())
  1865. if (!(isa<OMPArraySectionExpr>(
  1866. SC.getAssociatedExpression()) &&
  1867. isa<ArraySubscriptExpr>(
  1868. CCI->getAssociatedExpression())))
  1869. return false;
  1870. Decl *CCD = CCI->getAssociatedDeclaration();
  1871. Decl *SCD = SC.getAssociatedDeclaration();
  1872. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1873. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1874. if (SCD != CCD)
  1875. return false;
  1876. std::advance(CCI, 1);
  1877. if (CCI == CCE)
  1878. break;
  1879. }
  1880. return true;
  1881. })) {
  1882. Visit(E->getBase());
  1883. }
  1884. } else
  1885. Visit(E->getBase());
  1886. }
  1887. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1888. for (auto *C : S->clauses()) {
  1889. // Skip analysis of arguments of implicitly defined firstprivate clause
  1890. // for task|target directives.
  1891. // Skip analysis of arguments of implicitly defined map clause for target
  1892. // directives.
  1893. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  1894. C->isImplicit())) {
  1895. for (auto *CC : C->children()) {
  1896. if (CC)
  1897. Visit(CC);
  1898. }
  1899. }
  1900. }
  1901. }
  1902. void VisitStmt(Stmt *S) {
  1903. for (auto *C : S->children()) {
  1904. if (C && !isa<OMPExecutableDirective>(C))
  1905. Visit(C);
  1906. }
  1907. }
  1908. bool isErrorFound() { return ErrorFound; }
  1909. ArrayRef<Expr *> getImplicitFirstprivate() const {
  1910. return ImplicitFirstprivate;
  1911. }
  1912. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  1913. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1914. return VarsWithInheritedDSA;
  1915. }
  1916. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1917. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1918. };
  1919. } // namespace
  1920. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1921. switch (DKind) {
  1922. case OMPD_parallel:
  1923. case OMPD_parallel_for:
  1924. case OMPD_parallel_for_simd:
  1925. case OMPD_parallel_sections:
  1926. case OMPD_teams:
  1927. case OMPD_teams_distribute:
  1928. case OMPD_teams_distribute_simd: {
  1929. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1930. QualType KmpInt32PtrTy =
  1931. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1932. Sema::CapturedParamNameType Params[] = {
  1933. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1934. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1935. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1936. };
  1937. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1938. Params);
  1939. break;
  1940. }
  1941. case OMPD_target_teams:
  1942. case OMPD_target_parallel:
  1943. case OMPD_target_parallel_for:
  1944. case OMPD_target_parallel_for_simd:
  1945. case OMPD_target_teams_distribute: {
  1946. Sema::CapturedParamNameType ParamsTarget[] = {
  1947. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1948. };
  1949. // Start a captured region for 'target' with no implicit parameters.
  1950. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1951. ParamsTarget);
  1952. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1953. QualType KmpInt32PtrTy =
  1954. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1955. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  1956. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1957. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1958. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1959. };
  1960. // Start a captured region for 'teams' or 'parallel'. Both regions have
  1961. // the same implicit parameters.
  1962. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1963. ParamsTeamsOrParallel);
  1964. break;
  1965. }
  1966. case OMPD_simd:
  1967. case OMPD_for:
  1968. case OMPD_for_simd:
  1969. case OMPD_sections:
  1970. case OMPD_section:
  1971. case OMPD_single:
  1972. case OMPD_master:
  1973. case OMPD_critical:
  1974. case OMPD_taskgroup:
  1975. case OMPD_distribute:
  1976. case OMPD_distribute_simd:
  1977. case OMPD_ordered:
  1978. case OMPD_atomic:
  1979. case OMPD_target_data:
  1980. case OMPD_target:
  1981. case OMPD_target_simd: {
  1982. Sema::CapturedParamNameType Params[] = {
  1983. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1984. };
  1985. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1986. Params);
  1987. break;
  1988. }
  1989. case OMPD_task: {
  1990. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1991. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1992. FunctionProtoType::ExtProtoInfo EPI;
  1993. EPI.Variadic = true;
  1994. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1995. Sema::CapturedParamNameType Params[] = {
  1996. std::make_pair(".global_tid.", KmpInt32Ty),
  1997. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  1998. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  1999. std::make_pair(".copy_fn.",
  2000. Context.getPointerType(CopyFnType).withConst()),
  2001. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2002. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2003. };
  2004. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2005. Params);
  2006. // Mark this captured region as inlined, because we don't use outlined
  2007. // function directly.
  2008. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2009. AlwaysInlineAttr::CreateImplicit(
  2010. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2011. break;
  2012. }
  2013. case OMPD_taskloop:
  2014. case OMPD_taskloop_simd: {
  2015. QualType KmpInt32Ty =
  2016. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2017. QualType KmpUInt64Ty =
  2018. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  2019. QualType KmpInt64Ty =
  2020. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  2021. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2022. FunctionProtoType::ExtProtoInfo EPI;
  2023. EPI.Variadic = true;
  2024. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2025. Sema::CapturedParamNameType Params[] = {
  2026. std::make_pair(".global_tid.", KmpInt32Ty),
  2027. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2028. std::make_pair(".privates.",
  2029. Context.VoidPtrTy.withConst().withRestrict()),
  2030. std::make_pair(
  2031. ".copy_fn.",
  2032. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2033. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2034. std::make_pair(".lb.", KmpUInt64Ty),
  2035. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  2036. std::make_pair(".liter.", KmpInt32Ty),
  2037. std::make_pair(".reductions.",
  2038. Context.VoidPtrTy.withConst().withRestrict()),
  2039. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2040. };
  2041. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2042. Params);
  2043. // Mark this captured region as inlined, because we don't use outlined
  2044. // function directly.
  2045. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2046. AlwaysInlineAttr::CreateImplicit(
  2047. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2048. break;
  2049. }
  2050. case OMPD_distribute_parallel_for_simd:
  2051. case OMPD_distribute_parallel_for:
  2052. case OMPD_target_teams_distribute_parallel_for:
  2053. case OMPD_target_teams_distribute_parallel_for_simd:
  2054. case OMPD_target_teams_distribute_simd: {
  2055. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2056. QualType KmpInt32PtrTy =
  2057. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2058. Sema::CapturedParamNameType Params[] = {
  2059. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2060. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2061. std::make_pair(".previous.lb.", Context.getSizeType()),
  2062. std::make_pair(".previous.ub.", Context.getSizeType()),
  2063. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2064. };
  2065. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2066. Params);
  2067. break;
  2068. }
  2069. case OMPD_teams_distribute_parallel_for:
  2070. case OMPD_teams_distribute_parallel_for_simd: {
  2071. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2072. QualType KmpInt32PtrTy =
  2073. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2074. Sema::CapturedParamNameType ParamsTeams[] = {
  2075. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2076. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2077. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2078. };
  2079. // Start a captured region for 'target' with no implicit parameters.
  2080. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2081. ParamsTeams);
  2082. Sema::CapturedParamNameType ParamsParallel[] = {
  2083. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2084. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2085. std::make_pair(".previous.lb.", Context.getSizeType()),
  2086. std::make_pair(".previous.ub.", Context.getSizeType()),
  2087. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2088. };
  2089. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2090. // the same implicit parameters.
  2091. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2092. ParamsParallel);
  2093. break;
  2094. }
  2095. case OMPD_target_update:
  2096. case OMPD_target_enter_data:
  2097. case OMPD_target_exit_data: {
  2098. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2099. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2100. FunctionProtoType::ExtProtoInfo EPI;
  2101. EPI.Variadic = true;
  2102. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2103. Sema::CapturedParamNameType Params[] = {
  2104. std::make_pair(".global_tid.", KmpInt32Ty),
  2105. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2106. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2107. std::make_pair(".copy_fn.",
  2108. Context.getPointerType(CopyFnType).withConst()),
  2109. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2110. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2111. };
  2112. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2113. Params);
  2114. // Mark this captured region as inlined, because we don't use outlined
  2115. // function directly.
  2116. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2117. AlwaysInlineAttr::CreateImplicit(
  2118. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2119. break;
  2120. }
  2121. case OMPD_threadprivate:
  2122. case OMPD_taskyield:
  2123. case OMPD_barrier:
  2124. case OMPD_taskwait:
  2125. case OMPD_cancellation_point:
  2126. case OMPD_cancel:
  2127. case OMPD_flush:
  2128. case OMPD_declare_reduction:
  2129. case OMPD_declare_simd:
  2130. case OMPD_declare_target:
  2131. case OMPD_end_declare_target:
  2132. llvm_unreachable("OpenMP Directive is not allowed");
  2133. case OMPD_unknown:
  2134. llvm_unreachable("Unknown OpenMP directive");
  2135. }
  2136. }
  2137. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2138. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2139. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2140. return CaptureRegions.size();
  2141. }
  2142. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2143. Expr *CaptureExpr, bool WithInit,
  2144. bool AsExpression) {
  2145. assert(CaptureExpr);
  2146. ASTContext &C = S.getASTContext();
  2147. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2148. QualType Ty = Init->getType();
  2149. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2150. if (S.getLangOpts().CPlusPlus)
  2151. Ty = C.getLValueReferenceType(Ty);
  2152. else {
  2153. Ty = C.getPointerType(Ty);
  2154. ExprResult Res =
  2155. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2156. if (!Res.isUsable())
  2157. return nullptr;
  2158. Init = Res.get();
  2159. }
  2160. WithInit = true;
  2161. }
  2162. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2163. CaptureExpr->getLocStart());
  2164. if (!WithInit)
  2165. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  2166. S.CurContext->addHiddenDecl(CED);
  2167. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2168. return CED;
  2169. }
  2170. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2171. bool WithInit) {
  2172. OMPCapturedExprDecl *CD;
  2173. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  2174. CD = cast<OMPCapturedExprDecl>(VD);
  2175. else
  2176. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2177. /*AsExpression=*/false);
  2178. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2179. CaptureExpr->getExprLoc());
  2180. }
  2181. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2182. if (!Ref) {
  2183. auto *CD =
  2184. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  2185. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  2186. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2187. CaptureExpr->getExprLoc());
  2188. }
  2189. ExprResult Res = Ref;
  2190. if (!S.getLangOpts().CPlusPlus &&
  2191. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2192. Ref->getType()->isPointerType())
  2193. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2194. if (!Res.isUsable())
  2195. return ExprError();
  2196. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  2197. }
  2198. namespace {
  2199. // OpenMP directives parsed in this section are represented as a
  2200. // CapturedStatement with an associated statement. If a syntax error
  2201. // is detected during the parsing of the associated statement, the
  2202. // compiler must abort processing and close the CapturedStatement.
  2203. //
  2204. // Combined directives such as 'target parallel' have more than one
  2205. // nested CapturedStatements. This RAII ensures that we unwind out
  2206. // of all the nested CapturedStatements when an error is found.
  2207. class CaptureRegionUnwinderRAII {
  2208. private:
  2209. Sema &S;
  2210. bool &ErrorFound;
  2211. OpenMPDirectiveKind DKind;
  2212. public:
  2213. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2214. OpenMPDirectiveKind DKind)
  2215. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2216. ~CaptureRegionUnwinderRAII() {
  2217. if (ErrorFound) {
  2218. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2219. while (--ThisCaptureLevel >= 0)
  2220. S.ActOnCapturedRegionError();
  2221. }
  2222. }
  2223. };
  2224. } // namespace
  2225. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2226. ArrayRef<OMPClause *> Clauses) {
  2227. bool ErrorFound = false;
  2228. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2229. *this, ErrorFound, DSAStack->getCurrentDirective());
  2230. if (!S.isUsable()) {
  2231. ErrorFound = true;
  2232. return StmtError();
  2233. }
  2234. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2235. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2236. OMPOrderedClause *OC = nullptr;
  2237. OMPScheduleClause *SC = nullptr;
  2238. SmallVector<OMPLinearClause *, 4> LCs;
  2239. SmallVector<OMPClauseWithPreInit *, 8> PICs;
  2240. // This is required for proper codegen.
  2241. for (auto *Clause : Clauses) {
  2242. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2243. Clause->getClauseKind() == OMPC_in_reduction) {
  2244. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2245. // with the corresponding in_reduction items.
  2246. auto *IRC = cast<OMPInReductionClause>(Clause);
  2247. for (auto *E : IRC->taskgroup_descriptors())
  2248. if (E)
  2249. MarkDeclarationsReferencedInExpr(E);
  2250. }
  2251. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2252. Clause->getClauseKind() == OMPC_copyprivate ||
  2253. (getLangOpts().OpenMPUseTLS &&
  2254. getASTContext().getTargetInfo().isTLSSupported() &&
  2255. Clause->getClauseKind() == OMPC_copyin)) {
  2256. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2257. // Mark all variables in private list clauses as used in inner region.
  2258. for (auto *VarRef : Clause->children()) {
  2259. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2260. MarkDeclarationsReferencedInExpr(E);
  2261. }
  2262. }
  2263. DSAStack->setForceVarCapturing(/*V=*/false);
  2264. } else if (CaptureRegions.size() > 1 ||
  2265. CaptureRegions.back() != OMPD_unknown) {
  2266. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2267. PICs.push_back(C);
  2268. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2269. if (auto *E = C->getPostUpdateExpr())
  2270. MarkDeclarationsReferencedInExpr(E);
  2271. }
  2272. }
  2273. if (Clause->getClauseKind() == OMPC_schedule)
  2274. SC = cast<OMPScheduleClause>(Clause);
  2275. else if (Clause->getClauseKind() == OMPC_ordered)
  2276. OC = cast<OMPOrderedClause>(Clause);
  2277. else if (Clause->getClauseKind() == OMPC_linear)
  2278. LCs.push_back(cast<OMPLinearClause>(Clause));
  2279. }
  2280. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2281. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2282. // specified.
  2283. if (SC &&
  2284. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2285. SC->getSecondScheduleModifier() ==
  2286. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2287. OC) {
  2288. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2289. ? SC->getFirstScheduleModifierLoc()
  2290. : SC->getSecondScheduleModifierLoc(),
  2291. diag::err_omp_schedule_nonmonotonic_ordered)
  2292. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2293. ErrorFound = true;
  2294. }
  2295. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2296. for (auto *C : LCs) {
  2297. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2298. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2299. }
  2300. ErrorFound = true;
  2301. }
  2302. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2303. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2304. OC->getNumForLoops()) {
  2305. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2306. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2307. ErrorFound = true;
  2308. }
  2309. if (ErrorFound) {
  2310. return StmtError();
  2311. }
  2312. StmtResult SR = S;
  2313. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2314. // Mark all variables in private list clauses as used in inner region.
  2315. // Required for proper codegen of combined directives.
  2316. // TODO: add processing for other clauses.
  2317. if (ThisCaptureRegion != OMPD_unknown) {
  2318. for (auto *C : PICs) {
  2319. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2320. // Find the particular capture region for the clause if the
  2321. // directive is a combined one with multiple capture regions.
  2322. // If the directive is not a combined one, the capture region
  2323. // associated with the clause is OMPD_unknown and is generated
  2324. // only once.
  2325. if (CaptureRegion == ThisCaptureRegion ||
  2326. CaptureRegion == OMPD_unknown) {
  2327. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2328. for (auto *D : DS->decls())
  2329. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2330. }
  2331. }
  2332. }
  2333. }
  2334. SR = ActOnCapturedRegionEnd(SR.get());
  2335. }
  2336. return SR;
  2337. }
  2338. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2339. OpenMPDirectiveKind CancelRegion,
  2340. SourceLocation StartLoc) {
  2341. // CancelRegion is only needed for cancel and cancellation_point.
  2342. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2343. return false;
  2344. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2345. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2346. return false;
  2347. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2348. << getOpenMPDirectiveName(CancelRegion);
  2349. return true;
  2350. }
  2351. static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  2352. OpenMPDirectiveKind CurrentRegion,
  2353. const DeclarationNameInfo &CurrentName,
  2354. OpenMPDirectiveKind CancelRegion,
  2355. SourceLocation StartLoc) {
  2356. if (Stack->getCurScope()) {
  2357. auto ParentRegion = Stack->getParentDirective();
  2358. auto OffendingRegion = ParentRegion;
  2359. bool NestingProhibited = false;
  2360. bool CloseNesting = true;
  2361. bool OrphanSeen = false;
  2362. enum {
  2363. NoRecommend,
  2364. ShouldBeInParallelRegion,
  2365. ShouldBeInOrderedRegion,
  2366. ShouldBeInTargetRegion,
  2367. ShouldBeInTeamsRegion
  2368. } Recommend = NoRecommend;
  2369. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2370. // OpenMP [2.16, Nesting of Regions]
  2371. // OpenMP constructs may not be nested inside a simd region.
  2372. // OpenMP [2.8.1,simd Construct, Restrictions]
  2373. // An ordered construct with the simd clause is the only OpenMP
  2374. // construct that can appear in the simd region.
  2375. // Allowing a SIMD construct nested in another SIMD construct is an
  2376. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2377. // message.
  2378. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2379. ? diag::err_omp_prohibited_region_simd
  2380. : diag::warn_omp_nesting_simd);
  2381. return CurrentRegion != OMPD_simd;
  2382. }
  2383. if (ParentRegion == OMPD_atomic) {
  2384. // OpenMP [2.16, Nesting of Regions]
  2385. // OpenMP constructs may not be nested inside an atomic region.
  2386. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2387. return true;
  2388. }
  2389. if (CurrentRegion == OMPD_section) {
  2390. // OpenMP [2.7.2, sections Construct, Restrictions]
  2391. // Orphaned section directives are prohibited. That is, the section
  2392. // directives must appear within the sections construct and must not be
  2393. // encountered elsewhere in the sections region.
  2394. if (ParentRegion != OMPD_sections &&
  2395. ParentRegion != OMPD_parallel_sections) {
  2396. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2397. << (ParentRegion != OMPD_unknown)
  2398. << getOpenMPDirectiveName(ParentRegion);
  2399. return true;
  2400. }
  2401. return false;
  2402. }
  2403. // Allow some constructs (except teams) to be orphaned (they could be
  2404. // used in functions, called from OpenMP regions with the required
  2405. // preconditions).
  2406. if (ParentRegion == OMPD_unknown &&
  2407. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2408. return false;
  2409. if (CurrentRegion == OMPD_cancellation_point ||
  2410. CurrentRegion == OMPD_cancel) {
  2411. // OpenMP [2.16, Nesting of Regions]
  2412. // A cancellation point construct for which construct-type-clause is
  2413. // taskgroup must be nested inside a task construct. A cancellation
  2414. // point construct for which construct-type-clause is not taskgroup must
  2415. // be closely nested inside an OpenMP construct that matches the type
  2416. // specified in construct-type-clause.
  2417. // A cancel construct for which construct-type-clause is taskgroup must be
  2418. // nested inside a task construct. A cancel construct for which
  2419. // construct-type-clause is not taskgroup must be closely nested inside an
  2420. // OpenMP construct that matches the type specified in
  2421. // construct-type-clause.
  2422. NestingProhibited =
  2423. !((CancelRegion == OMPD_parallel &&
  2424. (ParentRegion == OMPD_parallel ||
  2425. ParentRegion == OMPD_target_parallel)) ||
  2426. (CancelRegion == OMPD_for &&
  2427. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2428. ParentRegion == OMPD_target_parallel_for ||
  2429. ParentRegion == OMPD_distribute_parallel_for ||
  2430. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2431. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2432. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2433. (CancelRegion == OMPD_sections &&
  2434. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2435. ParentRegion == OMPD_parallel_sections)));
  2436. } else if (CurrentRegion == OMPD_master) {
  2437. // OpenMP [2.16, Nesting of Regions]
  2438. // A master region may not be closely nested inside a worksharing,
  2439. // atomic, or explicit task region.
  2440. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2441. isOpenMPTaskingDirective(ParentRegion);
  2442. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2443. // OpenMP [2.16, Nesting of Regions]
  2444. // A critical region may not be nested (closely or otherwise) inside a
  2445. // critical region with the same name. Note that this restriction is not
  2446. // sufficient to prevent deadlock.
  2447. SourceLocation PreviousCriticalLoc;
  2448. bool DeadLock = Stack->hasDirective(
  2449. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2450. const DeclarationNameInfo &DNI,
  2451. SourceLocation Loc) -> bool {
  2452. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2453. PreviousCriticalLoc = Loc;
  2454. return true;
  2455. } else
  2456. return false;
  2457. },
  2458. false /* skip top directive */);
  2459. if (DeadLock) {
  2460. SemaRef.Diag(StartLoc,
  2461. diag::err_omp_prohibited_region_critical_same_name)
  2462. << CurrentName.getName();
  2463. if (PreviousCriticalLoc.isValid())
  2464. SemaRef.Diag(PreviousCriticalLoc,
  2465. diag::note_omp_previous_critical_region);
  2466. return true;
  2467. }
  2468. } else if (CurrentRegion == OMPD_barrier) {
  2469. // OpenMP [2.16, Nesting of Regions]
  2470. // A barrier region may not be closely nested inside a worksharing,
  2471. // explicit task, critical, ordered, atomic, or master region.
  2472. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2473. isOpenMPTaskingDirective(ParentRegion) ||
  2474. ParentRegion == OMPD_master ||
  2475. ParentRegion == OMPD_critical ||
  2476. ParentRegion == OMPD_ordered;
  2477. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2478. !isOpenMPParallelDirective(CurrentRegion) &&
  2479. !isOpenMPTeamsDirective(CurrentRegion)) {
  2480. // OpenMP [2.16, Nesting of Regions]
  2481. // A worksharing region may not be closely nested inside a worksharing,
  2482. // explicit task, critical, ordered, atomic, or master region.
  2483. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2484. isOpenMPTaskingDirective(ParentRegion) ||
  2485. ParentRegion == OMPD_master ||
  2486. ParentRegion == OMPD_critical ||
  2487. ParentRegion == OMPD_ordered;
  2488. Recommend = ShouldBeInParallelRegion;
  2489. } else if (CurrentRegion == OMPD_ordered) {
  2490. // OpenMP [2.16, Nesting of Regions]
  2491. // An ordered region may not be closely nested inside a critical,
  2492. // atomic, or explicit task region.
  2493. // An ordered region must be closely nested inside a loop region (or
  2494. // parallel loop region) with an ordered clause.
  2495. // OpenMP [2.8.1,simd Construct, Restrictions]
  2496. // An ordered construct with the simd clause is the only OpenMP construct
  2497. // that can appear in the simd region.
  2498. NestingProhibited = ParentRegion == OMPD_critical ||
  2499. isOpenMPTaskingDirective(ParentRegion) ||
  2500. !(isOpenMPSimdDirective(ParentRegion) ||
  2501. Stack->isParentOrderedRegion());
  2502. Recommend = ShouldBeInOrderedRegion;
  2503. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2504. // OpenMP [2.16, Nesting of Regions]
  2505. // If specified, a teams construct must be contained within a target
  2506. // construct.
  2507. NestingProhibited = ParentRegion != OMPD_target;
  2508. OrphanSeen = ParentRegion == OMPD_unknown;
  2509. Recommend = ShouldBeInTargetRegion;
  2510. }
  2511. if (!NestingProhibited &&
  2512. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2513. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2514. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2515. // OpenMP [2.16, Nesting of Regions]
  2516. // distribute, parallel, parallel sections, parallel workshare, and the
  2517. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2518. // constructs that can be closely nested in the teams region.
  2519. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2520. !isOpenMPDistributeDirective(CurrentRegion);
  2521. Recommend = ShouldBeInParallelRegion;
  2522. }
  2523. if (!NestingProhibited &&
  2524. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2525. // OpenMP 4.5 [2.17 Nesting of Regions]
  2526. // The region associated with the distribute construct must be strictly
  2527. // nested inside a teams region
  2528. NestingProhibited =
  2529. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2530. Recommend = ShouldBeInTeamsRegion;
  2531. }
  2532. if (!NestingProhibited &&
  2533. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2534. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2535. // OpenMP 4.5 [2.17 Nesting of Regions]
  2536. // If a target, target update, target data, target enter data, or
  2537. // target exit data construct is encountered during execution of a
  2538. // target region, the behavior is unspecified.
  2539. NestingProhibited = Stack->hasDirective(
  2540. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2541. SourceLocation) -> bool {
  2542. if (isOpenMPTargetExecutionDirective(K)) {
  2543. OffendingRegion = K;
  2544. return true;
  2545. } else
  2546. return false;
  2547. },
  2548. false /* don't skip top directive */);
  2549. CloseNesting = false;
  2550. }
  2551. if (NestingProhibited) {
  2552. if (OrphanSeen) {
  2553. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2554. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2555. } else {
  2556. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2557. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2558. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2559. }
  2560. return true;
  2561. }
  2562. }
  2563. return false;
  2564. }
  2565. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2566. ArrayRef<OMPClause *> Clauses,
  2567. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2568. bool ErrorFound = false;
  2569. unsigned NamedModifiersNumber = 0;
  2570. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2571. OMPD_unknown + 1);
  2572. SmallVector<SourceLocation, 4> NameModifierLoc;
  2573. for (const auto *C : Clauses) {
  2574. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2575. // At most one if clause without a directive-name-modifier can appear on
  2576. // the directive.
  2577. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2578. if (FoundNameModifiers[CurNM]) {
  2579. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2580. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2581. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2582. ErrorFound = true;
  2583. } else if (CurNM != OMPD_unknown) {
  2584. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2585. ++NamedModifiersNumber;
  2586. }
  2587. FoundNameModifiers[CurNM] = IC;
  2588. if (CurNM == OMPD_unknown)
  2589. continue;
  2590. // Check if the specified name modifier is allowed for the current
  2591. // directive.
  2592. // At most one if clause with the particular directive-name-modifier can
  2593. // appear on the directive.
  2594. bool MatchFound = false;
  2595. for (auto NM : AllowedNameModifiers) {
  2596. if (CurNM == NM) {
  2597. MatchFound = true;
  2598. break;
  2599. }
  2600. }
  2601. if (!MatchFound) {
  2602. S.Diag(IC->getNameModifierLoc(),
  2603. diag::err_omp_wrong_if_directive_name_modifier)
  2604. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2605. ErrorFound = true;
  2606. }
  2607. }
  2608. }
  2609. // If any if clause on the directive includes a directive-name-modifier then
  2610. // all if clauses on the directive must include a directive-name-modifier.
  2611. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2612. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2613. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2614. diag::err_omp_no_more_if_clause);
  2615. } else {
  2616. std::string Values;
  2617. std::string Sep(", ");
  2618. unsigned AllowedCnt = 0;
  2619. unsigned TotalAllowedNum =
  2620. AllowedNameModifiers.size() - NamedModifiersNumber;
  2621. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2622. ++Cnt) {
  2623. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2624. if (!FoundNameModifiers[NM]) {
  2625. Values += "'";
  2626. Values += getOpenMPDirectiveName(NM);
  2627. Values += "'";
  2628. if (AllowedCnt + 2 == TotalAllowedNum)
  2629. Values += " or ";
  2630. else if (AllowedCnt + 1 != TotalAllowedNum)
  2631. Values += Sep;
  2632. ++AllowedCnt;
  2633. }
  2634. }
  2635. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2636. diag::err_omp_unnamed_if_clause)
  2637. << (TotalAllowedNum > 1) << Values;
  2638. }
  2639. for (auto Loc : NameModifierLoc) {
  2640. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2641. }
  2642. ErrorFound = true;
  2643. }
  2644. return ErrorFound;
  2645. }
  2646. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2647. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2648. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2649. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2650. StmtResult Res = StmtError();
  2651. // First check CancelRegion which is then used in checkNestingOfRegions.
  2652. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2653. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2654. StartLoc))
  2655. return StmtError();
  2656. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2657. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2658. bool ErrorFound = false;
  2659. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2660. if (AStmt && !CurContext->isDependentContext()) {
  2661. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2662. // Check default data sharing attributes for referenced variables.
  2663. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2664. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2665. Stmt *S = AStmt;
  2666. while (--ThisCaptureLevel >= 0)
  2667. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2668. DSAChecker.Visit(S);
  2669. if (DSAChecker.isErrorFound())
  2670. return StmtError();
  2671. // Generate list of implicitly defined firstprivate variables.
  2672. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2673. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2674. DSAChecker.getImplicitFirstprivate().begin(),
  2675. DSAChecker.getImplicitFirstprivate().end());
  2676. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2677. DSAChecker.getImplicitMap().end());
  2678. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2679. for (auto *C : Clauses) {
  2680. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2681. for (auto *E : IRC->taskgroup_descriptors())
  2682. if (E)
  2683. ImplicitFirstprivates.emplace_back(E);
  2684. }
  2685. }
  2686. if (!ImplicitFirstprivates.empty()) {
  2687. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2688. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2689. SourceLocation())) {
  2690. ClausesWithImplicit.push_back(Implicit);
  2691. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2692. ImplicitFirstprivates.size();
  2693. } else
  2694. ErrorFound = true;
  2695. }
  2696. if (!ImplicitMaps.empty()) {
  2697. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2698. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2699. SourceLocation(), SourceLocation(), ImplicitMaps,
  2700. SourceLocation(), SourceLocation(), SourceLocation())) {
  2701. ClausesWithImplicit.emplace_back(Implicit);
  2702. ErrorFound |=
  2703. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2704. } else
  2705. ErrorFound = true;
  2706. }
  2707. }
  2708. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2709. switch (Kind) {
  2710. case OMPD_parallel:
  2711. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2712. EndLoc);
  2713. AllowedNameModifiers.push_back(OMPD_parallel);
  2714. break;
  2715. case OMPD_simd:
  2716. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2717. VarsWithInheritedDSA);
  2718. break;
  2719. case OMPD_for:
  2720. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2721. VarsWithInheritedDSA);
  2722. break;
  2723. case OMPD_for_simd:
  2724. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2725. EndLoc, VarsWithInheritedDSA);
  2726. break;
  2727. case OMPD_sections:
  2728. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2729. EndLoc);
  2730. break;
  2731. case OMPD_section:
  2732. assert(ClausesWithImplicit.empty() &&
  2733. "No clauses are allowed for 'omp section' directive");
  2734. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2735. break;
  2736. case OMPD_single:
  2737. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2738. EndLoc);
  2739. break;
  2740. case OMPD_master:
  2741. assert(ClausesWithImplicit.empty() &&
  2742. "No clauses are allowed for 'omp master' directive");
  2743. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2744. break;
  2745. case OMPD_critical:
  2746. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2747. StartLoc, EndLoc);
  2748. break;
  2749. case OMPD_parallel_for:
  2750. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2751. EndLoc, VarsWithInheritedDSA);
  2752. AllowedNameModifiers.push_back(OMPD_parallel);
  2753. break;
  2754. case OMPD_parallel_for_simd:
  2755. Res = ActOnOpenMPParallelForSimdDirective(
  2756. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2757. AllowedNameModifiers.push_back(OMPD_parallel);
  2758. break;
  2759. case OMPD_parallel_sections:
  2760. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2761. StartLoc, EndLoc);
  2762. AllowedNameModifiers.push_back(OMPD_parallel);
  2763. break;
  2764. case OMPD_task:
  2765. Res =
  2766. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2767. AllowedNameModifiers.push_back(OMPD_task);
  2768. break;
  2769. case OMPD_taskyield:
  2770. assert(ClausesWithImplicit.empty() &&
  2771. "No clauses are allowed for 'omp taskyield' directive");
  2772. assert(AStmt == nullptr &&
  2773. "No associated statement allowed for 'omp taskyield' directive");
  2774. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2775. break;
  2776. case OMPD_barrier:
  2777. assert(ClausesWithImplicit.empty() &&
  2778. "No clauses are allowed for 'omp barrier' directive");
  2779. assert(AStmt == nullptr &&
  2780. "No associated statement allowed for 'omp barrier' directive");
  2781. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2782. break;
  2783. case OMPD_taskwait:
  2784. assert(ClausesWithImplicit.empty() &&
  2785. "No clauses are allowed for 'omp taskwait' directive");
  2786. assert(AStmt == nullptr &&
  2787. "No associated statement allowed for 'omp taskwait' directive");
  2788. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2789. break;
  2790. case OMPD_taskgroup:
  2791. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  2792. EndLoc);
  2793. break;
  2794. case OMPD_flush:
  2795. assert(AStmt == nullptr &&
  2796. "No associated statement allowed for 'omp flush' directive");
  2797. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2798. break;
  2799. case OMPD_ordered:
  2800. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2801. EndLoc);
  2802. break;
  2803. case OMPD_atomic:
  2804. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2805. EndLoc);
  2806. break;
  2807. case OMPD_teams:
  2808. Res =
  2809. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2810. break;
  2811. case OMPD_target:
  2812. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2813. EndLoc);
  2814. AllowedNameModifiers.push_back(OMPD_target);
  2815. break;
  2816. case OMPD_target_parallel:
  2817. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2818. StartLoc, EndLoc);
  2819. AllowedNameModifiers.push_back(OMPD_target);
  2820. AllowedNameModifiers.push_back(OMPD_parallel);
  2821. break;
  2822. case OMPD_target_parallel_for:
  2823. Res = ActOnOpenMPTargetParallelForDirective(
  2824. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2825. AllowedNameModifiers.push_back(OMPD_target);
  2826. AllowedNameModifiers.push_back(OMPD_parallel);
  2827. break;
  2828. case OMPD_cancellation_point:
  2829. assert(ClausesWithImplicit.empty() &&
  2830. "No clauses are allowed for 'omp cancellation point' directive");
  2831. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2832. "cancellation point' directive");
  2833. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2834. break;
  2835. case OMPD_cancel:
  2836. assert(AStmt == nullptr &&
  2837. "No associated statement allowed for 'omp cancel' directive");
  2838. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2839. CancelRegion);
  2840. AllowedNameModifiers.push_back(OMPD_cancel);
  2841. break;
  2842. case OMPD_target_data:
  2843. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2844. EndLoc);
  2845. AllowedNameModifiers.push_back(OMPD_target_data);
  2846. break;
  2847. case OMPD_target_enter_data:
  2848. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2849. EndLoc, AStmt);
  2850. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2851. break;
  2852. case OMPD_target_exit_data:
  2853. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2854. EndLoc, AStmt);
  2855. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2856. break;
  2857. case OMPD_taskloop:
  2858. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2859. EndLoc, VarsWithInheritedDSA);
  2860. AllowedNameModifiers.push_back(OMPD_taskloop);
  2861. break;
  2862. case OMPD_taskloop_simd:
  2863. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2864. EndLoc, VarsWithInheritedDSA);
  2865. AllowedNameModifiers.push_back(OMPD_taskloop);
  2866. break;
  2867. case OMPD_distribute:
  2868. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2869. EndLoc, VarsWithInheritedDSA);
  2870. break;
  2871. case OMPD_target_update:
  2872. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  2873. EndLoc, AStmt);
  2874. AllowedNameModifiers.push_back(OMPD_target_update);
  2875. break;
  2876. case OMPD_distribute_parallel_for:
  2877. Res = ActOnOpenMPDistributeParallelForDirective(
  2878. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2879. AllowedNameModifiers.push_back(OMPD_parallel);
  2880. break;
  2881. case OMPD_distribute_parallel_for_simd:
  2882. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2883. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2884. AllowedNameModifiers.push_back(OMPD_parallel);
  2885. break;
  2886. case OMPD_distribute_simd:
  2887. Res = ActOnOpenMPDistributeSimdDirective(
  2888. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2889. break;
  2890. case OMPD_target_parallel_for_simd:
  2891. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2892. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2893. AllowedNameModifiers.push_back(OMPD_target);
  2894. AllowedNameModifiers.push_back(OMPD_parallel);
  2895. break;
  2896. case OMPD_target_simd:
  2897. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2898. EndLoc, VarsWithInheritedDSA);
  2899. AllowedNameModifiers.push_back(OMPD_target);
  2900. break;
  2901. case OMPD_teams_distribute:
  2902. Res = ActOnOpenMPTeamsDistributeDirective(
  2903. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2904. break;
  2905. case OMPD_teams_distribute_simd:
  2906. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2907. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2908. break;
  2909. case OMPD_teams_distribute_parallel_for_simd:
  2910. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2911. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2912. AllowedNameModifiers.push_back(OMPD_parallel);
  2913. break;
  2914. case OMPD_teams_distribute_parallel_for:
  2915. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2916. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2917. AllowedNameModifiers.push_back(OMPD_parallel);
  2918. break;
  2919. case OMPD_target_teams:
  2920. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2921. EndLoc);
  2922. AllowedNameModifiers.push_back(OMPD_target);
  2923. break;
  2924. case OMPD_target_teams_distribute:
  2925. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2926. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2927. AllowedNameModifiers.push_back(OMPD_target);
  2928. break;
  2929. case OMPD_target_teams_distribute_parallel_for:
  2930. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2931. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2932. AllowedNameModifiers.push_back(OMPD_target);
  2933. AllowedNameModifiers.push_back(OMPD_parallel);
  2934. break;
  2935. case OMPD_target_teams_distribute_parallel_for_simd:
  2936. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  2937. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2938. AllowedNameModifiers.push_back(OMPD_target);
  2939. AllowedNameModifiers.push_back(OMPD_parallel);
  2940. break;
  2941. case OMPD_target_teams_distribute_simd:
  2942. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  2943. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2944. AllowedNameModifiers.push_back(OMPD_target);
  2945. break;
  2946. case OMPD_declare_target:
  2947. case OMPD_end_declare_target:
  2948. case OMPD_threadprivate:
  2949. case OMPD_declare_reduction:
  2950. case OMPD_declare_simd:
  2951. llvm_unreachable("OpenMP Directive is not allowed");
  2952. case OMPD_unknown:
  2953. llvm_unreachable("Unknown OpenMP directive");
  2954. }
  2955. for (auto P : VarsWithInheritedDSA) {
  2956. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2957. << P.first << P.second->getSourceRange();
  2958. }
  2959. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2960. if (!AllowedNameModifiers.empty())
  2961. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2962. ErrorFound;
  2963. if (ErrorFound)
  2964. return StmtError();
  2965. return Res;
  2966. }
  2967. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2968. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2969. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2970. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2971. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2972. assert(Aligneds.size() == Alignments.size());
  2973. assert(Linears.size() == LinModifiers.size());
  2974. assert(Linears.size() == Steps.size());
  2975. if (!DG || DG.get().isNull())
  2976. return DeclGroupPtrTy();
  2977. if (!DG.get().isSingleDecl()) {
  2978. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2979. return DG;
  2980. }
  2981. auto *ADecl = DG.get().getSingleDecl();
  2982. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2983. ADecl = FTD->getTemplatedDecl();
  2984. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2985. if (!FD) {
  2986. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2987. return DeclGroupPtrTy();
  2988. }
  2989. // OpenMP [2.8.2, declare simd construct, Description]
  2990. // The parameter of the simdlen clause must be a constant positive integer
  2991. // expression.
  2992. ExprResult SL;
  2993. if (Simdlen)
  2994. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  2995. // OpenMP [2.8.2, declare simd construct, Description]
  2996. // The special this pointer can be used as if was one of the arguments to the
  2997. // function in any of the linear, aligned, or uniform clauses.
  2998. // The uniform clause declares one or more arguments to have an invariant
  2999. // value for all concurrent invocations of the function in the execution of a
  3000. // single SIMD loop.
  3001. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  3002. Expr *UniformedLinearThis = nullptr;
  3003. for (auto *E : Uniforms) {
  3004. E = E->IgnoreParenImpCasts();
  3005. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3006. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3007. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3008. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3009. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3010. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  3011. continue;
  3012. }
  3013. if (isa<CXXThisExpr>(E)) {
  3014. UniformedLinearThis = E;
  3015. continue;
  3016. }
  3017. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3018. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3019. }
  3020. // OpenMP [2.8.2, declare simd construct, Description]
  3021. // The aligned clause declares that the object to which each list item points
  3022. // is aligned to the number of bytes expressed in the optional parameter of
  3023. // the aligned clause.
  3024. // The special this pointer can be used as if was one of the arguments to the
  3025. // function in any of the linear, aligned, or uniform clauses.
  3026. // The type of list items appearing in the aligned clause must be array,
  3027. // pointer, reference to array, or reference to pointer.
  3028. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  3029. Expr *AlignedThis = nullptr;
  3030. for (auto *E : Aligneds) {
  3031. E = E->IgnoreParenImpCasts();
  3032. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3033. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3034. auto *CanonPVD = PVD->getCanonicalDecl();
  3035. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3036. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3037. ->getCanonicalDecl() == CanonPVD) {
  3038. // OpenMP [2.8.1, simd construct, Restrictions]
  3039. // A list-item cannot appear in more than one aligned clause.
  3040. if (AlignedArgs.count(CanonPVD) > 0) {
  3041. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3042. << 1 << E->getSourceRange();
  3043. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3044. diag::note_omp_explicit_dsa)
  3045. << getOpenMPClauseName(OMPC_aligned);
  3046. continue;
  3047. }
  3048. AlignedArgs[CanonPVD] = E;
  3049. QualType QTy = PVD->getType()
  3050. .getNonReferenceType()
  3051. .getUnqualifiedType()
  3052. .getCanonicalType();
  3053. const Type *Ty = QTy.getTypePtrOrNull();
  3054. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3055. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3056. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3057. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3058. }
  3059. continue;
  3060. }
  3061. }
  3062. if (isa<CXXThisExpr>(E)) {
  3063. if (AlignedThis) {
  3064. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3065. << 2 << E->getSourceRange();
  3066. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3067. << getOpenMPClauseName(OMPC_aligned);
  3068. }
  3069. AlignedThis = E;
  3070. continue;
  3071. }
  3072. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3073. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3074. }
  3075. // The optional parameter of the aligned clause, alignment, must be a constant
  3076. // positive integer expression. If no optional parameter is specified,
  3077. // implementation-defined default alignments for SIMD instructions on the
  3078. // target platforms are assumed.
  3079. SmallVector<Expr *, 4> NewAligns;
  3080. for (auto *E : Alignments) {
  3081. ExprResult Align;
  3082. if (E)
  3083. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3084. NewAligns.push_back(Align.get());
  3085. }
  3086. // OpenMP [2.8.2, declare simd construct, Description]
  3087. // The linear clause declares one or more list items to be private to a SIMD
  3088. // lane and to have a linear relationship with respect to the iteration space
  3089. // of a loop.
  3090. // The special this pointer can be used as if was one of the arguments to the
  3091. // function in any of the linear, aligned, or uniform clauses.
  3092. // When a linear-step expression is specified in a linear clause it must be
  3093. // either a constant integer expression or an integer-typed parameter that is
  3094. // specified in a uniform clause on the directive.
  3095. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  3096. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3097. auto MI = LinModifiers.begin();
  3098. for (auto *E : Linears) {
  3099. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3100. ++MI;
  3101. E = E->IgnoreParenImpCasts();
  3102. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3103. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3104. auto *CanonPVD = PVD->getCanonicalDecl();
  3105. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3106. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3107. ->getCanonicalDecl() == CanonPVD) {
  3108. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3109. // A list-item cannot appear in more than one linear clause.
  3110. if (LinearArgs.count(CanonPVD) > 0) {
  3111. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3112. << getOpenMPClauseName(OMPC_linear)
  3113. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3114. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3115. diag::note_omp_explicit_dsa)
  3116. << getOpenMPClauseName(OMPC_linear);
  3117. continue;
  3118. }
  3119. // Each argument can appear in at most one uniform or linear clause.
  3120. if (UniformedArgs.count(CanonPVD) > 0) {
  3121. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3122. << getOpenMPClauseName(OMPC_linear)
  3123. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3124. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3125. diag::note_omp_explicit_dsa)
  3126. << getOpenMPClauseName(OMPC_uniform);
  3127. continue;
  3128. }
  3129. LinearArgs[CanonPVD] = E;
  3130. if (E->isValueDependent() || E->isTypeDependent() ||
  3131. E->isInstantiationDependent() ||
  3132. E->containsUnexpandedParameterPack())
  3133. continue;
  3134. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3135. PVD->getOriginalType());
  3136. continue;
  3137. }
  3138. }
  3139. if (isa<CXXThisExpr>(E)) {
  3140. if (UniformedLinearThis) {
  3141. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3142. << getOpenMPClauseName(OMPC_linear)
  3143. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3144. << E->getSourceRange();
  3145. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3146. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3147. : OMPC_linear);
  3148. continue;
  3149. }
  3150. UniformedLinearThis = E;
  3151. if (E->isValueDependent() || E->isTypeDependent() ||
  3152. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3153. continue;
  3154. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3155. E->getType());
  3156. continue;
  3157. }
  3158. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3159. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3160. }
  3161. Expr *Step = nullptr;
  3162. Expr *NewStep = nullptr;
  3163. SmallVector<Expr *, 4> NewSteps;
  3164. for (auto *E : Steps) {
  3165. // Skip the same step expression, it was checked already.
  3166. if (Step == E || !E) {
  3167. NewSteps.push_back(E ? NewStep : nullptr);
  3168. continue;
  3169. }
  3170. Step = E;
  3171. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3172. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3173. auto *CanonPVD = PVD->getCanonicalDecl();
  3174. if (UniformedArgs.count(CanonPVD) == 0) {
  3175. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3176. << Step->getSourceRange();
  3177. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3178. E->isInstantiationDependent() ||
  3179. E->containsUnexpandedParameterPack() ||
  3180. CanonPVD->getType()->hasIntegerRepresentation())
  3181. NewSteps.push_back(Step);
  3182. else {
  3183. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3184. << Step->getSourceRange();
  3185. }
  3186. continue;
  3187. }
  3188. NewStep = Step;
  3189. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3190. !Step->isInstantiationDependent() &&
  3191. !Step->containsUnexpandedParameterPack()) {
  3192. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3193. .get();
  3194. if (NewStep)
  3195. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3196. }
  3197. NewSteps.push_back(NewStep);
  3198. }
  3199. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3200. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3201. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3202. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3203. const_cast<Expr **>(Linears.data()), Linears.size(),
  3204. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3205. NewSteps.data(), NewSteps.size(), SR);
  3206. ADecl->addAttr(NewAttr);
  3207. return ConvertDeclToDeclGroup(ADecl);
  3208. }
  3209. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3210. Stmt *AStmt,
  3211. SourceLocation StartLoc,
  3212. SourceLocation EndLoc) {
  3213. if (!AStmt)
  3214. return StmtError();
  3215. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3216. // 1.2.2 OpenMP Language Terminology
  3217. // Structured block - An executable statement with a single entry at the
  3218. // top and a single exit at the bottom.
  3219. // The point of exit cannot be a branch out of the structured block.
  3220. // longjmp() and throw() must not violate the entry/exit criteria.
  3221. CS->getCapturedDecl()->setNothrow();
  3222. getCurFunction()->setHasBranchProtectedScope();
  3223. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3224. DSAStack->isCancelRegion());
  3225. }
  3226. namespace {
  3227. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3228. /// extracting iteration space of each loop in the loop nest, that will be used
  3229. /// for IR generation.
  3230. class OpenMPIterationSpaceChecker {
  3231. /// \brief Reference to Sema.
  3232. Sema &SemaRef;
  3233. /// \brief A location for diagnostics (when there is no some better location).
  3234. SourceLocation DefaultLoc;
  3235. /// \brief A location for diagnostics (when increment is not compatible).
  3236. SourceLocation ConditionLoc;
  3237. /// \brief A source location for referring to loop init later.
  3238. SourceRange InitSrcRange;
  3239. /// \brief A source location for referring to condition later.
  3240. SourceRange ConditionSrcRange;
  3241. /// \brief A source location for referring to increment later.
  3242. SourceRange IncrementSrcRange;
  3243. /// \brief Loop variable.
  3244. ValueDecl *LCDecl = nullptr;
  3245. /// \brief Reference to loop variable.
  3246. Expr *LCRef = nullptr;
  3247. /// \brief Lower bound (initializer for the var).
  3248. Expr *LB = nullptr;
  3249. /// \brief Upper bound.
  3250. Expr *UB = nullptr;
  3251. /// \brief Loop step (increment).
  3252. Expr *Step = nullptr;
  3253. /// \brief This flag is true when condition is one of:
  3254. /// Var < UB
  3255. /// Var <= UB
  3256. /// UB > Var
  3257. /// UB >= Var
  3258. bool TestIsLessOp = false;
  3259. /// \brief This flag is true when condition is strict ( < or > ).
  3260. bool TestIsStrictOp = false;
  3261. /// \brief This flag is true when step is subtracted on each iteration.
  3262. bool SubtractStep = false;
  3263. public:
  3264. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3265. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3266. /// \brief Check init-expr for canonical loop form and save loop counter
  3267. /// variable - #Var and its initialization value - #LB.
  3268. bool CheckInit(Stmt *S, bool EmitDiags = true);
  3269. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3270. /// for less/greater and for strict/non-strict comparison.
  3271. bool CheckCond(Expr *S);
  3272. /// \brief Check incr-expr for canonical loop form and return true if it
  3273. /// does not conform, otherwise save loop step (#Step).
  3274. bool CheckInc(Expr *S);
  3275. /// \brief Return the loop counter variable.
  3276. ValueDecl *GetLoopDecl() const { return LCDecl; }
  3277. /// \brief Return the reference expression to loop counter variable.
  3278. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  3279. /// \brief Source range of the loop init.
  3280. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  3281. /// \brief Source range of the loop condition.
  3282. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  3283. /// \brief Source range of the loop increment.
  3284. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  3285. /// \brief True if the step should be subtracted.
  3286. bool ShouldSubtractStep() const { return SubtractStep; }
  3287. /// \brief Build the expression to calculate the number of iterations.
  3288. Expr *
  3289. BuildNumIterations(Scope *S, const bool LimitedType,
  3290. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3291. /// \brief Build the precondition expression for the loops.
  3292. Expr *BuildPreCond(Scope *S, Expr *Cond,
  3293. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3294. /// \brief Build reference expression to the counter be used for codegen.
  3295. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  3296. DSAStackTy &DSA) const;
  3297. /// \brief Build reference expression to the private counter be used for
  3298. /// codegen.
  3299. Expr *BuildPrivateCounterVar() const;
  3300. /// \brief Build initialization of the counter be used for codegen.
  3301. Expr *BuildCounterInit() const;
  3302. /// \brief Build step of the counter be used for codegen.
  3303. Expr *BuildCounterStep() const;
  3304. /// \brief Return true if any expression is dependent.
  3305. bool Dependent() const;
  3306. private:
  3307. /// \brief Check the right-hand side of an assignment in the increment
  3308. /// expression.
  3309. bool CheckIncRHS(Expr *RHS);
  3310. /// \brief Helper to set loop counter variable and its initializer.
  3311. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3312. /// \brief Helper to set upper bound.
  3313. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3314. SourceLocation SL);
  3315. /// \brief Helper to set loop increment.
  3316. bool SetStep(Expr *NewStep, bool Subtract);
  3317. };
  3318. bool OpenMPIterationSpaceChecker::Dependent() const {
  3319. if (!LCDecl) {
  3320. assert(!LB && !UB && !Step);
  3321. return false;
  3322. }
  3323. return LCDecl->getType()->isDependentType() ||
  3324. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3325. (Step && Step->isValueDependent());
  3326. }
  3327. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  3328. Expr *NewLCRefExpr,
  3329. Expr *NewLB) {
  3330. // State consistency checking to ensure correct usage.
  3331. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3332. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3333. if (!NewLCDecl || !NewLB)
  3334. return true;
  3335. LCDecl = getCanonicalDecl(NewLCDecl);
  3336. LCRef = NewLCRefExpr;
  3337. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3338. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3339. if ((Ctor->isCopyOrMoveConstructor() ||
  3340. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3341. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3342. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3343. LB = NewLB;
  3344. return false;
  3345. }
  3346. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3347. SourceRange SR, SourceLocation SL) {
  3348. // State consistency checking to ensure correct usage.
  3349. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3350. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3351. if (!NewUB)
  3352. return true;
  3353. UB = NewUB;
  3354. TestIsLessOp = LessOp;
  3355. TestIsStrictOp = StrictOp;
  3356. ConditionSrcRange = SR;
  3357. ConditionLoc = SL;
  3358. return false;
  3359. }
  3360. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3361. // State consistency checking to ensure correct usage.
  3362. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3363. if (!NewStep)
  3364. return true;
  3365. if (!NewStep->isValueDependent()) {
  3366. // Check that the step is integer expression.
  3367. SourceLocation StepLoc = NewStep->getLocStart();
  3368. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3369. StepLoc, getExprAsWritten(NewStep));
  3370. if (Val.isInvalid())
  3371. return true;
  3372. NewStep = Val.get();
  3373. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3374. // If test-expr is of form var relational-op b and relational-op is < or
  3375. // <= then incr-expr must cause var to increase on each iteration of the
  3376. // loop. If test-expr is of form var relational-op b and relational-op is
  3377. // > or >= then incr-expr must cause var to decrease on each iteration of
  3378. // the loop.
  3379. // If test-expr is of form b relational-op var and relational-op is < or
  3380. // <= then incr-expr must cause var to decrease on each iteration of the
  3381. // loop. If test-expr is of form b relational-op var and relational-op is
  3382. // > or >= then incr-expr must cause var to increase on each iteration of
  3383. // the loop.
  3384. llvm::APSInt Result;
  3385. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3386. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3387. bool IsConstNeg =
  3388. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3389. bool IsConstPos =
  3390. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3391. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3392. if (UB && (IsConstZero ||
  3393. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3394. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3395. SemaRef.Diag(NewStep->getExprLoc(),
  3396. diag::err_omp_loop_incr_not_compatible)
  3397. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3398. SemaRef.Diag(ConditionLoc,
  3399. diag::note_omp_loop_cond_requres_compatible_incr)
  3400. << TestIsLessOp << ConditionSrcRange;
  3401. return true;
  3402. }
  3403. if (TestIsLessOp == Subtract) {
  3404. NewStep =
  3405. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3406. .get();
  3407. Subtract = !Subtract;
  3408. }
  3409. }
  3410. Step = NewStep;
  3411. SubtractStep = Subtract;
  3412. return false;
  3413. }
  3414. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3415. // Check init-expr for canonical loop form and save loop counter
  3416. // variable - #Var and its initialization value - #LB.
  3417. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3418. // var = lb
  3419. // integer-type var = lb
  3420. // random-access-iterator-type var = lb
  3421. // pointer-type var = lb
  3422. //
  3423. if (!S) {
  3424. if (EmitDiags) {
  3425. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3426. }
  3427. return true;
  3428. }
  3429. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3430. if (!ExprTemp->cleanupsHaveSideEffects())
  3431. S = ExprTemp->getSubExpr();
  3432. InitSrcRange = S->getSourceRange();
  3433. if (Expr *E = dyn_cast<Expr>(S))
  3434. S = E->IgnoreParens();
  3435. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3436. if (BO->getOpcode() == BO_Assign) {
  3437. auto *LHS = BO->getLHS()->IgnoreParens();
  3438. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3439. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3440. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3441. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3442. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3443. }
  3444. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3445. if (ME->isArrow() &&
  3446. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3447. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3448. }
  3449. }
  3450. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3451. if (DS->isSingleDecl()) {
  3452. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3453. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3454. // Accept non-canonical init form here but emit ext. warning.
  3455. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3456. SemaRef.Diag(S->getLocStart(),
  3457. diag::ext_omp_loop_not_canonical_init)
  3458. << S->getSourceRange();
  3459. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  3460. }
  3461. }
  3462. }
  3463. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3464. if (CE->getOperator() == OO_Equal) {
  3465. auto *LHS = CE->getArg(0);
  3466. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3467. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3468. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3469. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3470. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3471. }
  3472. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3473. if (ME->isArrow() &&
  3474. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3475. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3476. }
  3477. }
  3478. }
  3479. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3480. return false;
  3481. if (EmitDiags) {
  3482. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3483. << S->getSourceRange();
  3484. }
  3485. return true;
  3486. }
  3487. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3488. /// variable (which may be the loop variable) if possible.
  3489. static const ValueDecl *GetInitLCDecl(Expr *E) {
  3490. if (!E)
  3491. return nullptr;
  3492. E = getExprAsWritten(E);
  3493. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3494. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3495. if ((Ctor->isCopyOrMoveConstructor() ||
  3496. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3497. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3498. E = CE->getArg(0)->IgnoreParenImpCasts();
  3499. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3500. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3501. return getCanonicalDecl(VD);
  3502. }
  3503. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3504. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3505. return getCanonicalDecl(ME->getMemberDecl());
  3506. return nullptr;
  3507. }
  3508. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3509. // Check test-expr for canonical form, save upper-bound UB, flags for
  3510. // less/greater and for strict/non-strict comparison.
  3511. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3512. // var relational-op b
  3513. // b relational-op var
  3514. //
  3515. if (!S) {
  3516. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3517. return true;
  3518. }
  3519. S = getExprAsWritten(S);
  3520. SourceLocation CondLoc = S->getLocStart();
  3521. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3522. if (BO->isRelationalOp()) {
  3523. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3524. return SetUB(BO->getRHS(),
  3525. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3526. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3527. BO->getSourceRange(), BO->getOperatorLoc());
  3528. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  3529. return SetUB(BO->getLHS(),
  3530. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3531. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3532. BO->getSourceRange(), BO->getOperatorLoc());
  3533. }
  3534. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3535. if (CE->getNumArgs() == 2) {
  3536. auto Op = CE->getOperator();
  3537. switch (Op) {
  3538. case OO_Greater:
  3539. case OO_GreaterEqual:
  3540. case OO_Less:
  3541. case OO_LessEqual:
  3542. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3543. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3544. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3545. CE->getOperatorLoc());
  3546. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3547. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3548. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3549. CE->getOperatorLoc());
  3550. break;
  3551. default:
  3552. break;
  3553. }
  3554. }
  3555. }
  3556. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3557. return false;
  3558. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3559. << S->getSourceRange() << LCDecl;
  3560. return true;
  3561. }
  3562. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3563. // RHS of canonical loop form increment can be:
  3564. // var + incr
  3565. // incr + var
  3566. // var - incr
  3567. //
  3568. RHS = RHS->IgnoreParenImpCasts();
  3569. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3570. if (BO->isAdditiveOp()) {
  3571. bool IsAdd = BO->getOpcode() == BO_Add;
  3572. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3573. return SetStep(BO->getRHS(), !IsAdd);
  3574. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  3575. return SetStep(BO->getLHS(), false);
  3576. }
  3577. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3578. bool IsAdd = CE->getOperator() == OO_Plus;
  3579. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3580. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3581. return SetStep(CE->getArg(1), !IsAdd);
  3582. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3583. return SetStep(CE->getArg(0), false);
  3584. }
  3585. }
  3586. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3587. return false;
  3588. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3589. << RHS->getSourceRange() << LCDecl;
  3590. return true;
  3591. }
  3592. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3593. // Check incr-expr for canonical loop form and return true if it
  3594. // does not conform.
  3595. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3596. // ++var
  3597. // var++
  3598. // --var
  3599. // var--
  3600. // var += incr
  3601. // var -= incr
  3602. // var = var + incr
  3603. // var = incr + var
  3604. // var = var - incr
  3605. //
  3606. if (!S) {
  3607. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3608. return true;
  3609. }
  3610. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3611. if (!ExprTemp->cleanupsHaveSideEffects())
  3612. S = ExprTemp->getSubExpr();
  3613. IncrementSrcRange = S->getSourceRange();
  3614. S = S->IgnoreParens();
  3615. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3616. if (UO->isIncrementDecrementOp() &&
  3617. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  3618. return SetStep(SemaRef
  3619. .ActOnIntegerConstant(UO->getLocStart(),
  3620. (UO->isDecrementOp() ? -1 : 1))
  3621. .get(),
  3622. false);
  3623. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3624. switch (BO->getOpcode()) {
  3625. case BO_AddAssign:
  3626. case BO_SubAssign:
  3627. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3628. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3629. break;
  3630. case BO_Assign:
  3631. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3632. return CheckIncRHS(BO->getRHS());
  3633. break;
  3634. default:
  3635. break;
  3636. }
  3637. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3638. switch (CE->getOperator()) {
  3639. case OO_PlusPlus:
  3640. case OO_MinusMinus:
  3641. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3642. return SetStep(SemaRef
  3643. .ActOnIntegerConstant(
  3644. CE->getLocStart(),
  3645. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3646. .get(),
  3647. false);
  3648. break;
  3649. case OO_PlusEqual:
  3650. case OO_MinusEqual:
  3651. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3652. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3653. break;
  3654. case OO_Equal:
  3655. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3656. return CheckIncRHS(CE->getArg(1));
  3657. break;
  3658. default:
  3659. break;
  3660. }
  3661. }
  3662. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3663. return false;
  3664. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3665. << S->getSourceRange() << LCDecl;
  3666. return true;
  3667. }
  3668. static ExprResult
  3669. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3670. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3671. if (SemaRef.CurContext->isDependentContext())
  3672. return ExprResult(Capture);
  3673. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3674. return SemaRef.PerformImplicitConversion(
  3675. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3676. /*AllowExplicit=*/true);
  3677. auto I = Captures.find(Capture);
  3678. if (I != Captures.end())
  3679. return buildCapture(SemaRef, Capture, I->second);
  3680. DeclRefExpr *Ref = nullptr;
  3681. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3682. Captures[Capture] = Ref;
  3683. return Res;
  3684. }
  3685. /// \brief Build the expression to calculate the number of iterations.
  3686. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3687. Scope *S, const bool LimitedType,
  3688. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3689. ExprResult Diff;
  3690. auto VarType = LCDecl->getType().getNonReferenceType();
  3691. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3692. SemaRef.getLangOpts().CPlusPlus) {
  3693. // Upper - Lower
  3694. auto *UBExpr = TestIsLessOp ? UB : LB;
  3695. auto *LBExpr = TestIsLessOp ? LB : UB;
  3696. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3697. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3698. if (!Upper || !Lower)
  3699. return nullptr;
  3700. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3701. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3702. // BuildBinOp already emitted error, this one is to point user to upper
  3703. // and lower bound, and to tell what is passed to 'operator-'.
  3704. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3705. << Upper->getSourceRange() << Lower->getSourceRange();
  3706. return nullptr;
  3707. }
  3708. }
  3709. if (!Diff.isUsable())
  3710. return nullptr;
  3711. // Upper - Lower [- 1]
  3712. if (TestIsStrictOp)
  3713. Diff = SemaRef.BuildBinOp(
  3714. S, DefaultLoc, BO_Sub, Diff.get(),
  3715. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3716. if (!Diff.isUsable())
  3717. return nullptr;
  3718. // Upper - Lower [- 1] + Step
  3719. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3720. if (!NewStep.isUsable())
  3721. return nullptr;
  3722. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3723. if (!Diff.isUsable())
  3724. return nullptr;
  3725. // Parentheses (for dumping/debugging purposes only).
  3726. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3727. if (!Diff.isUsable())
  3728. return nullptr;
  3729. // (Upper - Lower [- 1] + Step) / Step
  3730. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3731. if (!Diff.isUsable())
  3732. return nullptr;
  3733. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3734. QualType Type = Diff.get()->getType();
  3735. auto &C = SemaRef.Context;
  3736. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3737. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3738. if (!Type->isIntegerType() || UseVarType) {
  3739. unsigned NewSize =
  3740. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3741. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3742. : Type->hasSignedIntegerRepresentation();
  3743. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3744. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3745. Diff = SemaRef.PerformImplicitConversion(
  3746. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3747. if (!Diff.isUsable())
  3748. return nullptr;
  3749. }
  3750. }
  3751. if (LimitedType) {
  3752. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3753. if (NewSize != C.getTypeSize(Type)) {
  3754. if (NewSize < C.getTypeSize(Type)) {
  3755. assert(NewSize == 64 && "incorrect loop var size");
  3756. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3757. << InitSrcRange << ConditionSrcRange;
  3758. }
  3759. QualType NewType = C.getIntTypeForBitwidth(
  3760. NewSize, Type->hasSignedIntegerRepresentation() ||
  3761. C.getTypeSize(Type) < NewSize);
  3762. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3763. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3764. Sema::AA_Converting, true);
  3765. if (!Diff.isUsable())
  3766. return nullptr;
  3767. }
  3768. }
  3769. }
  3770. return Diff.get();
  3771. }
  3772. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3773. Scope *S, Expr *Cond,
  3774. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3775. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3776. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3777. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3778. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3779. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3780. if (!NewLB.isUsable() || !NewUB.isUsable())
  3781. return nullptr;
  3782. auto CondExpr = SemaRef.BuildBinOp(
  3783. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3784. : (TestIsStrictOp ? BO_GT : BO_GE),
  3785. NewLB.get(), NewUB.get());
  3786. if (CondExpr.isUsable()) {
  3787. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3788. SemaRef.Context.BoolTy))
  3789. CondExpr = SemaRef.PerformImplicitConversion(
  3790. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3791. /*AllowExplicit=*/true);
  3792. }
  3793. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3794. // Otherwise use original loop conditon and evaluate it in runtime.
  3795. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3796. }
  3797. /// \brief Build reference expression to the counter be used for codegen.
  3798. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3799. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3800. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3801. if (!VD) {
  3802. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3803. auto *Ref = buildDeclRefExpr(
  3804. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3805. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3806. // If the loop control decl is explicitly marked as private, do not mark it
  3807. // as captured again.
  3808. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3809. Captures.insert(std::make_pair(LCRef, Ref));
  3810. return Ref;
  3811. }
  3812. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3813. DefaultLoc);
  3814. }
  3815. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3816. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3817. auto Type = LCDecl->getType().getNonReferenceType();
  3818. auto *PrivateVar =
  3819. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3820. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3821. if (PrivateVar->isInvalidDecl())
  3822. return nullptr;
  3823. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3824. }
  3825. return nullptr;
  3826. }
  3827. /// \brief Build initialization of the counter to be used for codegen.
  3828. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3829. /// \brief Build step of the counter be used for codegen.
  3830. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3831. /// \brief Iteration space of a single for loop.
  3832. struct LoopIterationSpace final {
  3833. /// \brief Condition of the loop.
  3834. Expr *PreCond = nullptr;
  3835. /// \brief This expression calculates the number of iterations in the loop.
  3836. /// It is always possible to calculate it before starting the loop.
  3837. Expr *NumIterations = nullptr;
  3838. /// \brief The loop counter variable.
  3839. Expr *CounterVar = nullptr;
  3840. /// \brief Private loop counter variable.
  3841. Expr *PrivateCounterVar = nullptr;
  3842. /// \brief This is initializer for the initial value of #CounterVar.
  3843. Expr *CounterInit = nullptr;
  3844. /// \brief This is step for the #CounterVar used to generate its update:
  3845. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3846. Expr *CounterStep = nullptr;
  3847. /// \brief Should step be subtracted?
  3848. bool Subtract = false;
  3849. /// \brief Source range of the loop init.
  3850. SourceRange InitSrcRange;
  3851. /// \brief Source range of the loop condition.
  3852. SourceRange CondSrcRange;
  3853. /// \brief Source range of the loop increment.
  3854. SourceRange IncSrcRange;
  3855. };
  3856. } // namespace
  3857. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3858. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3859. assert(Init && "Expected loop in canonical form.");
  3860. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3861. if (AssociatedLoops > 0 &&
  3862. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3863. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3864. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3865. if (auto *D = ISC.GetLoopDecl()) {
  3866. auto *VD = dyn_cast<VarDecl>(D);
  3867. if (!VD) {
  3868. if (auto *Private = IsOpenMPCapturedDecl(D))
  3869. VD = Private;
  3870. else {
  3871. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3872. /*WithInit=*/false);
  3873. VD = cast<VarDecl>(Ref->getDecl());
  3874. }
  3875. }
  3876. DSAStack->addLoopControlVariable(D, VD);
  3877. }
  3878. }
  3879. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3880. }
  3881. }
  3882. /// \brief Called on a for stmt to check and extract its iteration space
  3883. /// for further processing (such as collapsing).
  3884. static bool CheckOpenMPIterationSpace(
  3885. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3886. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3887. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3888. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3889. LoopIterationSpace &ResultIterSpace,
  3890. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3891. // OpenMP [2.6, Canonical Loop Form]
  3892. // for (init-expr; test-expr; incr-expr) structured-block
  3893. auto *For = dyn_cast_or_null<ForStmt>(S);
  3894. if (!For) {
  3895. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3896. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3897. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3898. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3899. if (NestedLoopCount > 1) {
  3900. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3901. SemaRef.Diag(DSA.getConstructLoc(),
  3902. diag::note_omp_collapse_ordered_expr)
  3903. << 2 << CollapseLoopCountExpr->getSourceRange()
  3904. << OrderedLoopCountExpr->getSourceRange();
  3905. else if (CollapseLoopCountExpr)
  3906. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3907. diag::note_omp_collapse_ordered_expr)
  3908. << 0 << CollapseLoopCountExpr->getSourceRange();
  3909. else
  3910. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3911. diag::note_omp_collapse_ordered_expr)
  3912. << 1 << OrderedLoopCountExpr->getSourceRange();
  3913. }
  3914. return true;
  3915. }
  3916. assert(For->getBody());
  3917. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3918. // Check init.
  3919. auto Init = For->getInit();
  3920. if (ISC.CheckInit(Init))
  3921. return true;
  3922. bool HasErrors = false;
  3923. // Check loop variable's type.
  3924. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3925. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3926. // OpenMP [2.6, Canonical Loop Form]
  3927. // Var is one of the following:
  3928. // A variable of signed or unsigned integer type.
  3929. // For C++, a variable of a random access iterator type.
  3930. // For C, a variable of a pointer type.
  3931. auto VarType = LCDecl->getType().getNonReferenceType();
  3932. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3933. !VarType->isPointerType() &&
  3934. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3935. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3936. << SemaRef.getLangOpts().CPlusPlus;
  3937. HasErrors = true;
  3938. }
  3939. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3940. // a Construct
  3941. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3942. // parallel for construct is (are) private.
  3943. // The loop iteration variable in the associated for-loop of a simd
  3944. // construct with just one associated for-loop is linear with a
  3945. // constant-linear-step that is the increment of the associated for-loop.
  3946. // Exclude loop var from the list of variables with implicitly defined data
  3947. // sharing attributes.
  3948. VarsWithImplicitDSA.erase(LCDecl);
  3949. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3950. // in a Construct, C/C++].
  3951. // The loop iteration variable in the associated for-loop of a simd
  3952. // construct with just one associated for-loop may be listed in a linear
  3953. // clause with a constant-linear-step that is the increment of the
  3954. // associated for-loop.
  3955. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3956. // parallel for construct may be listed in a private or lastprivate clause.
  3957. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3958. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3959. // declared in the loop and it is predetermined as a private.
  3960. auto PredeterminedCKind =
  3961. isOpenMPSimdDirective(DKind)
  3962. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3963. : OMPC_private;
  3964. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3965. DVar.CKind != PredeterminedCKind) ||
  3966. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3967. isOpenMPDistributeDirective(DKind)) &&
  3968. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3969. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3970. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3971. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3972. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3973. << getOpenMPClauseName(PredeterminedCKind);
  3974. if (DVar.RefExpr == nullptr)
  3975. DVar.CKind = PredeterminedCKind;
  3976. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3977. HasErrors = true;
  3978. } else if (LoopDeclRefExpr != nullptr) {
  3979. // Make the loop iteration variable private (for worksharing constructs),
  3980. // linear (for simd directives with the only one associated loop) or
  3981. // lastprivate (for simd directives with several collapsed or ordered
  3982. // loops).
  3983. if (DVar.CKind == OMPC_unknown)
  3984. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3985. [](OpenMPDirectiveKind) -> bool { return true; },
  3986. /*FromParent=*/false);
  3987. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3988. }
  3989. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3990. // Check test-expr.
  3991. HasErrors |= ISC.CheckCond(For->getCond());
  3992. // Check incr-expr.
  3993. HasErrors |= ISC.CheckInc(For->getInc());
  3994. }
  3995. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3996. return HasErrors;
  3997. // Build the loop's iteration space representation.
  3998. ResultIterSpace.PreCond =
  3999. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4000. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  4001. DSA.getCurScope(),
  4002. (isOpenMPWorksharingDirective(DKind) ||
  4003. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4004. Captures);
  4005. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  4006. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  4007. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  4008. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  4009. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  4010. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  4011. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  4012. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  4013. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4014. ResultIterSpace.NumIterations == nullptr ||
  4015. ResultIterSpace.CounterVar == nullptr ||
  4016. ResultIterSpace.PrivateCounterVar == nullptr ||
  4017. ResultIterSpace.CounterInit == nullptr ||
  4018. ResultIterSpace.CounterStep == nullptr);
  4019. return HasErrors;
  4020. }
  4021. /// \brief Build 'VarRef = Start.
  4022. static ExprResult
  4023. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4024. ExprResult Start,
  4025. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4026. // Build 'VarRef = Start.
  4027. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4028. if (!NewStart.isUsable())
  4029. return ExprError();
  4030. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4031. VarRef.get()->getType())) {
  4032. NewStart = SemaRef.PerformImplicitConversion(
  4033. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4034. /*AllowExplicit=*/true);
  4035. if (!NewStart.isUsable())
  4036. return ExprError();
  4037. }
  4038. auto Init =
  4039. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4040. return Init;
  4041. }
  4042. /// \brief Build 'VarRef = Start + Iter * Step'.
  4043. static ExprResult
  4044. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  4045. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  4046. ExprResult Step, bool Subtract,
  4047. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  4048. // Add parentheses (for debugging purposes only).
  4049. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4050. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4051. !Step.isUsable())
  4052. return ExprError();
  4053. ExprResult NewStep = Step;
  4054. if (Captures)
  4055. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4056. if (NewStep.isInvalid())
  4057. return ExprError();
  4058. ExprResult Update =
  4059. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4060. if (!Update.isUsable())
  4061. return ExprError();
  4062. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4063. // 'VarRef = Start (+|-) Iter * Step'.
  4064. ExprResult NewStart = Start;
  4065. if (Captures)
  4066. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4067. if (NewStart.isInvalid())
  4068. return ExprError();
  4069. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4070. ExprResult SavedUpdate = Update;
  4071. ExprResult UpdateVal;
  4072. if (VarRef.get()->getType()->isOverloadableType() ||
  4073. NewStart.get()->getType()->isOverloadableType() ||
  4074. Update.get()->getType()->isOverloadableType()) {
  4075. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4076. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4077. Update =
  4078. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4079. if (Update.isUsable()) {
  4080. UpdateVal =
  4081. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4082. VarRef.get(), SavedUpdate.get());
  4083. if (UpdateVal.isUsable()) {
  4084. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4085. UpdateVal.get());
  4086. }
  4087. }
  4088. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4089. }
  4090. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4091. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4092. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4093. NewStart.get(), SavedUpdate.get());
  4094. if (!Update.isUsable())
  4095. return ExprError();
  4096. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4097. VarRef.get()->getType())) {
  4098. Update = SemaRef.PerformImplicitConversion(
  4099. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4100. if (!Update.isUsable())
  4101. return ExprError();
  4102. }
  4103. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4104. }
  4105. return Update;
  4106. }
  4107. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4108. /// bits.
  4109. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4110. if (E == nullptr)
  4111. return ExprError();
  4112. auto &C = SemaRef.Context;
  4113. QualType OldType = E->getType();
  4114. unsigned HasBits = C.getTypeSize(OldType);
  4115. if (HasBits >= Bits)
  4116. return ExprResult(E);
  4117. // OK to convert to signed, because new type has more bits than old.
  4118. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4119. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4120. true);
  4121. }
  4122. /// \brief Check if the given expression \a E is a constant integer that fits
  4123. /// into \a Bits bits.
  4124. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  4125. if (E == nullptr)
  4126. return false;
  4127. llvm::APSInt Result;
  4128. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4129. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4130. return false;
  4131. }
  4132. /// Build preinits statement for the given declarations.
  4133. static Stmt *buildPreInits(ASTContext &Context,
  4134. MutableArrayRef<Decl *> PreInits) {
  4135. if (!PreInits.empty()) {
  4136. return new (Context) DeclStmt(
  4137. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4138. SourceLocation(), SourceLocation());
  4139. }
  4140. return nullptr;
  4141. }
  4142. /// Build preinits statement for the given declarations.
  4143. static Stmt *
  4144. buildPreInits(ASTContext &Context,
  4145. const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4146. if (!Captures.empty()) {
  4147. SmallVector<Decl *, 16> PreInits;
  4148. for (auto &Pair : Captures)
  4149. PreInits.push_back(Pair.second->getDecl());
  4150. return buildPreInits(Context, PreInits);
  4151. }
  4152. return nullptr;
  4153. }
  4154. /// Build postupdate expression for the given list of postupdates expressions.
  4155. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4156. Expr *PostUpdate = nullptr;
  4157. if (!PostUpdates.empty()) {
  4158. for (auto *E : PostUpdates) {
  4159. Expr *ConvE = S.BuildCStyleCastExpr(
  4160. E->getExprLoc(),
  4161. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4162. E->getExprLoc(), E)
  4163. .get();
  4164. PostUpdate = PostUpdate
  4165. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4166. PostUpdate, ConvE)
  4167. .get()
  4168. : ConvE;
  4169. }
  4170. }
  4171. return PostUpdate;
  4172. }
  4173. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4174. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4175. /// number of collapsed loops otherwise.
  4176. static unsigned
  4177. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4178. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4179. DSAStackTy &DSA,
  4180. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  4181. OMPLoopDirective::HelperExprs &Built) {
  4182. unsigned NestedLoopCount = 1;
  4183. if (CollapseLoopCountExpr) {
  4184. // Found 'collapse' clause - calculate collapse number.
  4185. llvm::APSInt Result;
  4186. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4187. NestedLoopCount = Result.getLimitedValue();
  4188. }
  4189. if (OrderedLoopCountExpr) {
  4190. // Found 'ordered' clause - calculate collapse number.
  4191. llvm::APSInt Result;
  4192. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4193. if (Result.getLimitedValue() < NestedLoopCount) {
  4194. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4195. diag::err_omp_wrong_ordered_loop_count)
  4196. << OrderedLoopCountExpr->getSourceRange();
  4197. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4198. diag::note_collapse_loop_count)
  4199. << CollapseLoopCountExpr->getSourceRange();
  4200. }
  4201. NestedLoopCount = Result.getLimitedValue();
  4202. }
  4203. }
  4204. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4205. // 'for simd', etc.).
  4206. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  4207. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4208. IterSpaces.resize(NestedLoopCount);
  4209. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4210. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4211. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4212. NestedLoopCount, CollapseLoopCountExpr,
  4213. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4214. IterSpaces[Cnt], Captures))
  4215. return 0;
  4216. // Move on to the next nested for loop, or to the loop body.
  4217. // OpenMP [2.8.1, simd construct, Restrictions]
  4218. // All loops associated with the construct must be perfectly nested; that
  4219. // is, there must be no intervening code nor any OpenMP directive between
  4220. // any two loops.
  4221. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4222. }
  4223. Built.clear(/* size */ NestedLoopCount);
  4224. if (SemaRef.CurContext->isDependentContext())
  4225. return NestedLoopCount;
  4226. // An example of what is generated for the following code:
  4227. //
  4228. // #pragma omp simd collapse(2) ordered(2)
  4229. // for (i = 0; i < NI; ++i)
  4230. // for (k = 0; k < NK; ++k)
  4231. // for (j = J0; j < NJ; j+=2) {
  4232. // <loop body>
  4233. // }
  4234. //
  4235. // We generate the code below.
  4236. // Note: the loop body may be outlined in CodeGen.
  4237. // Note: some counters may be C++ classes, operator- is used to find number of
  4238. // iterations and operator+= to calculate counter value.
  4239. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4240. // or i64 is currently supported).
  4241. //
  4242. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4243. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4244. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4245. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4246. // // similar updates for vars in clauses (e.g. 'linear')
  4247. // <loop body (using local i and j)>
  4248. // }
  4249. // i = NI; // assign final values of counters
  4250. // j = NJ;
  4251. //
  4252. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4253. // the iteration counts of the collapsed for loops.
  4254. // Precondition tests if there is at least one iteration (all conditions are
  4255. // true).
  4256. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4257. auto N0 = IterSpaces[0].NumIterations;
  4258. ExprResult LastIteration32 = WidenIterationCount(
  4259. 32 /* Bits */, SemaRef
  4260. .PerformImplicitConversion(
  4261. N0->IgnoreImpCasts(), N0->getType(),
  4262. Sema::AA_Converting, /*AllowExplicit=*/true)
  4263. .get(),
  4264. SemaRef);
  4265. ExprResult LastIteration64 = WidenIterationCount(
  4266. 64 /* Bits */, SemaRef
  4267. .PerformImplicitConversion(
  4268. N0->IgnoreImpCasts(), N0->getType(),
  4269. Sema::AA_Converting, /*AllowExplicit=*/true)
  4270. .get(),
  4271. SemaRef);
  4272. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4273. return NestedLoopCount;
  4274. auto &C = SemaRef.Context;
  4275. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4276. Scope *CurScope = DSA.getCurScope();
  4277. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4278. if (PreCond.isUsable()) {
  4279. PreCond =
  4280. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4281. PreCond.get(), IterSpaces[Cnt].PreCond);
  4282. }
  4283. auto N = IterSpaces[Cnt].NumIterations;
  4284. SourceLocation Loc = N->getExprLoc();
  4285. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4286. if (LastIteration32.isUsable())
  4287. LastIteration32 = SemaRef.BuildBinOp(
  4288. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4289. SemaRef
  4290. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4291. Sema::AA_Converting,
  4292. /*AllowExplicit=*/true)
  4293. .get());
  4294. if (LastIteration64.isUsable())
  4295. LastIteration64 = SemaRef.BuildBinOp(
  4296. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4297. SemaRef
  4298. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4299. Sema::AA_Converting,
  4300. /*AllowExplicit=*/true)
  4301. .get());
  4302. }
  4303. // Choose either the 32-bit or 64-bit version.
  4304. ExprResult LastIteration = LastIteration64;
  4305. if (LastIteration32.isUsable() &&
  4306. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4307. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4308. FitsInto(
  4309. 32 /* Bits */,
  4310. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4311. LastIteration64.get(), SemaRef)))
  4312. LastIteration = LastIteration32;
  4313. QualType VType = LastIteration.get()->getType();
  4314. QualType RealVType = VType;
  4315. QualType StrideVType = VType;
  4316. if (isOpenMPTaskLoopDirective(DKind)) {
  4317. VType =
  4318. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4319. StrideVType =
  4320. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4321. }
  4322. if (!LastIteration.isUsable())
  4323. return 0;
  4324. // Save the number of iterations.
  4325. ExprResult NumIterations = LastIteration;
  4326. {
  4327. LastIteration = SemaRef.BuildBinOp(
  4328. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4329. LastIteration.get(),
  4330. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4331. if (!LastIteration.isUsable())
  4332. return 0;
  4333. }
  4334. // Calculate the last iteration number beforehand instead of doing this on
  4335. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4336. llvm::APSInt Result;
  4337. bool IsConstant =
  4338. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4339. ExprResult CalcLastIteration;
  4340. if (!IsConstant) {
  4341. ExprResult SaveRef =
  4342. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4343. LastIteration = SaveRef;
  4344. // Prepare SaveRef + 1.
  4345. NumIterations = SemaRef.BuildBinOp(
  4346. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4347. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4348. if (!NumIterations.isUsable())
  4349. return 0;
  4350. }
  4351. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4352. // Build variables passed into runtime, necessary for worksharing directives.
  4353. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4354. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4355. isOpenMPDistributeDirective(DKind)) {
  4356. // Lower bound variable, initialized with zero.
  4357. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4358. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4359. SemaRef.AddInitializerToDecl(LBDecl,
  4360. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4361. /*DirectInit*/ false);
  4362. // Upper bound variable, initialized with last iteration number.
  4363. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4364. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4365. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4366. /*DirectInit*/ false);
  4367. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4368. // This will be used to implement clause 'lastprivate'.
  4369. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4370. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4371. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4372. SemaRef.AddInitializerToDecl(ILDecl,
  4373. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4374. /*DirectInit*/ false);
  4375. // Stride variable returned by runtime (we initialize it to 1 by default).
  4376. VarDecl *STDecl =
  4377. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4378. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4379. SemaRef.AddInitializerToDecl(STDecl,
  4380. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4381. /*DirectInit*/ false);
  4382. // Build expression: UB = min(UB, LastIteration)
  4383. // It is necessary for CodeGen of directives with static scheduling.
  4384. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4385. UB.get(), LastIteration.get());
  4386. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4387. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4388. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4389. CondOp.get());
  4390. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4391. // If we have a combined directive that combines 'distribute', 'for' or
  4392. // 'simd' we need to be able to access the bounds of the schedule of the
  4393. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4394. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4395. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4396. // Lower bound variable, initialized with zero.
  4397. VarDecl *CombLBDecl =
  4398. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4399. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4400. SemaRef.AddInitializerToDecl(
  4401. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4402. /*DirectInit*/ false);
  4403. // Upper bound variable, initialized with last iteration number.
  4404. VarDecl *CombUBDecl =
  4405. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4406. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4407. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4408. /*DirectInit*/ false);
  4409. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4410. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4411. ExprResult CombCondOp =
  4412. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4413. LastIteration.get(), CombUB.get());
  4414. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4415. CombCondOp.get());
  4416. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4417. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4418. // We expect to have at least 2 more parameters than the 'parallel'
  4419. // directive does - the lower and upper bounds of the previous schedule.
  4420. assert(CD->getNumParams() >= 4 &&
  4421. "Unexpected number of parameters in loop combined directive");
  4422. // Set the proper type for the bounds given what we learned from the
  4423. // enclosed loops.
  4424. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4425. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4426. // Previous lower and upper bounds are obtained from the region
  4427. // parameters.
  4428. PrevLB =
  4429. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4430. PrevUB =
  4431. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4432. }
  4433. }
  4434. // Build the iteration variable and its initialization before loop.
  4435. ExprResult IV;
  4436. ExprResult Init, CombInit;
  4437. {
  4438. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4439. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4440. Expr *RHS =
  4441. (isOpenMPWorksharingDirective(DKind) ||
  4442. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4443. ? LB.get()
  4444. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4445. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4446. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4447. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4448. Expr *CombRHS =
  4449. (isOpenMPWorksharingDirective(DKind) ||
  4450. isOpenMPTaskLoopDirective(DKind) ||
  4451. isOpenMPDistributeDirective(DKind))
  4452. ? CombLB.get()
  4453. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4454. CombInit =
  4455. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4456. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4457. }
  4458. }
  4459. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4460. SourceLocation CondLoc;
  4461. ExprResult Cond =
  4462. (isOpenMPWorksharingDirective(DKind) ||
  4463. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4464. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4465. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4466. NumIterations.get());
  4467. ExprResult CombCond;
  4468. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4469. CombCond =
  4470. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4471. }
  4472. // Loop increment (IV = IV + 1)
  4473. SourceLocation IncLoc;
  4474. ExprResult Inc =
  4475. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4476. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4477. if (!Inc.isUsable())
  4478. return 0;
  4479. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4480. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4481. if (!Inc.isUsable())
  4482. return 0;
  4483. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4484. // Used for directives with static scheduling.
  4485. // In combined construct, add combined version that use CombLB and CombUB
  4486. // base variables for the update
  4487. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4488. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4489. isOpenMPDistributeDirective(DKind)) {
  4490. // LB + ST
  4491. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4492. if (!NextLB.isUsable())
  4493. return 0;
  4494. // LB = LB + ST
  4495. NextLB =
  4496. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4497. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4498. if (!NextLB.isUsable())
  4499. return 0;
  4500. // UB + ST
  4501. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4502. if (!NextUB.isUsable())
  4503. return 0;
  4504. // UB = UB + ST
  4505. NextUB =
  4506. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4507. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4508. if (!NextUB.isUsable())
  4509. return 0;
  4510. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4511. CombNextLB =
  4512. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4513. if (!NextLB.isUsable())
  4514. return 0;
  4515. // LB = LB + ST
  4516. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4517. CombNextLB.get());
  4518. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4519. if (!CombNextLB.isUsable())
  4520. return 0;
  4521. // UB + ST
  4522. CombNextUB =
  4523. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4524. if (!CombNextUB.isUsable())
  4525. return 0;
  4526. // UB = UB + ST
  4527. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4528. CombNextUB.get());
  4529. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4530. if (!CombNextUB.isUsable())
  4531. return 0;
  4532. }
  4533. }
  4534. // Create increment expression for distribute loop when combined in a same
  4535. // directive with for as IV = IV + ST; ensure upper bound expression based
  4536. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4537. // in combination with 'distribute', like in 'distribute parallel for'
  4538. SourceLocation DistIncLoc;
  4539. ExprResult DistCond, DistInc, PrevEUB;
  4540. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4541. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4542. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4543. DistInc =
  4544. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4545. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4546. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4547. DistInc.get());
  4548. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4549. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4550. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4551. // construct
  4552. SourceLocation DistEUBLoc;
  4553. ExprResult IsUBGreater =
  4554. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4555. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4556. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4557. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4558. CondOp.get());
  4559. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4560. }
  4561. // Build updates and final values of the loop counters.
  4562. bool HasErrors = false;
  4563. Built.Counters.resize(NestedLoopCount);
  4564. Built.Inits.resize(NestedLoopCount);
  4565. Built.Updates.resize(NestedLoopCount);
  4566. Built.Finals.resize(NestedLoopCount);
  4567. SmallVector<Expr *, 4> LoopMultipliers;
  4568. {
  4569. ExprResult Div;
  4570. // Go from inner nested loop to outer.
  4571. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4572. LoopIterationSpace &IS = IterSpaces[Cnt];
  4573. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4574. // Build: Iter = (IV / Div) % IS.NumIters
  4575. // where Div is product of previous iterations' IS.NumIters.
  4576. ExprResult Iter;
  4577. if (Div.isUsable()) {
  4578. Iter =
  4579. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4580. } else {
  4581. Iter = IV;
  4582. assert((Cnt == (int)NestedLoopCount - 1) &&
  4583. "unusable div expected on first iteration only");
  4584. }
  4585. if (Cnt != 0 && Iter.isUsable())
  4586. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4587. IS.NumIterations);
  4588. if (!Iter.isUsable()) {
  4589. HasErrors = true;
  4590. break;
  4591. }
  4592. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4593. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4594. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  4595. IS.CounterVar->getExprLoc(),
  4596. /*RefersToCapture=*/true);
  4597. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4598. IS.CounterInit, Captures);
  4599. if (!Init.isUsable()) {
  4600. HasErrors = true;
  4601. break;
  4602. }
  4603. ExprResult Update = BuildCounterUpdate(
  4604. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4605. IS.CounterStep, IS.Subtract, &Captures);
  4606. if (!Update.isUsable()) {
  4607. HasErrors = true;
  4608. break;
  4609. }
  4610. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4611. ExprResult Final = BuildCounterUpdate(
  4612. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4613. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4614. if (!Final.isUsable()) {
  4615. HasErrors = true;
  4616. break;
  4617. }
  4618. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4619. if (Cnt != 0) {
  4620. if (Div.isUnset())
  4621. Div = IS.NumIterations;
  4622. else
  4623. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4624. IS.NumIterations);
  4625. // Add parentheses (for debugging purposes only).
  4626. if (Div.isUsable())
  4627. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4628. if (!Div.isUsable()) {
  4629. HasErrors = true;
  4630. break;
  4631. }
  4632. LoopMultipliers.push_back(Div.get());
  4633. }
  4634. if (!Update.isUsable() || !Final.isUsable()) {
  4635. HasErrors = true;
  4636. break;
  4637. }
  4638. // Save results
  4639. Built.Counters[Cnt] = IS.CounterVar;
  4640. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4641. Built.Inits[Cnt] = Init.get();
  4642. Built.Updates[Cnt] = Update.get();
  4643. Built.Finals[Cnt] = Final.get();
  4644. }
  4645. }
  4646. if (HasErrors)
  4647. return 0;
  4648. // Save results
  4649. Built.IterationVarRef = IV.get();
  4650. Built.LastIteration = LastIteration.get();
  4651. Built.NumIterations = NumIterations.get();
  4652. Built.CalcLastIteration =
  4653. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4654. Built.PreCond = PreCond.get();
  4655. Built.PreInits = buildPreInits(C, Captures);
  4656. Built.Cond = Cond.get();
  4657. Built.Init = Init.get();
  4658. Built.Inc = Inc.get();
  4659. Built.LB = LB.get();
  4660. Built.UB = UB.get();
  4661. Built.IL = IL.get();
  4662. Built.ST = ST.get();
  4663. Built.EUB = EUB.get();
  4664. Built.NLB = NextLB.get();
  4665. Built.NUB = NextUB.get();
  4666. Built.PrevLB = PrevLB.get();
  4667. Built.PrevUB = PrevUB.get();
  4668. Built.DistInc = DistInc.get();
  4669. Built.PrevEUB = PrevEUB.get();
  4670. Built.DistCombinedFields.LB = CombLB.get();
  4671. Built.DistCombinedFields.UB = CombUB.get();
  4672. Built.DistCombinedFields.EUB = CombEUB.get();
  4673. Built.DistCombinedFields.Init = CombInit.get();
  4674. Built.DistCombinedFields.Cond = CombCond.get();
  4675. Built.DistCombinedFields.NLB = CombNextLB.get();
  4676. Built.DistCombinedFields.NUB = CombNextUB.get();
  4677. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4678. // Fill data for doacross depend clauses.
  4679. for (auto Pair : DSA.getDoacrossDependClauses()) {
  4680. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4681. Pair.first->setCounterValue(CounterVal);
  4682. else {
  4683. if (NestedLoopCount != Pair.second.size() ||
  4684. NestedLoopCount != LoopMultipliers.size() + 1) {
  4685. // Erroneous case - clause has some problems.
  4686. Pair.first->setCounterValue(CounterVal);
  4687. continue;
  4688. }
  4689. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4690. auto I = Pair.second.rbegin();
  4691. auto IS = IterSpaces.rbegin();
  4692. auto ILM = LoopMultipliers.rbegin();
  4693. Expr *UpCounterVal = CounterVal;
  4694. Expr *Multiplier = nullptr;
  4695. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4696. if (I->first) {
  4697. assert(IS->CounterStep);
  4698. Expr *NormalizedOffset =
  4699. SemaRef
  4700. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4701. I->first, IS->CounterStep)
  4702. .get();
  4703. if (Multiplier) {
  4704. NormalizedOffset =
  4705. SemaRef
  4706. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4707. NormalizedOffset, Multiplier)
  4708. .get();
  4709. }
  4710. assert(I->second == OO_Plus || I->second == OO_Minus);
  4711. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4712. UpCounterVal = SemaRef
  4713. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4714. UpCounterVal, NormalizedOffset)
  4715. .get();
  4716. }
  4717. Multiplier = *ILM;
  4718. ++I;
  4719. ++IS;
  4720. ++ILM;
  4721. }
  4722. Pair.first->setCounterValue(UpCounterVal);
  4723. }
  4724. }
  4725. return NestedLoopCount;
  4726. }
  4727. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4728. auto CollapseClauses =
  4729. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4730. if (CollapseClauses.begin() != CollapseClauses.end())
  4731. return (*CollapseClauses.begin())->getNumForLoops();
  4732. return nullptr;
  4733. }
  4734. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4735. auto OrderedClauses =
  4736. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4737. if (OrderedClauses.begin() != OrderedClauses.end())
  4738. return (*OrderedClauses.begin())->getNumForLoops();
  4739. return nullptr;
  4740. }
  4741. static bool checkSimdlenSafelenSpecified(Sema &S,
  4742. const ArrayRef<OMPClause *> Clauses) {
  4743. OMPSafelenClause *Safelen = nullptr;
  4744. OMPSimdlenClause *Simdlen = nullptr;
  4745. for (auto *Clause : Clauses) {
  4746. if (Clause->getClauseKind() == OMPC_safelen)
  4747. Safelen = cast<OMPSafelenClause>(Clause);
  4748. else if (Clause->getClauseKind() == OMPC_simdlen)
  4749. Simdlen = cast<OMPSimdlenClause>(Clause);
  4750. if (Safelen && Simdlen)
  4751. break;
  4752. }
  4753. if (Simdlen && Safelen) {
  4754. llvm::APSInt SimdlenRes, SafelenRes;
  4755. auto SimdlenLength = Simdlen->getSimdlen();
  4756. auto SafelenLength = Safelen->getSafelen();
  4757. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4758. SimdlenLength->isInstantiationDependent() ||
  4759. SimdlenLength->containsUnexpandedParameterPack())
  4760. return false;
  4761. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4762. SafelenLength->isInstantiationDependent() ||
  4763. SafelenLength->containsUnexpandedParameterPack())
  4764. return false;
  4765. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4766. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4767. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4768. // If both simdlen and safelen clauses are specified, the value of the
  4769. // simdlen parameter must be less than or equal to the value of the safelen
  4770. // parameter.
  4771. if (SimdlenRes > SafelenRes) {
  4772. S.Diag(SimdlenLength->getExprLoc(),
  4773. diag::err_omp_wrong_simdlen_safelen_values)
  4774. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4775. return true;
  4776. }
  4777. }
  4778. return false;
  4779. }
  4780. StmtResult Sema::ActOnOpenMPSimdDirective(
  4781. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4782. SourceLocation EndLoc,
  4783. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4784. if (!AStmt)
  4785. return StmtError();
  4786. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4787. OMPLoopDirective::HelperExprs B;
  4788. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4789. // define the nested loops number.
  4790. unsigned NestedLoopCount = CheckOpenMPLoop(
  4791. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4792. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4793. if (NestedLoopCount == 0)
  4794. return StmtError();
  4795. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4796. "omp simd loop exprs were not built");
  4797. if (!CurContext->isDependentContext()) {
  4798. // Finalize the clauses that need pre-built expressions for CodeGen.
  4799. for (auto C : Clauses) {
  4800. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4801. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4802. B.NumIterations, *this, CurScope,
  4803. DSAStack))
  4804. return StmtError();
  4805. }
  4806. }
  4807. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4808. return StmtError();
  4809. getCurFunction()->setHasBranchProtectedScope();
  4810. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4811. Clauses, AStmt, B);
  4812. }
  4813. StmtResult Sema::ActOnOpenMPForDirective(
  4814. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4815. SourceLocation EndLoc,
  4816. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4817. if (!AStmt)
  4818. return StmtError();
  4819. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4820. OMPLoopDirective::HelperExprs B;
  4821. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4822. // define the nested loops number.
  4823. unsigned NestedLoopCount = CheckOpenMPLoop(
  4824. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4825. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4826. if (NestedLoopCount == 0)
  4827. return StmtError();
  4828. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4829. "omp for loop exprs were not built");
  4830. if (!CurContext->isDependentContext()) {
  4831. // Finalize the clauses that need pre-built expressions for CodeGen.
  4832. for (auto C : Clauses) {
  4833. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4834. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4835. B.NumIterations, *this, CurScope,
  4836. DSAStack))
  4837. return StmtError();
  4838. }
  4839. }
  4840. getCurFunction()->setHasBranchProtectedScope();
  4841. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4842. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4843. }
  4844. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4845. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4846. SourceLocation EndLoc,
  4847. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4848. if (!AStmt)
  4849. return StmtError();
  4850. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4851. OMPLoopDirective::HelperExprs B;
  4852. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4853. // define the nested loops number.
  4854. unsigned NestedLoopCount =
  4855. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4856. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4857. VarsWithImplicitDSA, B);
  4858. if (NestedLoopCount == 0)
  4859. return StmtError();
  4860. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4861. "omp for simd loop exprs were not built");
  4862. if (!CurContext->isDependentContext()) {
  4863. // Finalize the clauses that need pre-built expressions for CodeGen.
  4864. for (auto C : Clauses) {
  4865. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4866. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4867. B.NumIterations, *this, CurScope,
  4868. DSAStack))
  4869. return StmtError();
  4870. }
  4871. }
  4872. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4873. return StmtError();
  4874. getCurFunction()->setHasBranchProtectedScope();
  4875. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4876. Clauses, AStmt, B);
  4877. }
  4878. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4879. Stmt *AStmt,
  4880. SourceLocation StartLoc,
  4881. SourceLocation EndLoc) {
  4882. if (!AStmt)
  4883. return StmtError();
  4884. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4885. auto BaseStmt = AStmt;
  4886. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4887. BaseStmt = CS->getCapturedStmt();
  4888. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4889. auto S = C->children();
  4890. if (S.begin() == S.end())
  4891. return StmtError();
  4892. // All associated statements must be '#pragma omp section' except for
  4893. // the first one.
  4894. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4895. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4896. if (SectionStmt)
  4897. Diag(SectionStmt->getLocStart(),
  4898. diag::err_omp_sections_substmt_not_section);
  4899. return StmtError();
  4900. }
  4901. cast<OMPSectionDirective>(SectionStmt)
  4902. ->setHasCancel(DSAStack->isCancelRegion());
  4903. }
  4904. } else {
  4905. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4906. return StmtError();
  4907. }
  4908. getCurFunction()->setHasBranchProtectedScope();
  4909. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4910. DSAStack->isCancelRegion());
  4911. }
  4912. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4913. SourceLocation StartLoc,
  4914. SourceLocation EndLoc) {
  4915. if (!AStmt)
  4916. return StmtError();
  4917. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4918. getCurFunction()->setHasBranchProtectedScope();
  4919. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4920. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4921. DSAStack->isCancelRegion());
  4922. }
  4923. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4924. Stmt *AStmt,
  4925. SourceLocation StartLoc,
  4926. SourceLocation EndLoc) {
  4927. if (!AStmt)
  4928. return StmtError();
  4929. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4930. getCurFunction()->setHasBranchProtectedScope();
  4931. // OpenMP [2.7.3, single Construct, Restrictions]
  4932. // The copyprivate clause must not be used with the nowait clause.
  4933. OMPClause *Nowait = nullptr;
  4934. OMPClause *Copyprivate = nullptr;
  4935. for (auto *Clause : Clauses) {
  4936. if (Clause->getClauseKind() == OMPC_nowait)
  4937. Nowait = Clause;
  4938. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4939. Copyprivate = Clause;
  4940. if (Copyprivate && Nowait) {
  4941. Diag(Copyprivate->getLocStart(),
  4942. diag::err_omp_single_copyprivate_with_nowait);
  4943. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4944. return StmtError();
  4945. }
  4946. }
  4947. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4948. }
  4949. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4950. SourceLocation StartLoc,
  4951. SourceLocation EndLoc) {
  4952. if (!AStmt)
  4953. return StmtError();
  4954. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4955. getCurFunction()->setHasBranchProtectedScope();
  4956. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4957. }
  4958. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4959. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4960. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4961. if (!AStmt)
  4962. return StmtError();
  4963. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4964. bool ErrorFound = false;
  4965. llvm::APSInt Hint;
  4966. SourceLocation HintLoc;
  4967. bool DependentHint = false;
  4968. for (auto *C : Clauses) {
  4969. if (C->getClauseKind() == OMPC_hint) {
  4970. if (!DirName.getName()) {
  4971. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4972. ErrorFound = true;
  4973. }
  4974. Expr *E = cast<OMPHintClause>(C)->getHint();
  4975. if (E->isTypeDependent() || E->isValueDependent() ||
  4976. E->isInstantiationDependent())
  4977. DependentHint = true;
  4978. else {
  4979. Hint = E->EvaluateKnownConstInt(Context);
  4980. HintLoc = C->getLocStart();
  4981. }
  4982. }
  4983. }
  4984. if (ErrorFound)
  4985. return StmtError();
  4986. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4987. if (Pair.first && DirName.getName() && !DependentHint) {
  4988. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4989. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4990. if (HintLoc.isValid()) {
  4991. Diag(HintLoc, diag::note_omp_critical_hint_here)
  4992. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  4993. } else
  4994. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  4995. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  4996. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  4997. << 1
  4998. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  4999. /*Radix=*/10, /*Signed=*/false);
  5000. } else
  5001. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  5002. }
  5003. }
  5004. getCurFunction()->setHasBranchProtectedScope();
  5005. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5006. Clauses, AStmt);
  5007. if (!Pair.first && DirName.getName() && !DependentHint)
  5008. DSAStack->addCriticalWithHint(Dir, Hint);
  5009. return Dir;
  5010. }
  5011. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5012. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5013. SourceLocation EndLoc,
  5014. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5015. if (!AStmt)
  5016. return StmtError();
  5017. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5018. // 1.2.2 OpenMP Language Terminology
  5019. // Structured block - An executable statement with a single entry at the
  5020. // top and a single exit at the bottom.
  5021. // The point of exit cannot be a branch out of the structured block.
  5022. // longjmp() and throw() must not violate the entry/exit criteria.
  5023. CS->getCapturedDecl()->setNothrow();
  5024. OMPLoopDirective::HelperExprs B;
  5025. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5026. // define the nested loops number.
  5027. unsigned NestedLoopCount =
  5028. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5029. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5030. VarsWithImplicitDSA, B);
  5031. if (NestedLoopCount == 0)
  5032. return StmtError();
  5033. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5034. "omp parallel for loop exprs were not built");
  5035. if (!CurContext->isDependentContext()) {
  5036. // Finalize the clauses that need pre-built expressions for CodeGen.
  5037. for (auto C : Clauses) {
  5038. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5039. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5040. B.NumIterations, *this, CurScope,
  5041. DSAStack))
  5042. return StmtError();
  5043. }
  5044. }
  5045. getCurFunction()->setHasBranchProtectedScope();
  5046. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5047. NestedLoopCount, Clauses, AStmt, B,
  5048. DSAStack->isCancelRegion());
  5049. }
  5050. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5051. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5052. SourceLocation EndLoc,
  5053. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5054. if (!AStmt)
  5055. return StmtError();
  5056. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5057. // 1.2.2 OpenMP Language Terminology
  5058. // Structured block - An executable statement with a single entry at the
  5059. // top and a single exit at the bottom.
  5060. // The point of exit cannot be a branch out of the structured block.
  5061. // longjmp() and throw() must not violate the entry/exit criteria.
  5062. CS->getCapturedDecl()->setNothrow();
  5063. OMPLoopDirective::HelperExprs B;
  5064. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5065. // define the nested loops number.
  5066. unsigned NestedLoopCount =
  5067. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5068. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5069. VarsWithImplicitDSA, B);
  5070. if (NestedLoopCount == 0)
  5071. return StmtError();
  5072. if (!CurContext->isDependentContext()) {
  5073. // Finalize the clauses that need pre-built expressions for CodeGen.
  5074. for (auto C : Clauses) {
  5075. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5076. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5077. B.NumIterations, *this, CurScope,
  5078. DSAStack))
  5079. return StmtError();
  5080. }
  5081. }
  5082. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5083. return StmtError();
  5084. getCurFunction()->setHasBranchProtectedScope();
  5085. return OMPParallelForSimdDirective::Create(
  5086. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5087. }
  5088. StmtResult
  5089. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5090. Stmt *AStmt, SourceLocation StartLoc,
  5091. SourceLocation EndLoc) {
  5092. if (!AStmt)
  5093. return StmtError();
  5094. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5095. auto BaseStmt = AStmt;
  5096. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5097. BaseStmt = CS->getCapturedStmt();
  5098. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5099. auto S = C->children();
  5100. if (S.begin() == S.end())
  5101. return StmtError();
  5102. // All associated statements must be '#pragma omp section' except for
  5103. // the first one.
  5104. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5105. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5106. if (SectionStmt)
  5107. Diag(SectionStmt->getLocStart(),
  5108. diag::err_omp_parallel_sections_substmt_not_section);
  5109. return StmtError();
  5110. }
  5111. cast<OMPSectionDirective>(SectionStmt)
  5112. ->setHasCancel(DSAStack->isCancelRegion());
  5113. }
  5114. } else {
  5115. Diag(AStmt->getLocStart(),
  5116. diag::err_omp_parallel_sections_not_compound_stmt);
  5117. return StmtError();
  5118. }
  5119. getCurFunction()->setHasBranchProtectedScope();
  5120. return OMPParallelSectionsDirective::Create(
  5121. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5122. }
  5123. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5124. Stmt *AStmt, SourceLocation StartLoc,
  5125. SourceLocation EndLoc) {
  5126. if (!AStmt)
  5127. return StmtError();
  5128. auto *CS = cast<CapturedStmt>(AStmt);
  5129. // 1.2.2 OpenMP Language Terminology
  5130. // Structured block - An executable statement with a single entry at the
  5131. // top and a single exit at the bottom.
  5132. // The point of exit cannot be a branch out of the structured block.
  5133. // longjmp() and throw() must not violate the entry/exit criteria.
  5134. CS->getCapturedDecl()->setNothrow();
  5135. getCurFunction()->setHasBranchProtectedScope();
  5136. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5137. DSAStack->isCancelRegion());
  5138. }
  5139. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5140. SourceLocation EndLoc) {
  5141. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5142. }
  5143. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5144. SourceLocation EndLoc) {
  5145. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5146. }
  5147. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5148. SourceLocation EndLoc) {
  5149. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5150. }
  5151. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5152. Stmt *AStmt,
  5153. SourceLocation StartLoc,
  5154. SourceLocation EndLoc) {
  5155. if (!AStmt)
  5156. return StmtError();
  5157. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5158. getCurFunction()->setHasBranchProtectedScope();
  5159. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5160. AStmt,
  5161. DSAStack->getTaskgroupReductionRef());
  5162. }
  5163. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5164. SourceLocation StartLoc,
  5165. SourceLocation EndLoc) {
  5166. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5167. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5168. }
  5169. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5170. Stmt *AStmt,
  5171. SourceLocation StartLoc,
  5172. SourceLocation EndLoc) {
  5173. OMPClause *DependFound = nullptr;
  5174. OMPClause *DependSourceClause = nullptr;
  5175. OMPClause *DependSinkClause = nullptr;
  5176. bool ErrorFound = false;
  5177. OMPThreadsClause *TC = nullptr;
  5178. OMPSIMDClause *SC = nullptr;
  5179. for (auto *C : Clauses) {
  5180. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5181. DependFound = C;
  5182. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5183. if (DependSourceClause) {
  5184. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5185. << getOpenMPDirectiveName(OMPD_ordered)
  5186. << getOpenMPClauseName(OMPC_depend) << 2;
  5187. ErrorFound = true;
  5188. } else
  5189. DependSourceClause = C;
  5190. if (DependSinkClause) {
  5191. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5192. << 0;
  5193. ErrorFound = true;
  5194. }
  5195. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5196. if (DependSourceClause) {
  5197. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5198. << 1;
  5199. ErrorFound = true;
  5200. }
  5201. DependSinkClause = C;
  5202. }
  5203. } else if (C->getClauseKind() == OMPC_threads)
  5204. TC = cast<OMPThreadsClause>(C);
  5205. else if (C->getClauseKind() == OMPC_simd)
  5206. SC = cast<OMPSIMDClause>(C);
  5207. }
  5208. if (!ErrorFound && !SC &&
  5209. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5210. // OpenMP [2.8.1,simd Construct, Restrictions]
  5211. // An ordered construct with the simd clause is the only OpenMP construct
  5212. // that can appear in the simd region.
  5213. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5214. ErrorFound = true;
  5215. } else if (DependFound && (TC || SC)) {
  5216. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5217. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5218. ErrorFound = true;
  5219. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5220. Diag(DependFound->getLocStart(),
  5221. diag::err_omp_ordered_directive_without_param);
  5222. ErrorFound = true;
  5223. } else if (TC || Clauses.empty()) {
  5224. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  5225. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5226. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5227. << (TC != nullptr);
  5228. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5229. ErrorFound = true;
  5230. }
  5231. }
  5232. if ((!AStmt && !DependFound) || ErrorFound)
  5233. return StmtError();
  5234. if (AStmt) {
  5235. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5236. getCurFunction()->setHasBranchProtectedScope();
  5237. }
  5238. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5239. }
  5240. namespace {
  5241. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5242. /// construct.
  5243. class OpenMPAtomicUpdateChecker {
  5244. /// \brief Error results for atomic update expressions.
  5245. enum ExprAnalysisErrorCode {
  5246. /// \brief A statement is not an expression statement.
  5247. NotAnExpression,
  5248. /// \brief Expression is not builtin binary or unary operation.
  5249. NotABinaryOrUnaryExpression,
  5250. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5251. NotAnUnaryIncDecExpression,
  5252. /// \brief An expression is not of scalar type.
  5253. NotAScalarType,
  5254. /// \brief A binary operation is not an assignment operation.
  5255. NotAnAssignmentOp,
  5256. /// \brief RHS part of the binary operation is not a binary expression.
  5257. NotABinaryExpression,
  5258. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5259. /// expression.
  5260. NotABinaryOperator,
  5261. /// \brief RHS binary operation does not have reference to the updated LHS
  5262. /// part.
  5263. NotAnUpdateExpression,
  5264. /// \brief No errors is found.
  5265. NoError
  5266. };
  5267. /// \brief Reference to Sema.
  5268. Sema &SemaRef;
  5269. /// \brief A location for note diagnostics (when error is found).
  5270. SourceLocation NoteLoc;
  5271. /// \brief 'x' lvalue part of the source atomic expression.
  5272. Expr *X;
  5273. /// \brief 'expr' rvalue part of the source atomic expression.
  5274. Expr *E;
  5275. /// \brief Helper expression of the form
  5276. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5277. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5278. Expr *UpdateExpr;
  5279. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5280. /// important for non-associative operations.
  5281. bool IsXLHSInRHSPart;
  5282. BinaryOperatorKind Op;
  5283. SourceLocation OpLoc;
  5284. /// \brief true if the source expression is a postfix unary operation, false
  5285. /// if it is a prefix unary operation.
  5286. bool IsPostfixUpdate;
  5287. public:
  5288. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5289. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5290. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5291. /// \brief Check specified statement that it is suitable for 'atomic update'
  5292. /// constructs and extract 'x', 'expr' and Operation from the original
  5293. /// expression. If DiagId and NoteId == 0, then only check is performed
  5294. /// without error notification.
  5295. /// \param DiagId Diagnostic which should be emitted if error is found.
  5296. /// \param NoteId Diagnostic note for the main error message.
  5297. /// \return true if statement is not an update expression, false otherwise.
  5298. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5299. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5300. Expr *getX() const { return X; }
  5301. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5302. Expr *getExpr() const { return E; }
  5303. /// \brief Return the update expression used in calculation of the updated
  5304. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5305. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5306. Expr *getUpdateExpr() const { return UpdateExpr; }
  5307. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5308. /// false otherwise.
  5309. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5310. /// \brief true if the source expression is a postfix unary operation, false
  5311. /// if it is a prefix unary operation.
  5312. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5313. private:
  5314. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5315. unsigned NoteId = 0);
  5316. };
  5317. } // namespace
  5318. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5319. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5320. ExprAnalysisErrorCode ErrorFound = NoError;
  5321. SourceLocation ErrorLoc, NoteLoc;
  5322. SourceRange ErrorRange, NoteRange;
  5323. // Allowed constructs are:
  5324. // x = x binop expr;
  5325. // x = expr binop x;
  5326. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5327. X = AtomicBinOp->getLHS();
  5328. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5329. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5330. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5331. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5332. AtomicInnerBinOp->isBitwiseOp()) {
  5333. Op = AtomicInnerBinOp->getOpcode();
  5334. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5335. auto *LHS = AtomicInnerBinOp->getLHS();
  5336. auto *RHS = AtomicInnerBinOp->getRHS();
  5337. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5338. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5339. /*Canonical=*/true);
  5340. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5341. /*Canonical=*/true);
  5342. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5343. /*Canonical=*/true);
  5344. if (XId == LHSId) {
  5345. E = RHS;
  5346. IsXLHSInRHSPart = true;
  5347. } else if (XId == RHSId) {
  5348. E = LHS;
  5349. IsXLHSInRHSPart = false;
  5350. } else {
  5351. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5352. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5353. NoteLoc = X->getExprLoc();
  5354. NoteRange = X->getSourceRange();
  5355. ErrorFound = NotAnUpdateExpression;
  5356. }
  5357. } else {
  5358. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5359. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5360. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5361. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5362. ErrorFound = NotABinaryOperator;
  5363. }
  5364. } else {
  5365. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5366. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5367. ErrorFound = NotABinaryExpression;
  5368. }
  5369. } else {
  5370. ErrorLoc = AtomicBinOp->getExprLoc();
  5371. ErrorRange = AtomicBinOp->getSourceRange();
  5372. NoteLoc = AtomicBinOp->getOperatorLoc();
  5373. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5374. ErrorFound = NotAnAssignmentOp;
  5375. }
  5376. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5377. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5378. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5379. return true;
  5380. } else if (SemaRef.CurContext->isDependentContext())
  5381. E = X = UpdateExpr = nullptr;
  5382. return ErrorFound != NoError;
  5383. }
  5384. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5385. unsigned NoteId) {
  5386. ExprAnalysisErrorCode ErrorFound = NoError;
  5387. SourceLocation ErrorLoc, NoteLoc;
  5388. SourceRange ErrorRange, NoteRange;
  5389. // Allowed constructs are:
  5390. // x++;
  5391. // x--;
  5392. // ++x;
  5393. // --x;
  5394. // x binop= expr;
  5395. // x = x binop expr;
  5396. // x = expr binop x;
  5397. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5398. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5399. if (AtomicBody->getType()->isScalarType() ||
  5400. AtomicBody->isInstantiationDependent()) {
  5401. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5402. AtomicBody->IgnoreParenImpCasts())) {
  5403. // Check for Compound Assignment Operation
  5404. Op = BinaryOperator::getOpForCompoundAssignment(
  5405. AtomicCompAssignOp->getOpcode());
  5406. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5407. E = AtomicCompAssignOp->getRHS();
  5408. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5409. IsXLHSInRHSPart = true;
  5410. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5411. AtomicBody->IgnoreParenImpCasts())) {
  5412. // Check for Binary Operation
  5413. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5414. return true;
  5415. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5416. AtomicBody->IgnoreParenImpCasts())) {
  5417. // Check for Unary Operation
  5418. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5419. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5420. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5421. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5422. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5423. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5424. IsXLHSInRHSPart = true;
  5425. } else {
  5426. ErrorFound = NotAnUnaryIncDecExpression;
  5427. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5428. ErrorRange = AtomicUnaryOp->getSourceRange();
  5429. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5430. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5431. }
  5432. } else if (!AtomicBody->isInstantiationDependent()) {
  5433. ErrorFound = NotABinaryOrUnaryExpression;
  5434. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5435. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5436. }
  5437. } else {
  5438. ErrorFound = NotAScalarType;
  5439. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5440. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5441. }
  5442. } else {
  5443. ErrorFound = NotAnExpression;
  5444. NoteLoc = ErrorLoc = S->getLocStart();
  5445. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5446. }
  5447. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5448. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5449. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5450. return true;
  5451. } else if (SemaRef.CurContext->isDependentContext())
  5452. E = X = UpdateExpr = nullptr;
  5453. if (ErrorFound == NoError && E && X) {
  5454. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5455. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5456. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5457. auto *OVEX = new (SemaRef.getASTContext())
  5458. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5459. auto *OVEExpr = new (SemaRef.getASTContext())
  5460. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5461. auto Update =
  5462. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5463. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5464. if (Update.isInvalid())
  5465. return true;
  5466. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5467. Sema::AA_Casting);
  5468. if (Update.isInvalid())
  5469. return true;
  5470. UpdateExpr = Update.get();
  5471. }
  5472. return ErrorFound != NoError;
  5473. }
  5474. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5475. Stmt *AStmt,
  5476. SourceLocation StartLoc,
  5477. SourceLocation EndLoc) {
  5478. if (!AStmt)
  5479. return StmtError();
  5480. auto *CS = cast<CapturedStmt>(AStmt);
  5481. // 1.2.2 OpenMP Language Terminology
  5482. // Structured block - An executable statement with a single entry at the
  5483. // top and a single exit at the bottom.
  5484. // The point of exit cannot be a branch out of the structured block.
  5485. // longjmp() and throw() must not violate the entry/exit criteria.
  5486. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5487. SourceLocation AtomicKindLoc;
  5488. for (auto *C : Clauses) {
  5489. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5490. C->getClauseKind() == OMPC_update ||
  5491. C->getClauseKind() == OMPC_capture) {
  5492. if (AtomicKind != OMPC_unknown) {
  5493. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5494. << SourceRange(C->getLocStart(), C->getLocEnd());
  5495. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5496. << getOpenMPClauseName(AtomicKind);
  5497. } else {
  5498. AtomicKind = C->getClauseKind();
  5499. AtomicKindLoc = C->getLocStart();
  5500. }
  5501. }
  5502. }
  5503. auto Body = CS->getCapturedStmt();
  5504. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5505. Body = EWC->getSubExpr();
  5506. Expr *X = nullptr;
  5507. Expr *V = nullptr;
  5508. Expr *E = nullptr;
  5509. Expr *UE = nullptr;
  5510. bool IsXLHSInRHSPart = false;
  5511. bool IsPostfixUpdate = false;
  5512. // OpenMP [2.12.6, atomic Construct]
  5513. // In the next expressions:
  5514. // * x and v (as applicable) are both l-value expressions with scalar type.
  5515. // * During the execution of an atomic region, multiple syntactic
  5516. // occurrences of x must designate the same storage location.
  5517. // * Neither of v and expr (as applicable) may access the storage location
  5518. // designated by x.
  5519. // * Neither of x and expr (as applicable) may access the storage location
  5520. // designated by v.
  5521. // * expr is an expression with scalar type.
  5522. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5523. // * binop, binop=, ++, and -- are not overloaded operators.
  5524. // * The expression x binop expr must be numerically equivalent to x binop
  5525. // (expr). This requirement is satisfied if the operators in expr have
  5526. // precedence greater than binop, or by using parentheses around expr or
  5527. // subexpressions of expr.
  5528. // * The expression expr binop x must be numerically equivalent to (expr)
  5529. // binop x. This requirement is satisfied if the operators in expr have
  5530. // precedence equal to or greater than binop, or by using parentheses around
  5531. // expr or subexpressions of expr.
  5532. // * For forms that allow multiple occurrences of x, the number of times
  5533. // that x is evaluated is unspecified.
  5534. if (AtomicKind == OMPC_read) {
  5535. enum {
  5536. NotAnExpression,
  5537. NotAnAssignmentOp,
  5538. NotAScalarType,
  5539. NotAnLValue,
  5540. NoError
  5541. } ErrorFound = NoError;
  5542. SourceLocation ErrorLoc, NoteLoc;
  5543. SourceRange ErrorRange, NoteRange;
  5544. // If clause is read:
  5545. // v = x;
  5546. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5547. auto *AtomicBinOp =
  5548. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5549. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5550. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5551. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5552. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5553. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5554. if (!X->isLValue() || !V->isLValue()) {
  5555. auto NotLValueExpr = X->isLValue() ? V : X;
  5556. ErrorFound = NotAnLValue;
  5557. ErrorLoc = AtomicBinOp->getExprLoc();
  5558. ErrorRange = AtomicBinOp->getSourceRange();
  5559. NoteLoc = NotLValueExpr->getExprLoc();
  5560. NoteRange = NotLValueExpr->getSourceRange();
  5561. }
  5562. } else if (!X->isInstantiationDependent() ||
  5563. !V->isInstantiationDependent()) {
  5564. auto NotScalarExpr =
  5565. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5566. ? V
  5567. : X;
  5568. ErrorFound = NotAScalarType;
  5569. ErrorLoc = AtomicBinOp->getExprLoc();
  5570. ErrorRange = AtomicBinOp->getSourceRange();
  5571. NoteLoc = NotScalarExpr->getExprLoc();
  5572. NoteRange = NotScalarExpr->getSourceRange();
  5573. }
  5574. } else if (!AtomicBody->isInstantiationDependent()) {
  5575. ErrorFound = NotAnAssignmentOp;
  5576. ErrorLoc = AtomicBody->getExprLoc();
  5577. ErrorRange = AtomicBody->getSourceRange();
  5578. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5579. : AtomicBody->getExprLoc();
  5580. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5581. : AtomicBody->getSourceRange();
  5582. }
  5583. } else {
  5584. ErrorFound = NotAnExpression;
  5585. NoteLoc = ErrorLoc = Body->getLocStart();
  5586. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5587. }
  5588. if (ErrorFound != NoError) {
  5589. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5590. << ErrorRange;
  5591. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5592. << NoteRange;
  5593. return StmtError();
  5594. } else if (CurContext->isDependentContext())
  5595. V = X = nullptr;
  5596. } else if (AtomicKind == OMPC_write) {
  5597. enum {
  5598. NotAnExpression,
  5599. NotAnAssignmentOp,
  5600. NotAScalarType,
  5601. NotAnLValue,
  5602. NoError
  5603. } ErrorFound = NoError;
  5604. SourceLocation ErrorLoc, NoteLoc;
  5605. SourceRange ErrorRange, NoteRange;
  5606. // If clause is write:
  5607. // x = expr;
  5608. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5609. auto *AtomicBinOp =
  5610. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5611. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5612. X = AtomicBinOp->getLHS();
  5613. E = AtomicBinOp->getRHS();
  5614. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5615. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5616. if (!X->isLValue()) {
  5617. ErrorFound = NotAnLValue;
  5618. ErrorLoc = AtomicBinOp->getExprLoc();
  5619. ErrorRange = AtomicBinOp->getSourceRange();
  5620. NoteLoc = X->getExprLoc();
  5621. NoteRange = X->getSourceRange();
  5622. }
  5623. } else if (!X->isInstantiationDependent() ||
  5624. !E->isInstantiationDependent()) {
  5625. auto NotScalarExpr =
  5626. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5627. ? E
  5628. : X;
  5629. ErrorFound = NotAScalarType;
  5630. ErrorLoc = AtomicBinOp->getExprLoc();
  5631. ErrorRange = AtomicBinOp->getSourceRange();
  5632. NoteLoc = NotScalarExpr->getExprLoc();
  5633. NoteRange = NotScalarExpr->getSourceRange();
  5634. }
  5635. } else if (!AtomicBody->isInstantiationDependent()) {
  5636. ErrorFound = NotAnAssignmentOp;
  5637. ErrorLoc = AtomicBody->getExprLoc();
  5638. ErrorRange = AtomicBody->getSourceRange();
  5639. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5640. : AtomicBody->getExprLoc();
  5641. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5642. : AtomicBody->getSourceRange();
  5643. }
  5644. } else {
  5645. ErrorFound = NotAnExpression;
  5646. NoteLoc = ErrorLoc = Body->getLocStart();
  5647. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5648. }
  5649. if (ErrorFound != NoError) {
  5650. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5651. << ErrorRange;
  5652. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5653. << NoteRange;
  5654. return StmtError();
  5655. } else if (CurContext->isDependentContext())
  5656. E = X = nullptr;
  5657. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5658. // If clause is update:
  5659. // x++;
  5660. // x--;
  5661. // ++x;
  5662. // --x;
  5663. // x binop= expr;
  5664. // x = x binop expr;
  5665. // x = expr binop x;
  5666. OpenMPAtomicUpdateChecker Checker(*this);
  5667. if (Checker.checkStatement(
  5668. Body, (AtomicKind == OMPC_update)
  5669. ? diag::err_omp_atomic_update_not_expression_statement
  5670. : diag::err_omp_atomic_not_expression_statement,
  5671. diag::note_omp_atomic_update))
  5672. return StmtError();
  5673. if (!CurContext->isDependentContext()) {
  5674. E = Checker.getExpr();
  5675. X = Checker.getX();
  5676. UE = Checker.getUpdateExpr();
  5677. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5678. }
  5679. } else if (AtomicKind == OMPC_capture) {
  5680. enum {
  5681. NotAnAssignmentOp,
  5682. NotACompoundStatement,
  5683. NotTwoSubstatements,
  5684. NotASpecificExpression,
  5685. NoError
  5686. } ErrorFound = NoError;
  5687. SourceLocation ErrorLoc, NoteLoc;
  5688. SourceRange ErrorRange, NoteRange;
  5689. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5690. // If clause is a capture:
  5691. // v = x++;
  5692. // v = x--;
  5693. // v = ++x;
  5694. // v = --x;
  5695. // v = x binop= expr;
  5696. // v = x = x binop expr;
  5697. // v = x = expr binop x;
  5698. auto *AtomicBinOp =
  5699. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5700. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5701. V = AtomicBinOp->getLHS();
  5702. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5703. OpenMPAtomicUpdateChecker Checker(*this);
  5704. if (Checker.checkStatement(
  5705. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5706. diag::note_omp_atomic_update))
  5707. return StmtError();
  5708. E = Checker.getExpr();
  5709. X = Checker.getX();
  5710. UE = Checker.getUpdateExpr();
  5711. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5712. IsPostfixUpdate = Checker.isPostfixUpdate();
  5713. } else if (!AtomicBody->isInstantiationDependent()) {
  5714. ErrorLoc = AtomicBody->getExprLoc();
  5715. ErrorRange = AtomicBody->getSourceRange();
  5716. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5717. : AtomicBody->getExprLoc();
  5718. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5719. : AtomicBody->getSourceRange();
  5720. ErrorFound = NotAnAssignmentOp;
  5721. }
  5722. if (ErrorFound != NoError) {
  5723. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5724. << ErrorRange;
  5725. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5726. return StmtError();
  5727. } else if (CurContext->isDependentContext()) {
  5728. UE = V = E = X = nullptr;
  5729. }
  5730. } else {
  5731. // If clause is a capture:
  5732. // { v = x; x = expr; }
  5733. // { v = x; x++; }
  5734. // { v = x; x--; }
  5735. // { v = x; ++x; }
  5736. // { v = x; --x; }
  5737. // { v = x; x binop= expr; }
  5738. // { v = x; x = x binop expr; }
  5739. // { v = x; x = expr binop x; }
  5740. // { x++; v = x; }
  5741. // { x--; v = x; }
  5742. // { ++x; v = x; }
  5743. // { --x; v = x; }
  5744. // { x binop= expr; v = x; }
  5745. // { x = x binop expr; v = x; }
  5746. // { x = expr binop x; v = x; }
  5747. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5748. // Check that this is { expr1; expr2; }
  5749. if (CS->size() == 2) {
  5750. auto *First = CS->body_front();
  5751. auto *Second = CS->body_back();
  5752. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5753. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5754. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5755. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5756. // Need to find what subexpression is 'v' and what is 'x'.
  5757. OpenMPAtomicUpdateChecker Checker(*this);
  5758. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5759. BinaryOperator *BinOp = nullptr;
  5760. if (IsUpdateExprFound) {
  5761. BinOp = dyn_cast<BinaryOperator>(First);
  5762. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5763. }
  5764. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5765. // { v = x; x++; }
  5766. // { v = x; x--; }
  5767. // { v = x; ++x; }
  5768. // { v = x; --x; }
  5769. // { v = x; x binop= expr; }
  5770. // { v = x; x = x binop expr; }
  5771. // { v = x; x = expr binop x; }
  5772. // Check that the first expression has form v = x.
  5773. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5774. llvm::FoldingSetNodeID XId, PossibleXId;
  5775. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5776. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5777. IsUpdateExprFound = XId == PossibleXId;
  5778. if (IsUpdateExprFound) {
  5779. V = BinOp->getLHS();
  5780. X = Checker.getX();
  5781. E = Checker.getExpr();
  5782. UE = Checker.getUpdateExpr();
  5783. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5784. IsPostfixUpdate = true;
  5785. }
  5786. }
  5787. if (!IsUpdateExprFound) {
  5788. IsUpdateExprFound = !Checker.checkStatement(First);
  5789. BinOp = nullptr;
  5790. if (IsUpdateExprFound) {
  5791. BinOp = dyn_cast<BinaryOperator>(Second);
  5792. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5793. }
  5794. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5795. // { x++; v = x; }
  5796. // { x--; v = x; }
  5797. // { ++x; v = x; }
  5798. // { --x; v = x; }
  5799. // { x binop= expr; v = x; }
  5800. // { x = x binop expr; v = x; }
  5801. // { x = expr binop x; v = x; }
  5802. // Check that the second expression has form v = x.
  5803. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5804. llvm::FoldingSetNodeID XId, PossibleXId;
  5805. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5806. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5807. IsUpdateExprFound = XId == PossibleXId;
  5808. if (IsUpdateExprFound) {
  5809. V = BinOp->getLHS();
  5810. X = Checker.getX();
  5811. E = Checker.getExpr();
  5812. UE = Checker.getUpdateExpr();
  5813. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5814. IsPostfixUpdate = false;
  5815. }
  5816. }
  5817. }
  5818. if (!IsUpdateExprFound) {
  5819. // { v = x; x = expr; }
  5820. auto *FirstExpr = dyn_cast<Expr>(First);
  5821. auto *SecondExpr = dyn_cast<Expr>(Second);
  5822. if (!FirstExpr || !SecondExpr ||
  5823. !(FirstExpr->isInstantiationDependent() ||
  5824. SecondExpr->isInstantiationDependent())) {
  5825. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5826. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5827. ErrorFound = NotAnAssignmentOp;
  5828. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5829. : First->getLocStart();
  5830. NoteRange = ErrorRange = FirstBinOp
  5831. ? FirstBinOp->getSourceRange()
  5832. : SourceRange(ErrorLoc, ErrorLoc);
  5833. } else {
  5834. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5835. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5836. ErrorFound = NotAnAssignmentOp;
  5837. NoteLoc = ErrorLoc = SecondBinOp
  5838. ? SecondBinOp->getOperatorLoc()
  5839. : Second->getLocStart();
  5840. NoteRange = ErrorRange =
  5841. SecondBinOp ? SecondBinOp->getSourceRange()
  5842. : SourceRange(ErrorLoc, ErrorLoc);
  5843. } else {
  5844. auto *PossibleXRHSInFirst =
  5845. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5846. auto *PossibleXLHSInSecond =
  5847. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5848. llvm::FoldingSetNodeID X1Id, X2Id;
  5849. PossibleXRHSInFirst->Profile(X1Id, Context,
  5850. /*Canonical=*/true);
  5851. PossibleXLHSInSecond->Profile(X2Id, Context,
  5852. /*Canonical=*/true);
  5853. IsUpdateExprFound = X1Id == X2Id;
  5854. if (IsUpdateExprFound) {
  5855. V = FirstBinOp->getLHS();
  5856. X = SecondBinOp->getLHS();
  5857. E = SecondBinOp->getRHS();
  5858. UE = nullptr;
  5859. IsXLHSInRHSPart = false;
  5860. IsPostfixUpdate = true;
  5861. } else {
  5862. ErrorFound = NotASpecificExpression;
  5863. ErrorLoc = FirstBinOp->getExprLoc();
  5864. ErrorRange = FirstBinOp->getSourceRange();
  5865. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5866. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5867. }
  5868. }
  5869. }
  5870. }
  5871. }
  5872. } else {
  5873. NoteLoc = ErrorLoc = Body->getLocStart();
  5874. NoteRange = ErrorRange =
  5875. SourceRange(Body->getLocStart(), Body->getLocStart());
  5876. ErrorFound = NotTwoSubstatements;
  5877. }
  5878. } else {
  5879. NoteLoc = ErrorLoc = Body->getLocStart();
  5880. NoteRange = ErrorRange =
  5881. SourceRange(Body->getLocStart(), Body->getLocStart());
  5882. ErrorFound = NotACompoundStatement;
  5883. }
  5884. if (ErrorFound != NoError) {
  5885. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5886. << ErrorRange;
  5887. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5888. return StmtError();
  5889. } else if (CurContext->isDependentContext()) {
  5890. UE = V = E = X = nullptr;
  5891. }
  5892. }
  5893. }
  5894. getCurFunction()->setHasBranchProtectedScope();
  5895. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5896. X, V, E, UE, IsXLHSInRHSPart,
  5897. IsPostfixUpdate);
  5898. }
  5899. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5900. Stmt *AStmt,
  5901. SourceLocation StartLoc,
  5902. SourceLocation EndLoc) {
  5903. if (!AStmt)
  5904. return StmtError();
  5905. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5906. // 1.2.2 OpenMP Language Terminology
  5907. // Structured block - An executable statement with a single entry at the
  5908. // top and a single exit at the bottom.
  5909. // The point of exit cannot be a branch out of the structured block.
  5910. // longjmp() and throw() must not violate the entry/exit criteria.
  5911. CS->getCapturedDecl()->setNothrow();
  5912. // OpenMP [2.16, Nesting of Regions]
  5913. // If specified, a teams construct must be contained within a target
  5914. // construct. That target construct must contain no statements or directives
  5915. // outside of the teams construct.
  5916. if (DSAStack->hasInnerTeamsRegion()) {
  5917. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5918. bool OMPTeamsFound = true;
  5919. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5920. auto I = CS->body_begin();
  5921. while (I != CS->body_end()) {
  5922. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5923. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5924. OMPTeamsFound = false;
  5925. break;
  5926. }
  5927. ++I;
  5928. }
  5929. assert(I != CS->body_end() && "Not found statement");
  5930. S = *I;
  5931. } else {
  5932. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5933. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5934. }
  5935. if (!OMPTeamsFound) {
  5936. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5937. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5938. diag::note_omp_nested_teams_construct_here);
  5939. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5940. << isa<OMPExecutableDirective>(S);
  5941. return StmtError();
  5942. }
  5943. }
  5944. getCurFunction()->setHasBranchProtectedScope();
  5945. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5946. }
  5947. StmtResult
  5948. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5949. Stmt *AStmt, SourceLocation StartLoc,
  5950. SourceLocation EndLoc) {
  5951. if (!AStmt)
  5952. return StmtError();
  5953. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5954. // 1.2.2 OpenMP Language Terminology
  5955. // Structured block - An executable statement with a single entry at the
  5956. // top and a single exit at the bottom.
  5957. // The point of exit cannot be a branch out of the structured block.
  5958. // longjmp() and throw() must not violate the entry/exit criteria.
  5959. CS->getCapturedDecl()->setNothrow();
  5960. getCurFunction()->setHasBranchProtectedScope();
  5961. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5962. AStmt);
  5963. }
  5964. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5965. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5966. SourceLocation EndLoc,
  5967. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5968. if (!AStmt)
  5969. return StmtError();
  5970. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5971. // 1.2.2 OpenMP Language Terminology
  5972. // Structured block - An executable statement with a single entry at the
  5973. // top and a single exit at the bottom.
  5974. // The point of exit cannot be a branch out of the structured block.
  5975. // longjmp() and throw() must not violate the entry/exit criteria.
  5976. CS->getCapturedDecl()->setNothrow();
  5977. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  5978. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  5979. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5980. // 1.2.2 OpenMP Language Terminology
  5981. // Structured block - An executable statement with a single entry at the
  5982. // top and a single exit at the bottom.
  5983. // The point of exit cannot be a branch out of the structured block.
  5984. // longjmp() and throw() must not violate the entry/exit criteria.
  5985. CS->getCapturedDecl()->setNothrow();
  5986. }
  5987. OMPLoopDirective::HelperExprs B;
  5988. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5989. // define the nested loops number.
  5990. unsigned NestedLoopCount =
  5991. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  5992. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  5993. VarsWithImplicitDSA, B);
  5994. if (NestedLoopCount == 0)
  5995. return StmtError();
  5996. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5997. "omp target parallel for loop exprs were not built");
  5998. if (!CurContext->isDependentContext()) {
  5999. // Finalize the clauses that need pre-built expressions for CodeGen.
  6000. for (auto C : Clauses) {
  6001. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6002. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6003. B.NumIterations, *this, CurScope,
  6004. DSAStack))
  6005. return StmtError();
  6006. }
  6007. }
  6008. getCurFunction()->setHasBranchProtectedScope();
  6009. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6010. NestedLoopCount, Clauses, AStmt,
  6011. B, DSAStack->isCancelRegion());
  6012. }
  6013. /// Check for existence of a map clause in the list of clauses.
  6014. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6015. const OpenMPClauseKind K) {
  6016. return llvm::any_of(
  6017. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6018. }
  6019. template <typename... Params>
  6020. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6021. const Params... ClauseTypes) {
  6022. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6023. }
  6024. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6025. Stmt *AStmt,
  6026. SourceLocation StartLoc,
  6027. SourceLocation EndLoc) {
  6028. if (!AStmt)
  6029. return StmtError();
  6030. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6031. // OpenMP [2.10.1, Restrictions, p. 97]
  6032. // At least one map clause must appear on the directive.
  6033. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6034. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6035. << "'map' or 'use_device_ptr'"
  6036. << getOpenMPDirectiveName(OMPD_target_data);
  6037. return StmtError();
  6038. }
  6039. getCurFunction()->setHasBranchProtectedScope();
  6040. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6041. AStmt);
  6042. }
  6043. StmtResult
  6044. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6045. SourceLocation StartLoc,
  6046. SourceLocation EndLoc, Stmt *AStmt) {
  6047. if (!AStmt)
  6048. return StmtError();
  6049. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6050. // 1.2.2 OpenMP Language Terminology
  6051. // Structured block - An executable statement with a single entry at the
  6052. // top and a single exit at the bottom.
  6053. // The point of exit cannot be a branch out of the structured block.
  6054. // longjmp() and throw() must not violate the entry/exit criteria.
  6055. CS->getCapturedDecl()->setNothrow();
  6056. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6057. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6058. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6059. // 1.2.2 OpenMP Language Terminology
  6060. // Structured block - An executable statement with a single entry at the
  6061. // top and a single exit at the bottom.
  6062. // The point of exit cannot be a branch out of the structured block.
  6063. // longjmp() and throw() must not violate the entry/exit criteria.
  6064. CS->getCapturedDecl()->setNothrow();
  6065. }
  6066. // OpenMP [2.10.2, Restrictions, p. 99]
  6067. // At least one map clause must appear on the directive.
  6068. if (!hasClauses(Clauses, OMPC_map)) {
  6069. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6070. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6071. return StmtError();
  6072. }
  6073. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6074. AStmt);
  6075. }
  6076. StmtResult
  6077. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6078. SourceLocation StartLoc,
  6079. SourceLocation EndLoc, Stmt *AStmt) {
  6080. if (!AStmt)
  6081. return StmtError();
  6082. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6083. // 1.2.2 OpenMP Language Terminology
  6084. // Structured block - An executable statement with a single entry at the
  6085. // top and a single exit at the bottom.
  6086. // The point of exit cannot be a branch out of the structured block.
  6087. // longjmp() and throw() must not violate the entry/exit criteria.
  6088. CS->getCapturedDecl()->setNothrow();
  6089. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6090. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6091. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6092. // 1.2.2 OpenMP Language Terminology
  6093. // Structured block - An executable statement with a single entry at the
  6094. // top and a single exit at the bottom.
  6095. // The point of exit cannot be a branch out of the structured block.
  6096. // longjmp() and throw() must not violate the entry/exit criteria.
  6097. CS->getCapturedDecl()->setNothrow();
  6098. }
  6099. // OpenMP [2.10.3, Restrictions, p. 102]
  6100. // At least one map clause must appear on the directive.
  6101. if (!hasClauses(Clauses, OMPC_map)) {
  6102. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6103. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6104. return StmtError();
  6105. }
  6106. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6107. AStmt);
  6108. }
  6109. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6110. SourceLocation StartLoc,
  6111. SourceLocation EndLoc,
  6112. Stmt *AStmt) {
  6113. if (!AStmt)
  6114. return StmtError();
  6115. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6116. // 1.2.2 OpenMP Language Terminology
  6117. // Structured block - An executable statement with a single entry at the
  6118. // top and a single exit at the bottom.
  6119. // The point of exit cannot be a branch out of the structured block.
  6120. // longjmp() and throw() must not violate the entry/exit criteria.
  6121. CS->getCapturedDecl()->setNothrow();
  6122. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6123. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6124. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6125. // 1.2.2 OpenMP Language Terminology
  6126. // Structured block - An executable statement with a single entry at the
  6127. // top and a single exit at the bottom.
  6128. // The point of exit cannot be a branch out of the structured block.
  6129. // longjmp() and throw() must not violate the entry/exit criteria.
  6130. CS->getCapturedDecl()->setNothrow();
  6131. }
  6132. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6133. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6134. return StmtError();
  6135. }
  6136. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6137. AStmt);
  6138. }
  6139. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6140. Stmt *AStmt, SourceLocation StartLoc,
  6141. SourceLocation EndLoc) {
  6142. if (!AStmt)
  6143. return StmtError();
  6144. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6145. // 1.2.2 OpenMP Language Terminology
  6146. // Structured block - An executable statement with a single entry at the
  6147. // top and a single exit at the bottom.
  6148. // The point of exit cannot be a branch out of the structured block.
  6149. // longjmp() and throw() must not violate the entry/exit criteria.
  6150. CS->getCapturedDecl()->setNothrow();
  6151. getCurFunction()->setHasBranchProtectedScope();
  6152. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6153. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6154. }
  6155. StmtResult
  6156. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6157. SourceLocation EndLoc,
  6158. OpenMPDirectiveKind CancelRegion) {
  6159. if (DSAStack->isParentNowaitRegion()) {
  6160. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6161. return StmtError();
  6162. }
  6163. if (DSAStack->isParentOrderedRegion()) {
  6164. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6165. return StmtError();
  6166. }
  6167. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6168. CancelRegion);
  6169. }
  6170. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6171. SourceLocation StartLoc,
  6172. SourceLocation EndLoc,
  6173. OpenMPDirectiveKind CancelRegion) {
  6174. if (DSAStack->isParentNowaitRegion()) {
  6175. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6176. return StmtError();
  6177. }
  6178. if (DSAStack->isParentOrderedRegion()) {
  6179. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6180. return StmtError();
  6181. }
  6182. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6183. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6184. CancelRegion);
  6185. }
  6186. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6187. ArrayRef<OMPClause *> Clauses) {
  6188. OMPClause *PrevClause = nullptr;
  6189. bool ErrorFound = false;
  6190. for (auto *C : Clauses) {
  6191. if (C->getClauseKind() == OMPC_grainsize ||
  6192. C->getClauseKind() == OMPC_num_tasks) {
  6193. if (!PrevClause)
  6194. PrevClause = C;
  6195. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6196. S.Diag(C->getLocStart(),
  6197. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6198. << getOpenMPClauseName(C->getClauseKind())
  6199. << getOpenMPClauseName(PrevClause->getClauseKind());
  6200. S.Diag(PrevClause->getLocStart(),
  6201. diag::note_omp_previous_grainsize_num_tasks)
  6202. << getOpenMPClauseName(PrevClause->getClauseKind());
  6203. ErrorFound = true;
  6204. }
  6205. }
  6206. }
  6207. return ErrorFound;
  6208. }
  6209. static bool checkReductionClauseWithNogroup(Sema &S,
  6210. ArrayRef<OMPClause *> Clauses) {
  6211. OMPClause *ReductionClause = nullptr;
  6212. OMPClause *NogroupClause = nullptr;
  6213. for (auto *C : Clauses) {
  6214. if (C->getClauseKind() == OMPC_reduction) {
  6215. ReductionClause = C;
  6216. if (NogroupClause)
  6217. break;
  6218. continue;
  6219. }
  6220. if (C->getClauseKind() == OMPC_nogroup) {
  6221. NogroupClause = C;
  6222. if (ReductionClause)
  6223. break;
  6224. continue;
  6225. }
  6226. }
  6227. if (ReductionClause && NogroupClause) {
  6228. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6229. << SourceRange(NogroupClause->getLocStart(),
  6230. NogroupClause->getLocEnd());
  6231. return true;
  6232. }
  6233. return false;
  6234. }
  6235. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6236. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6237. SourceLocation EndLoc,
  6238. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6239. if (!AStmt)
  6240. return StmtError();
  6241. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6242. OMPLoopDirective::HelperExprs B;
  6243. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6244. // define the nested loops number.
  6245. unsigned NestedLoopCount =
  6246. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6247. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6248. VarsWithImplicitDSA, B);
  6249. if (NestedLoopCount == 0)
  6250. return StmtError();
  6251. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6252. "omp for loop exprs were not built");
  6253. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6254. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6255. // not appear on the same taskloop directive.
  6256. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6257. return StmtError();
  6258. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6259. // If a reduction clause is present on the taskloop directive, the nogroup
  6260. // clause must not be specified.
  6261. if (checkReductionClauseWithNogroup(*this, Clauses))
  6262. return StmtError();
  6263. getCurFunction()->setHasBranchProtectedScope();
  6264. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6265. NestedLoopCount, Clauses, AStmt, B);
  6266. }
  6267. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6268. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6269. SourceLocation EndLoc,
  6270. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6271. if (!AStmt)
  6272. return StmtError();
  6273. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6274. OMPLoopDirective::HelperExprs B;
  6275. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6276. // define the nested loops number.
  6277. unsigned NestedLoopCount =
  6278. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6279. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6280. VarsWithImplicitDSA, B);
  6281. if (NestedLoopCount == 0)
  6282. return StmtError();
  6283. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6284. "omp for loop exprs were not built");
  6285. if (!CurContext->isDependentContext()) {
  6286. // Finalize the clauses that need pre-built expressions for CodeGen.
  6287. for (auto C : Clauses) {
  6288. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6289. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6290. B.NumIterations, *this, CurScope,
  6291. DSAStack))
  6292. return StmtError();
  6293. }
  6294. }
  6295. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6296. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6297. // not appear on the same taskloop directive.
  6298. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6299. return StmtError();
  6300. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6301. // If a reduction clause is present on the taskloop directive, the nogroup
  6302. // clause must not be specified.
  6303. if (checkReductionClauseWithNogroup(*this, Clauses))
  6304. return StmtError();
  6305. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6306. return StmtError();
  6307. getCurFunction()->setHasBranchProtectedScope();
  6308. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6309. NestedLoopCount, Clauses, AStmt, B);
  6310. }
  6311. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6312. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6313. SourceLocation EndLoc,
  6314. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6315. if (!AStmt)
  6316. return StmtError();
  6317. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6318. OMPLoopDirective::HelperExprs B;
  6319. // In presence of clause 'collapse' with number of loops, it will
  6320. // define the nested loops number.
  6321. unsigned NestedLoopCount =
  6322. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6323. nullptr /*ordered not a clause on distribute*/, AStmt,
  6324. *this, *DSAStack, VarsWithImplicitDSA, B);
  6325. if (NestedLoopCount == 0)
  6326. return StmtError();
  6327. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6328. "omp for loop exprs were not built");
  6329. getCurFunction()->setHasBranchProtectedScope();
  6330. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6331. NestedLoopCount, Clauses, AStmt, B);
  6332. }
  6333. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6334. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6335. SourceLocation EndLoc,
  6336. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6337. if (!AStmt)
  6338. return StmtError();
  6339. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6340. // 1.2.2 OpenMP Language Terminology
  6341. // Structured block - An executable statement with a single entry at the
  6342. // top and a single exit at the bottom.
  6343. // The point of exit cannot be a branch out of the structured block.
  6344. // longjmp() and throw() must not violate the entry/exit criteria.
  6345. CS->getCapturedDecl()->setNothrow();
  6346. for (int ThisCaptureLevel =
  6347. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6348. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6349. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6350. // 1.2.2 OpenMP Language Terminology
  6351. // Structured block - An executable statement with a single entry at the
  6352. // top and a single exit at the bottom.
  6353. // The point of exit cannot be a branch out of the structured block.
  6354. // longjmp() and throw() must not violate the entry/exit criteria.
  6355. CS->getCapturedDecl()->setNothrow();
  6356. }
  6357. OMPLoopDirective::HelperExprs B;
  6358. // In presence of clause 'collapse' with number of loops, it will
  6359. // define the nested loops number.
  6360. unsigned NestedLoopCount = CheckOpenMPLoop(
  6361. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6362. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6363. VarsWithImplicitDSA, B);
  6364. if (NestedLoopCount == 0)
  6365. return StmtError();
  6366. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6367. "omp for loop exprs were not built");
  6368. getCurFunction()->setHasBranchProtectedScope();
  6369. return OMPDistributeParallelForDirective::Create(
  6370. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6371. DSAStack->isCancelRegion());
  6372. }
  6373. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6374. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6375. SourceLocation EndLoc,
  6376. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6377. if (!AStmt)
  6378. return StmtError();
  6379. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6380. // 1.2.2 OpenMP Language Terminology
  6381. // Structured block - An executable statement with a single entry at the
  6382. // top and a single exit at the bottom.
  6383. // The point of exit cannot be a branch out of the structured block.
  6384. // longjmp() and throw() must not violate the entry/exit criteria.
  6385. CS->getCapturedDecl()->setNothrow();
  6386. for (int ThisCaptureLevel =
  6387. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6388. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6389. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6390. // 1.2.2 OpenMP Language Terminology
  6391. // Structured block - An executable statement with a single entry at the
  6392. // top and a single exit at the bottom.
  6393. // The point of exit cannot be a branch out of the structured block.
  6394. // longjmp() and throw() must not violate the entry/exit criteria.
  6395. CS->getCapturedDecl()->setNothrow();
  6396. }
  6397. OMPLoopDirective::HelperExprs B;
  6398. // In presence of clause 'collapse' with number of loops, it will
  6399. // define the nested loops number.
  6400. unsigned NestedLoopCount = CheckOpenMPLoop(
  6401. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6402. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6403. VarsWithImplicitDSA, B);
  6404. if (NestedLoopCount == 0)
  6405. return StmtError();
  6406. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6407. "omp for loop exprs were not built");
  6408. if (!CurContext->isDependentContext()) {
  6409. // Finalize the clauses that need pre-built expressions for CodeGen.
  6410. for (auto C : Clauses) {
  6411. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6412. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6413. B.NumIterations, *this, CurScope,
  6414. DSAStack))
  6415. return StmtError();
  6416. }
  6417. }
  6418. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6419. return StmtError();
  6420. getCurFunction()->setHasBranchProtectedScope();
  6421. return OMPDistributeParallelForSimdDirective::Create(
  6422. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6423. }
  6424. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6425. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6426. SourceLocation EndLoc,
  6427. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6428. if (!AStmt)
  6429. return StmtError();
  6430. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6431. // 1.2.2 OpenMP Language Terminology
  6432. // Structured block - An executable statement with a single entry at the
  6433. // top and a single exit at the bottom.
  6434. // The point of exit cannot be a branch out of the structured block.
  6435. // longjmp() and throw() must not violate the entry/exit criteria.
  6436. CS->getCapturedDecl()->setNothrow();
  6437. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6438. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6439. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6440. // 1.2.2 OpenMP Language Terminology
  6441. // Structured block - An executable statement with a single entry at the
  6442. // top and a single exit at the bottom.
  6443. // The point of exit cannot be a branch out of the structured block.
  6444. // longjmp() and throw() must not violate the entry/exit criteria.
  6445. CS->getCapturedDecl()->setNothrow();
  6446. }
  6447. OMPLoopDirective::HelperExprs B;
  6448. // In presence of clause 'collapse' with number of loops, it will
  6449. // define the nested loops number.
  6450. unsigned NestedLoopCount =
  6451. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6452. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6453. *DSAStack, VarsWithImplicitDSA, B);
  6454. if (NestedLoopCount == 0)
  6455. return StmtError();
  6456. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6457. "omp for loop exprs were not built");
  6458. if (!CurContext->isDependentContext()) {
  6459. // Finalize the clauses that need pre-built expressions for CodeGen.
  6460. for (auto C : Clauses) {
  6461. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6462. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6463. B.NumIterations, *this, CurScope,
  6464. DSAStack))
  6465. return StmtError();
  6466. }
  6467. }
  6468. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6469. return StmtError();
  6470. getCurFunction()->setHasBranchProtectedScope();
  6471. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6472. NestedLoopCount, Clauses, AStmt, B);
  6473. }
  6474. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6475. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6476. SourceLocation EndLoc,
  6477. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6478. if (!AStmt)
  6479. return StmtError();
  6480. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6481. // 1.2.2 OpenMP Language Terminology
  6482. // Structured block - An executable statement with a single entry at the
  6483. // top and a single exit at the bottom.
  6484. // The point of exit cannot be a branch out of the structured block.
  6485. // longjmp() and throw() must not violate the entry/exit criteria.
  6486. CS->getCapturedDecl()->setNothrow();
  6487. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6488. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6489. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6490. // 1.2.2 OpenMP Language Terminology
  6491. // Structured block - An executable statement with a single entry at the
  6492. // top and a single exit at the bottom.
  6493. // The point of exit cannot be a branch out of the structured block.
  6494. // longjmp() and throw() must not violate the entry/exit criteria.
  6495. CS->getCapturedDecl()->setNothrow();
  6496. }
  6497. OMPLoopDirective::HelperExprs B;
  6498. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6499. // define the nested loops number.
  6500. unsigned NestedLoopCount = CheckOpenMPLoop(
  6501. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6502. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6503. VarsWithImplicitDSA, B);
  6504. if (NestedLoopCount == 0)
  6505. return StmtError();
  6506. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6507. "omp target parallel for simd loop exprs were not built");
  6508. if (!CurContext->isDependentContext()) {
  6509. // Finalize the clauses that need pre-built expressions for CodeGen.
  6510. for (auto C : Clauses) {
  6511. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6512. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6513. B.NumIterations, *this, CurScope,
  6514. DSAStack))
  6515. return StmtError();
  6516. }
  6517. }
  6518. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6519. return StmtError();
  6520. getCurFunction()->setHasBranchProtectedScope();
  6521. return OMPTargetParallelForSimdDirective::Create(
  6522. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6523. }
  6524. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  6525. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6526. SourceLocation EndLoc,
  6527. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6528. if (!AStmt)
  6529. return StmtError();
  6530. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6531. // 1.2.2 OpenMP Language Terminology
  6532. // Structured block - An executable statement with a single entry at the
  6533. // top and a single exit at the bottom.
  6534. // The point of exit cannot be a branch out of the structured block.
  6535. // longjmp() and throw() must not violate the entry/exit criteria.
  6536. CS->getCapturedDecl()->setNothrow();
  6537. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  6538. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6539. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6540. // 1.2.2 OpenMP Language Terminology
  6541. // Structured block - An executable statement with a single entry at the
  6542. // top and a single exit at the bottom.
  6543. // The point of exit cannot be a branch out of the structured block.
  6544. // longjmp() and throw() must not violate the entry/exit criteria.
  6545. CS->getCapturedDecl()->setNothrow();
  6546. }
  6547. OMPLoopDirective::HelperExprs B;
  6548. // In presence of clause 'collapse' with number of loops, it will define the
  6549. // nested loops number.
  6550. unsigned NestedLoopCount =
  6551. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6552. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6553. VarsWithImplicitDSA, B);
  6554. if (NestedLoopCount == 0)
  6555. return StmtError();
  6556. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6557. "omp target simd loop exprs were not built");
  6558. if (!CurContext->isDependentContext()) {
  6559. // Finalize the clauses that need pre-built expressions for CodeGen.
  6560. for (auto C : Clauses) {
  6561. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6562. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6563. B.NumIterations, *this, CurScope,
  6564. DSAStack))
  6565. return StmtError();
  6566. }
  6567. }
  6568. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6569. return StmtError();
  6570. getCurFunction()->setHasBranchProtectedScope();
  6571. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6572. NestedLoopCount, Clauses, AStmt, B);
  6573. }
  6574. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  6575. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6576. SourceLocation EndLoc,
  6577. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6578. if (!AStmt)
  6579. return StmtError();
  6580. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6581. // 1.2.2 OpenMP Language Terminology
  6582. // Structured block - An executable statement with a single entry at the
  6583. // top and a single exit at the bottom.
  6584. // The point of exit cannot be a branch out of the structured block.
  6585. // longjmp() and throw() must not violate the entry/exit criteria.
  6586. CS->getCapturedDecl()->setNothrow();
  6587. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  6588. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6589. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6590. // 1.2.2 OpenMP Language Terminology
  6591. // Structured block - An executable statement with a single entry at the
  6592. // top and a single exit at the bottom.
  6593. // The point of exit cannot be a branch out of the structured block.
  6594. // longjmp() and throw() must not violate the entry/exit criteria.
  6595. CS->getCapturedDecl()->setNothrow();
  6596. }
  6597. OMPLoopDirective::HelperExprs B;
  6598. // In presence of clause 'collapse' with number of loops, it will
  6599. // define the nested loops number.
  6600. unsigned NestedLoopCount =
  6601. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6602. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6603. *DSAStack, VarsWithImplicitDSA, B);
  6604. if (NestedLoopCount == 0)
  6605. return StmtError();
  6606. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6607. "omp teams distribute loop exprs were not built");
  6608. getCurFunction()->setHasBranchProtectedScope();
  6609. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6610. return OMPTeamsDistributeDirective::Create(
  6611. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6612. }
  6613. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6614. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6615. SourceLocation EndLoc,
  6616. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6617. if (!AStmt)
  6618. return StmtError();
  6619. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6620. // 1.2.2 OpenMP Language Terminology
  6621. // Structured block - An executable statement with a single entry at the
  6622. // top and a single exit at the bottom.
  6623. // The point of exit cannot be a branch out of the structured block.
  6624. // longjmp() and throw() must not violate the entry/exit criteria.
  6625. CS->getCapturedDecl()->setNothrow();
  6626. for (int ThisCaptureLevel =
  6627. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  6628. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6629. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6630. // 1.2.2 OpenMP Language Terminology
  6631. // Structured block - An executable statement with a single entry at the
  6632. // top and a single exit at the bottom.
  6633. // The point of exit cannot be a branch out of the structured block.
  6634. // longjmp() and throw() must not violate the entry/exit criteria.
  6635. CS->getCapturedDecl()->setNothrow();
  6636. }
  6637. OMPLoopDirective::HelperExprs B;
  6638. // In presence of clause 'collapse' with number of loops, it will
  6639. // define the nested loops number.
  6640. unsigned NestedLoopCount = CheckOpenMPLoop(
  6641. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6642. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6643. VarsWithImplicitDSA, B);
  6644. if (NestedLoopCount == 0)
  6645. return StmtError();
  6646. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6647. "omp teams distribute simd loop exprs were not built");
  6648. if (!CurContext->isDependentContext()) {
  6649. // Finalize the clauses that need pre-built expressions for CodeGen.
  6650. for (auto C : Clauses) {
  6651. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6652. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6653. B.NumIterations, *this, CurScope,
  6654. DSAStack))
  6655. return StmtError();
  6656. }
  6657. }
  6658. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6659. return StmtError();
  6660. getCurFunction()->setHasBranchProtectedScope();
  6661. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6662. return OMPTeamsDistributeSimdDirective::Create(
  6663. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6664. }
  6665. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6666. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6667. SourceLocation EndLoc,
  6668. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6669. if (!AStmt)
  6670. return StmtError();
  6671. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6672. // 1.2.2 OpenMP Language Terminology
  6673. // Structured block - An executable statement with a single entry at the
  6674. // top and a single exit at the bottom.
  6675. // The point of exit cannot be a branch out of the structured block.
  6676. // longjmp() and throw() must not violate the entry/exit criteria.
  6677. CS->getCapturedDecl()->setNothrow();
  6678. for (int ThisCaptureLevel =
  6679. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  6680. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6681. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6682. // 1.2.2 OpenMP Language Terminology
  6683. // Structured block - An executable statement with a single entry at the
  6684. // top and a single exit at the bottom.
  6685. // The point of exit cannot be a branch out of the structured block.
  6686. // longjmp() and throw() must not violate the entry/exit criteria.
  6687. CS->getCapturedDecl()->setNothrow();
  6688. }
  6689. OMPLoopDirective::HelperExprs B;
  6690. // In presence of clause 'collapse' with number of loops, it will
  6691. // define the nested loops number.
  6692. auto NestedLoopCount = CheckOpenMPLoop(
  6693. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6694. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6695. VarsWithImplicitDSA, B);
  6696. if (NestedLoopCount == 0)
  6697. return StmtError();
  6698. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6699. "omp for loop exprs were not built");
  6700. if (!CurContext->isDependentContext()) {
  6701. // Finalize the clauses that need pre-built expressions for CodeGen.
  6702. for (auto C : Clauses) {
  6703. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6704. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6705. B.NumIterations, *this, CurScope,
  6706. DSAStack))
  6707. return StmtError();
  6708. }
  6709. }
  6710. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6711. return StmtError();
  6712. getCurFunction()->setHasBranchProtectedScope();
  6713. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6714. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6715. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6716. }
  6717. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6718. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6719. SourceLocation EndLoc,
  6720. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6721. if (!AStmt)
  6722. return StmtError();
  6723. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6724. // 1.2.2 OpenMP Language Terminology
  6725. // Structured block - An executable statement with a single entry at the
  6726. // top and a single exit at the bottom.
  6727. // The point of exit cannot be a branch out of the structured block.
  6728. // longjmp() and throw() must not violate the entry/exit criteria.
  6729. CS->getCapturedDecl()->setNothrow();
  6730. for (int ThisCaptureLevel =
  6731. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  6732. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6733. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6734. // 1.2.2 OpenMP Language Terminology
  6735. // Structured block - An executable statement with a single entry at the
  6736. // top and a single exit at the bottom.
  6737. // The point of exit cannot be a branch out of the structured block.
  6738. // longjmp() and throw() must not violate the entry/exit criteria.
  6739. CS->getCapturedDecl()->setNothrow();
  6740. }
  6741. OMPLoopDirective::HelperExprs B;
  6742. // In presence of clause 'collapse' with number of loops, it will
  6743. // define the nested loops number.
  6744. unsigned NestedLoopCount = CheckOpenMPLoop(
  6745. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6746. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6747. VarsWithImplicitDSA, B);
  6748. if (NestedLoopCount == 0)
  6749. return StmtError();
  6750. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6751. "omp for loop exprs were not built");
  6752. getCurFunction()->setHasBranchProtectedScope();
  6753. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6754. return OMPTeamsDistributeParallelForDirective::Create(
  6755. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6756. DSAStack->isCancelRegion());
  6757. }
  6758. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6759. Stmt *AStmt,
  6760. SourceLocation StartLoc,
  6761. SourceLocation EndLoc) {
  6762. if (!AStmt)
  6763. return StmtError();
  6764. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6765. // 1.2.2 OpenMP Language Terminology
  6766. // Structured block - An executable statement with a single entry at the
  6767. // top and a single exit at the bottom.
  6768. // The point of exit cannot be a branch out of the structured block.
  6769. // longjmp() and throw() must not violate the entry/exit criteria.
  6770. CS->getCapturedDecl()->setNothrow();
  6771. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  6772. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6773. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6774. // 1.2.2 OpenMP Language Terminology
  6775. // Structured block - An executable statement with a single entry at the
  6776. // top and a single exit at the bottom.
  6777. // The point of exit cannot be a branch out of the structured block.
  6778. // longjmp() and throw() must not violate the entry/exit criteria.
  6779. CS->getCapturedDecl()->setNothrow();
  6780. }
  6781. getCurFunction()->setHasBranchProtectedScope();
  6782. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6783. AStmt);
  6784. }
  6785. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  6786. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6787. SourceLocation EndLoc,
  6788. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6789. if (!AStmt)
  6790. return StmtError();
  6791. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6792. // 1.2.2 OpenMP Language Terminology
  6793. // Structured block - An executable statement with a single entry at the
  6794. // top and a single exit at the bottom.
  6795. // The point of exit cannot be a branch out of the structured block.
  6796. // longjmp() and throw() must not violate the entry/exit criteria.
  6797. CS->getCapturedDecl()->setNothrow();
  6798. for (int ThisCaptureLevel =
  6799. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  6800. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6801. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6802. // 1.2.2 OpenMP Language Terminology
  6803. // Structured block - An executable statement with a single entry at the
  6804. // top and a single exit at the bottom.
  6805. // The point of exit cannot be a branch out of the structured block.
  6806. // longjmp() and throw() must not violate the entry/exit criteria.
  6807. CS->getCapturedDecl()->setNothrow();
  6808. }
  6809. OMPLoopDirective::HelperExprs B;
  6810. // In presence of clause 'collapse' with number of loops, it will
  6811. // define the nested loops number.
  6812. auto NestedLoopCount = CheckOpenMPLoop(
  6813. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  6814. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6815. VarsWithImplicitDSA, B);
  6816. if (NestedLoopCount == 0)
  6817. return StmtError();
  6818. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6819. "omp target teams distribute loop exprs were not built");
  6820. getCurFunction()->setHasBranchProtectedScope();
  6821. return OMPTargetTeamsDistributeDirective::Create(
  6822. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6823. }
  6824. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6825. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6826. SourceLocation EndLoc,
  6827. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6828. if (!AStmt)
  6829. return StmtError();
  6830. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6831. // 1.2.2 OpenMP Language Terminology
  6832. // Structured block - An executable statement with a single entry at the
  6833. // top and a single exit at the bottom.
  6834. // The point of exit cannot be a branch out of the structured block.
  6835. // longjmp() and throw() must not violate the entry/exit criteria.
  6836. CS->getCapturedDecl()->setNothrow();
  6837. OMPLoopDirective::HelperExprs B;
  6838. // In presence of clause 'collapse' with number of loops, it will
  6839. // define the nested loops number.
  6840. auto NestedLoopCount = CheckOpenMPLoop(
  6841. OMPD_target_teams_distribute_parallel_for,
  6842. getCollapseNumberExpr(Clauses),
  6843. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6844. VarsWithImplicitDSA, B);
  6845. if (NestedLoopCount == 0)
  6846. return StmtError();
  6847. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6848. "omp target teams distribute parallel for loop exprs were not built");
  6849. getCurFunction()->setHasBranchProtectedScope();
  6850. return OMPTargetTeamsDistributeParallelForDirective::Create(
  6851. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6852. DSAStack->isCancelRegion());
  6853. }
  6854. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6855. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6856. SourceLocation EndLoc,
  6857. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6858. if (!AStmt)
  6859. return StmtError();
  6860. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6861. // 1.2.2 OpenMP Language Terminology
  6862. // Structured block - An executable statement with a single entry at the
  6863. // top and a single exit at the bottom.
  6864. // The point of exit cannot be a branch out of the structured block.
  6865. // longjmp() and throw() must not violate the entry/exit criteria.
  6866. CS->getCapturedDecl()->setNothrow();
  6867. OMPLoopDirective::HelperExprs B;
  6868. // In presence of clause 'collapse' with number of loops, it will
  6869. // define the nested loops number.
  6870. auto NestedLoopCount = CheckOpenMPLoop(
  6871. OMPD_target_teams_distribute_parallel_for_simd,
  6872. getCollapseNumberExpr(Clauses),
  6873. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6874. VarsWithImplicitDSA, B);
  6875. if (NestedLoopCount == 0)
  6876. return StmtError();
  6877. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6878. "omp target teams distribute parallel for simd loop exprs were not "
  6879. "built");
  6880. if (!CurContext->isDependentContext()) {
  6881. // Finalize the clauses that need pre-built expressions for CodeGen.
  6882. for (auto C : Clauses) {
  6883. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6884. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6885. B.NumIterations, *this, CurScope,
  6886. DSAStack))
  6887. return StmtError();
  6888. }
  6889. }
  6890. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6891. return StmtError();
  6892. getCurFunction()->setHasBranchProtectedScope();
  6893. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  6894. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6895. }
  6896. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6897. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6898. SourceLocation EndLoc,
  6899. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6900. if (!AStmt)
  6901. return StmtError();
  6902. auto *CS = cast<CapturedStmt>(AStmt);
  6903. // 1.2.2 OpenMP Language Terminology
  6904. // Structured block - An executable statement with a single entry at the
  6905. // top and a single exit at the bottom.
  6906. // The point of exit cannot be a branch out of the structured block.
  6907. // longjmp() and throw() must not violate the entry/exit criteria.
  6908. CS->getCapturedDecl()->setNothrow();
  6909. OMPLoopDirective::HelperExprs B;
  6910. // In presence of clause 'collapse' with number of loops, it will
  6911. // define the nested loops number.
  6912. auto NestedLoopCount = CheckOpenMPLoop(
  6913. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6914. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6915. VarsWithImplicitDSA, B);
  6916. if (NestedLoopCount == 0)
  6917. return StmtError();
  6918. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6919. "omp target teams distribute simd loop exprs were not built");
  6920. if (!CurContext->isDependentContext()) {
  6921. // Finalize the clauses that need pre-built expressions for CodeGen.
  6922. for (auto C : Clauses) {
  6923. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6924. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6925. B.NumIterations, *this, CurScope,
  6926. DSAStack))
  6927. return StmtError();
  6928. }
  6929. }
  6930. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6931. return StmtError();
  6932. getCurFunction()->setHasBranchProtectedScope();
  6933. return OMPTargetTeamsDistributeSimdDirective::Create(
  6934. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6935. }
  6936. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  6937. SourceLocation StartLoc,
  6938. SourceLocation LParenLoc,
  6939. SourceLocation EndLoc) {
  6940. OMPClause *Res = nullptr;
  6941. switch (Kind) {
  6942. case OMPC_final:
  6943. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  6944. break;
  6945. case OMPC_num_threads:
  6946. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6947. break;
  6948. case OMPC_safelen:
  6949. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6950. break;
  6951. case OMPC_simdlen:
  6952. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6953. break;
  6954. case OMPC_collapse:
  6955. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  6956. break;
  6957. case OMPC_ordered:
  6958. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  6959. break;
  6960. case OMPC_device:
  6961. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  6962. break;
  6963. case OMPC_num_teams:
  6964. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6965. break;
  6966. case OMPC_thread_limit:
  6967. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  6968. break;
  6969. case OMPC_priority:
  6970. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  6971. break;
  6972. case OMPC_grainsize:
  6973. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  6974. break;
  6975. case OMPC_num_tasks:
  6976. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  6977. break;
  6978. case OMPC_hint:
  6979. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  6980. break;
  6981. case OMPC_if:
  6982. case OMPC_default:
  6983. case OMPC_proc_bind:
  6984. case OMPC_schedule:
  6985. case OMPC_private:
  6986. case OMPC_firstprivate:
  6987. case OMPC_lastprivate:
  6988. case OMPC_shared:
  6989. case OMPC_reduction:
  6990. case OMPC_task_reduction:
  6991. case OMPC_in_reduction:
  6992. case OMPC_linear:
  6993. case OMPC_aligned:
  6994. case OMPC_copyin:
  6995. case OMPC_copyprivate:
  6996. case OMPC_nowait:
  6997. case OMPC_untied:
  6998. case OMPC_mergeable:
  6999. case OMPC_threadprivate:
  7000. case OMPC_flush:
  7001. case OMPC_read:
  7002. case OMPC_write:
  7003. case OMPC_update:
  7004. case OMPC_capture:
  7005. case OMPC_seq_cst:
  7006. case OMPC_depend:
  7007. case OMPC_threads:
  7008. case OMPC_simd:
  7009. case OMPC_map:
  7010. case OMPC_nogroup:
  7011. case OMPC_dist_schedule:
  7012. case OMPC_defaultmap:
  7013. case OMPC_unknown:
  7014. case OMPC_uniform:
  7015. case OMPC_to:
  7016. case OMPC_from:
  7017. case OMPC_use_device_ptr:
  7018. case OMPC_is_device_ptr:
  7019. llvm_unreachable("Clause is not allowed.");
  7020. }
  7021. return Res;
  7022. }
  7023. // An OpenMP directive such as 'target parallel' has two captured regions:
  7024. // for the 'target' and 'parallel' respectively. This function returns
  7025. // the region in which to capture expressions associated with a clause.
  7026. // A return value of OMPD_unknown signifies that the expression should not
  7027. // be captured.
  7028. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7029. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7030. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7031. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7032. switch (CKind) {
  7033. case OMPC_if:
  7034. switch (DKind) {
  7035. case OMPD_target_parallel:
  7036. case OMPD_target_parallel_for:
  7037. case OMPD_target_parallel_for_simd:
  7038. case OMPD_target_teams_distribute_parallel_for:
  7039. case OMPD_target_teams_distribute_parallel_for_simd:
  7040. // If this clause applies to the nested 'parallel' region, capture within
  7041. // the 'target' region, otherwise do not capture.
  7042. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7043. CaptureRegion = OMPD_target;
  7044. break;
  7045. case OMPD_teams_distribute_parallel_for:
  7046. case OMPD_teams_distribute_parallel_for_simd:
  7047. CaptureRegion = OMPD_teams;
  7048. break;
  7049. case OMPD_cancel:
  7050. case OMPD_parallel:
  7051. case OMPD_parallel_sections:
  7052. case OMPD_parallel_for:
  7053. case OMPD_parallel_for_simd:
  7054. case OMPD_target:
  7055. case OMPD_target_simd:
  7056. case OMPD_target_teams:
  7057. case OMPD_target_teams_distribute:
  7058. case OMPD_target_teams_distribute_simd:
  7059. case OMPD_distribute_parallel_for:
  7060. case OMPD_distribute_parallel_for_simd:
  7061. case OMPD_task:
  7062. case OMPD_taskloop:
  7063. case OMPD_taskloop_simd:
  7064. case OMPD_target_data:
  7065. case OMPD_target_enter_data:
  7066. case OMPD_target_exit_data:
  7067. case OMPD_target_update:
  7068. // Do not capture if-clause expressions.
  7069. break;
  7070. case OMPD_threadprivate:
  7071. case OMPD_taskyield:
  7072. case OMPD_barrier:
  7073. case OMPD_taskwait:
  7074. case OMPD_cancellation_point:
  7075. case OMPD_flush:
  7076. case OMPD_declare_reduction:
  7077. case OMPD_declare_simd:
  7078. case OMPD_declare_target:
  7079. case OMPD_end_declare_target:
  7080. case OMPD_teams:
  7081. case OMPD_simd:
  7082. case OMPD_for:
  7083. case OMPD_for_simd:
  7084. case OMPD_sections:
  7085. case OMPD_section:
  7086. case OMPD_single:
  7087. case OMPD_master:
  7088. case OMPD_critical:
  7089. case OMPD_taskgroup:
  7090. case OMPD_distribute:
  7091. case OMPD_ordered:
  7092. case OMPD_atomic:
  7093. case OMPD_distribute_simd:
  7094. case OMPD_teams_distribute:
  7095. case OMPD_teams_distribute_simd:
  7096. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7097. case OMPD_unknown:
  7098. llvm_unreachable("Unknown OpenMP directive");
  7099. }
  7100. break;
  7101. case OMPC_num_threads:
  7102. switch (DKind) {
  7103. case OMPD_target_parallel:
  7104. case OMPD_target_parallel_for:
  7105. case OMPD_target_parallel_for_simd:
  7106. case OMPD_target_teams_distribute_parallel_for:
  7107. case OMPD_target_teams_distribute_parallel_for_simd:
  7108. CaptureRegion = OMPD_target;
  7109. break;
  7110. case OMPD_teams_distribute_parallel_for:
  7111. case OMPD_teams_distribute_parallel_for_simd:
  7112. CaptureRegion = OMPD_teams;
  7113. break;
  7114. case OMPD_parallel:
  7115. case OMPD_parallel_sections:
  7116. case OMPD_parallel_for:
  7117. case OMPD_parallel_for_simd:
  7118. case OMPD_distribute_parallel_for:
  7119. case OMPD_distribute_parallel_for_simd:
  7120. // Do not capture num_threads-clause expressions.
  7121. break;
  7122. case OMPD_target_data:
  7123. case OMPD_target_enter_data:
  7124. case OMPD_target_exit_data:
  7125. case OMPD_target_update:
  7126. case OMPD_target:
  7127. case OMPD_target_simd:
  7128. case OMPD_target_teams:
  7129. case OMPD_target_teams_distribute:
  7130. case OMPD_target_teams_distribute_simd:
  7131. case OMPD_cancel:
  7132. case OMPD_task:
  7133. case OMPD_taskloop:
  7134. case OMPD_taskloop_simd:
  7135. case OMPD_threadprivate:
  7136. case OMPD_taskyield:
  7137. case OMPD_barrier:
  7138. case OMPD_taskwait:
  7139. case OMPD_cancellation_point:
  7140. case OMPD_flush:
  7141. case OMPD_declare_reduction:
  7142. case OMPD_declare_simd:
  7143. case OMPD_declare_target:
  7144. case OMPD_end_declare_target:
  7145. case OMPD_teams:
  7146. case OMPD_simd:
  7147. case OMPD_for:
  7148. case OMPD_for_simd:
  7149. case OMPD_sections:
  7150. case OMPD_section:
  7151. case OMPD_single:
  7152. case OMPD_master:
  7153. case OMPD_critical:
  7154. case OMPD_taskgroup:
  7155. case OMPD_distribute:
  7156. case OMPD_ordered:
  7157. case OMPD_atomic:
  7158. case OMPD_distribute_simd:
  7159. case OMPD_teams_distribute:
  7160. case OMPD_teams_distribute_simd:
  7161. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7162. case OMPD_unknown:
  7163. llvm_unreachable("Unknown OpenMP directive");
  7164. }
  7165. break;
  7166. case OMPC_num_teams:
  7167. switch (DKind) {
  7168. case OMPD_target_teams:
  7169. case OMPD_target_teams_distribute:
  7170. case OMPD_target_teams_distribute_simd:
  7171. case OMPD_target_teams_distribute_parallel_for:
  7172. case OMPD_target_teams_distribute_parallel_for_simd:
  7173. CaptureRegion = OMPD_target;
  7174. break;
  7175. case OMPD_teams_distribute_parallel_for:
  7176. case OMPD_teams_distribute_parallel_for_simd:
  7177. case OMPD_teams:
  7178. case OMPD_teams_distribute:
  7179. case OMPD_teams_distribute_simd:
  7180. // Do not capture num_teams-clause expressions.
  7181. break;
  7182. case OMPD_distribute_parallel_for:
  7183. case OMPD_distribute_parallel_for_simd:
  7184. case OMPD_task:
  7185. case OMPD_taskloop:
  7186. case OMPD_taskloop_simd:
  7187. case OMPD_target_data:
  7188. case OMPD_target_enter_data:
  7189. case OMPD_target_exit_data:
  7190. case OMPD_target_update:
  7191. case OMPD_cancel:
  7192. case OMPD_parallel:
  7193. case OMPD_parallel_sections:
  7194. case OMPD_parallel_for:
  7195. case OMPD_parallel_for_simd:
  7196. case OMPD_target:
  7197. case OMPD_target_simd:
  7198. case OMPD_target_parallel:
  7199. case OMPD_target_parallel_for:
  7200. case OMPD_target_parallel_for_simd:
  7201. case OMPD_threadprivate:
  7202. case OMPD_taskyield:
  7203. case OMPD_barrier:
  7204. case OMPD_taskwait:
  7205. case OMPD_cancellation_point:
  7206. case OMPD_flush:
  7207. case OMPD_declare_reduction:
  7208. case OMPD_declare_simd:
  7209. case OMPD_declare_target:
  7210. case OMPD_end_declare_target:
  7211. case OMPD_simd:
  7212. case OMPD_for:
  7213. case OMPD_for_simd:
  7214. case OMPD_sections:
  7215. case OMPD_section:
  7216. case OMPD_single:
  7217. case OMPD_master:
  7218. case OMPD_critical:
  7219. case OMPD_taskgroup:
  7220. case OMPD_distribute:
  7221. case OMPD_ordered:
  7222. case OMPD_atomic:
  7223. case OMPD_distribute_simd:
  7224. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7225. case OMPD_unknown:
  7226. llvm_unreachable("Unknown OpenMP directive");
  7227. }
  7228. break;
  7229. case OMPC_thread_limit:
  7230. switch (DKind) {
  7231. case OMPD_target_teams:
  7232. case OMPD_target_teams_distribute:
  7233. case OMPD_target_teams_distribute_simd:
  7234. case OMPD_target_teams_distribute_parallel_for:
  7235. case OMPD_target_teams_distribute_parallel_for_simd:
  7236. CaptureRegion = OMPD_target;
  7237. break;
  7238. case OMPD_teams_distribute_parallel_for:
  7239. case OMPD_teams_distribute_parallel_for_simd:
  7240. case OMPD_teams:
  7241. case OMPD_teams_distribute:
  7242. case OMPD_teams_distribute_simd:
  7243. // Do not capture thread_limit-clause expressions.
  7244. break;
  7245. case OMPD_distribute_parallel_for:
  7246. case OMPD_distribute_parallel_for_simd:
  7247. case OMPD_task:
  7248. case OMPD_taskloop:
  7249. case OMPD_taskloop_simd:
  7250. case OMPD_target_data:
  7251. case OMPD_target_enter_data:
  7252. case OMPD_target_exit_data:
  7253. case OMPD_target_update:
  7254. case OMPD_cancel:
  7255. case OMPD_parallel:
  7256. case OMPD_parallel_sections:
  7257. case OMPD_parallel_for:
  7258. case OMPD_parallel_for_simd:
  7259. case OMPD_target:
  7260. case OMPD_target_simd:
  7261. case OMPD_target_parallel:
  7262. case OMPD_target_parallel_for:
  7263. case OMPD_target_parallel_for_simd:
  7264. case OMPD_threadprivate:
  7265. case OMPD_taskyield:
  7266. case OMPD_barrier:
  7267. case OMPD_taskwait:
  7268. case OMPD_cancellation_point:
  7269. case OMPD_flush:
  7270. case OMPD_declare_reduction:
  7271. case OMPD_declare_simd:
  7272. case OMPD_declare_target:
  7273. case OMPD_end_declare_target:
  7274. case OMPD_simd:
  7275. case OMPD_for:
  7276. case OMPD_for_simd:
  7277. case OMPD_sections:
  7278. case OMPD_section:
  7279. case OMPD_single:
  7280. case OMPD_master:
  7281. case OMPD_critical:
  7282. case OMPD_taskgroup:
  7283. case OMPD_distribute:
  7284. case OMPD_ordered:
  7285. case OMPD_atomic:
  7286. case OMPD_distribute_simd:
  7287. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7288. case OMPD_unknown:
  7289. llvm_unreachable("Unknown OpenMP directive");
  7290. }
  7291. break;
  7292. case OMPC_schedule:
  7293. switch (DKind) {
  7294. case OMPD_target_parallel_for:
  7295. case OMPD_target_parallel_for_simd:
  7296. case OMPD_target_teams_distribute_parallel_for:
  7297. case OMPD_target_teams_distribute_parallel_for_simd:
  7298. CaptureRegion = OMPD_target;
  7299. break;
  7300. case OMPD_teams_distribute_parallel_for:
  7301. case OMPD_teams_distribute_parallel_for_simd:
  7302. CaptureRegion = OMPD_teams;
  7303. break;
  7304. case OMPD_parallel_for:
  7305. case OMPD_parallel_for_simd:
  7306. case OMPD_distribute_parallel_for:
  7307. case OMPD_distribute_parallel_for_simd:
  7308. CaptureRegion = OMPD_parallel;
  7309. break;
  7310. case OMPD_for:
  7311. case OMPD_for_simd:
  7312. // Do not capture schedule-clause expressions.
  7313. break;
  7314. case OMPD_task:
  7315. case OMPD_taskloop:
  7316. case OMPD_taskloop_simd:
  7317. case OMPD_target_data:
  7318. case OMPD_target_enter_data:
  7319. case OMPD_target_exit_data:
  7320. case OMPD_target_update:
  7321. case OMPD_teams:
  7322. case OMPD_teams_distribute:
  7323. case OMPD_teams_distribute_simd:
  7324. case OMPD_target_teams_distribute:
  7325. case OMPD_target_teams_distribute_simd:
  7326. case OMPD_target:
  7327. case OMPD_target_simd:
  7328. case OMPD_target_parallel:
  7329. case OMPD_cancel:
  7330. case OMPD_parallel:
  7331. case OMPD_parallel_sections:
  7332. case OMPD_threadprivate:
  7333. case OMPD_taskyield:
  7334. case OMPD_barrier:
  7335. case OMPD_taskwait:
  7336. case OMPD_cancellation_point:
  7337. case OMPD_flush:
  7338. case OMPD_declare_reduction:
  7339. case OMPD_declare_simd:
  7340. case OMPD_declare_target:
  7341. case OMPD_end_declare_target:
  7342. case OMPD_simd:
  7343. case OMPD_sections:
  7344. case OMPD_section:
  7345. case OMPD_single:
  7346. case OMPD_master:
  7347. case OMPD_critical:
  7348. case OMPD_taskgroup:
  7349. case OMPD_distribute:
  7350. case OMPD_ordered:
  7351. case OMPD_atomic:
  7352. case OMPD_distribute_simd:
  7353. case OMPD_target_teams:
  7354. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7355. case OMPD_unknown:
  7356. llvm_unreachable("Unknown OpenMP directive");
  7357. }
  7358. break;
  7359. case OMPC_dist_schedule:
  7360. switch (DKind) {
  7361. case OMPD_teams_distribute_parallel_for:
  7362. case OMPD_teams_distribute_parallel_for_simd:
  7363. case OMPD_teams_distribute:
  7364. case OMPD_teams_distribute_simd:
  7365. CaptureRegion = OMPD_teams;
  7366. break;
  7367. case OMPD_target_teams_distribute_parallel_for:
  7368. case OMPD_target_teams_distribute_parallel_for_simd:
  7369. case OMPD_target_teams_distribute:
  7370. case OMPD_target_teams_distribute_simd:
  7371. CaptureRegion = OMPD_target;
  7372. break;
  7373. case OMPD_distribute_parallel_for:
  7374. case OMPD_distribute_parallel_for_simd:
  7375. CaptureRegion = OMPD_parallel;
  7376. break;
  7377. case OMPD_distribute:
  7378. case OMPD_distribute_simd:
  7379. // Do not capture thread_limit-clause expressions.
  7380. break;
  7381. case OMPD_parallel_for:
  7382. case OMPD_parallel_for_simd:
  7383. case OMPD_target_parallel_for_simd:
  7384. case OMPD_target_parallel_for:
  7385. case OMPD_task:
  7386. case OMPD_taskloop:
  7387. case OMPD_taskloop_simd:
  7388. case OMPD_target_data:
  7389. case OMPD_target_enter_data:
  7390. case OMPD_target_exit_data:
  7391. case OMPD_target_update:
  7392. case OMPD_teams:
  7393. case OMPD_target:
  7394. case OMPD_target_simd:
  7395. case OMPD_target_parallel:
  7396. case OMPD_cancel:
  7397. case OMPD_parallel:
  7398. case OMPD_parallel_sections:
  7399. case OMPD_threadprivate:
  7400. case OMPD_taskyield:
  7401. case OMPD_barrier:
  7402. case OMPD_taskwait:
  7403. case OMPD_cancellation_point:
  7404. case OMPD_flush:
  7405. case OMPD_declare_reduction:
  7406. case OMPD_declare_simd:
  7407. case OMPD_declare_target:
  7408. case OMPD_end_declare_target:
  7409. case OMPD_simd:
  7410. case OMPD_for:
  7411. case OMPD_for_simd:
  7412. case OMPD_sections:
  7413. case OMPD_section:
  7414. case OMPD_single:
  7415. case OMPD_master:
  7416. case OMPD_critical:
  7417. case OMPD_taskgroup:
  7418. case OMPD_ordered:
  7419. case OMPD_atomic:
  7420. case OMPD_target_teams:
  7421. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7422. case OMPD_unknown:
  7423. llvm_unreachable("Unknown OpenMP directive");
  7424. }
  7425. break;
  7426. case OMPC_device:
  7427. switch (DKind) {
  7428. case OMPD_target_teams:
  7429. case OMPD_target_teams_distribute:
  7430. case OMPD_target_teams_distribute_simd:
  7431. case OMPD_target_teams_distribute_parallel_for:
  7432. case OMPD_target_teams_distribute_parallel_for_simd:
  7433. case OMPD_target_data:
  7434. case OMPD_target_enter_data:
  7435. case OMPD_target_exit_data:
  7436. case OMPD_target_update:
  7437. case OMPD_target:
  7438. case OMPD_target_simd:
  7439. case OMPD_target_parallel:
  7440. case OMPD_target_parallel_for:
  7441. case OMPD_target_parallel_for_simd:
  7442. // Do not capture device-clause expressions.
  7443. break;
  7444. case OMPD_teams_distribute_parallel_for:
  7445. case OMPD_teams_distribute_parallel_for_simd:
  7446. case OMPD_teams:
  7447. case OMPD_teams_distribute:
  7448. case OMPD_teams_distribute_simd:
  7449. case OMPD_distribute_parallel_for:
  7450. case OMPD_distribute_parallel_for_simd:
  7451. case OMPD_task:
  7452. case OMPD_taskloop:
  7453. case OMPD_taskloop_simd:
  7454. case OMPD_cancel:
  7455. case OMPD_parallel:
  7456. case OMPD_parallel_sections:
  7457. case OMPD_parallel_for:
  7458. case OMPD_parallel_for_simd:
  7459. case OMPD_threadprivate:
  7460. case OMPD_taskyield:
  7461. case OMPD_barrier:
  7462. case OMPD_taskwait:
  7463. case OMPD_cancellation_point:
  7464. case OMPD_flush:
  7465. case OMPD_declare_reduction:
  7466. case OMPD_declare_simd:
  7467. case OMPD_declare_target:
  7468. case OMPD_end_declare_target:
  7469. case OMPD_simd:
  7470. case OMPD_for:
  7471. case OMPD_for_simd:
  7472. case OMPD_sections:
  7473. case OMPD_section:
  7474. case OMPD_single:
  7475. case OMPD_master:
  7476. case OMPD_critical:
  7477. case OMPD_taskgroup:
  7478. case OMPD_distribute:
  7479. case OMPD_ordered:
  7480. case OMPD_atomic:
  7481. case OMPD_distribute_simd:
  7482. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7483. case OMPD_unknown:
  7484. llvm_unreachable("Unknown OpenMP directive");
  7485. }
  7486. break;
  7487. case OMPC_firstprivate:
  7488. case OMPC_lastprivate:
  7489. case OMPC_reduction:
  7490. case OMPC_task_reduction:
  7491. case OMPC_in_reduction:
  7492. case OMPC_linear:
  7493. case OMPC_default:
  7494. case OMPC_proc_bind:
  7495. case OMPC_final:
  7496. case OMPC_safelen:
  7497. case OMPC_simdlen:
  7498. case OMPC_collapse:
  7499. case OMPC_private:
  7500. case OMPC_shared:
  7501. case OMPC_aligned:
  7502. case OMPC_copyin:
  7503. case OMPC_copyprivate:
  7504. case OMPC_ordered:
  7505. case OMPC_nowait:
  7506. case OMPC_untied:
  7507. case OMPC_mergeable:
  7508. case OMPC_threadprivate:
  7509. case OMPC_flush:
  7510. case OMPC_read:
  7511. case OMPC_write:
  7512. case OMPC_update:
  7513. case OMPC_capture:
  7514. case OMPC_seq_cst:
  7515. case OMPC_depend:
  7516. case OMPC_threads:
  7517. case OMPC_simd:
  7518. case OMPC_map:
  7519. case OMPC_priority:
  7520. case OMPC_grainsize:
  7521. case OMPC_nogroup:
  7522. case OMPC_num_tasks:
  7523. case OMPC_hint:
  7524. case OMPC_defaultmap:
  7525. case OMPC_unknown:
  7526. case OMPC_uniform:
  7527. case OMPC_to:
  7528. case OMPC_from:
  7529. case OMPC_use_device_ptr:
  7530. case OMPC_is_device_ptr:
  7531. llvm_unreachable("Unexpected OpenMP clause.");
  7532. }
  7533. return CaptureRegion;
  7534. }
  7535. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7536. Expr *Condition, SourceLocation StartLoc,
  7537. SourceLocation LParenLoc,
  7538. SourceLocation NameModifierLoc,
  7539. SourceLocation ColonLoc,
  7540. SourceLocation EndLoc) {
  7541. Expr *ValExpr = Condition;
  7542. Stmt *HelperValStmt = nullptr;
  7543. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7544. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7545. !Condition->isInstantiationDependent() &&
  7546. !Condition->containsUnexpandedParameterPack()) {
  7547. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7548. if (Val.isInvalid())
  7549. return nullptr;
  7550. ValExpr = MakeFullExpr(Val.get()).get();
  7551. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7552. CaptureRegion =
  7553. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7554. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7555. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7556. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7557. HelperValStmt = buildPreInits(Context, Captures);
  7558. }
  7559. }
  7560. return new (Context)
  7561. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7562. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7563. }
  7564. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7565. SourceLocation StartLoc,
  7566. SourceLocation LParenLoc,
  7567. SourceLocation EndLoc) {
  7568. Expr *ValExpr = Condition;
  7569. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7570. !Condition->isInstantiationDependent() &&
  7571. !Condition->containsUnexpandedParameterPack()) {
  7572. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7573. if (Val.isInvalid())
  7574. return nullptr;
  7575. ValExpr = MakeFullExpr(Val.get()).get();
  7576. }
  7577. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7578. }
  7579. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7580. Expr *Op) {
  7581. if (!Op)
  7582. return ExprError();
  7583. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7584. public:
  7585. IntConvertDiagnoser()
  7586. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7587. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7588. QualType T) override {
  7589. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7590. }
  7591. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7592. QualType T) override {
  7593. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7594. }
  7595. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7596. QualType T,
  7597. QualType ConvTy) override {
  7598. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7599. }
  7600. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7601. QualType ConvTy) override {
  7602. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7603. << ConvTy->isEnumeralType() << ConvTy;
  7604. }
  7605. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7606. QualType T) override {
  7607. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7608. }
  7609. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7610. QualType ConvTy) override {
  7611. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7612. << ConvTy->isEnumeralType() << ConvTy;
  7613. }
  7614. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7615. QualType) override {
  7616. llvm_unreachable("conversion functions are permitted");
  7617. }
  7618. } ConvertDiagnoser;
  7619. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7620. }
  7621. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7622. OpenMPClauseKind CKind,
  7623. bool StrictlyPositive) {
  7624. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7625. !ValExpr->isInstantiationDependent()) {
  7626. SourceLocation Loc = ValExpr->getExprLoc();
  7627. ExprResult Value =
  7628. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7629. if (Value.isInvalid())
  7630. return false;
  7631. ValExpr = Value.get();
  7632. // The expression must evaluate to a non-negative integer value.
  7633. llvm::APSInt Result;
  7634. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7635. Result.isSigned() &&
  7636. !((!StrictlyPositive && Result.isNonNegative()) ||
  7637. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7638. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7639. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7640. << ValExpr->getSourceRange();
  7641. return false;
  7642. }
  7643. }
  7644. return true;
  7645. }
  7646. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7647. SourceLocation StartLoc,
  7648. SourceLocation LParenLoc,
  7649. SourceLocation EndLoc) {
  7650. Expr *ValExpr = NumThreads;
  7651. Stmt *HelperValStmt = nullptr;
  7652. // OpenMP [2.5, Restrictions]
  7653. // The num_threads expression must evaluate to a positive integer value.
  7654. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7655. /*StrictlyPositive=*/true))
  7656. return nullptr;
  7657. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7658. OpenMPDirectiveKind CaptureRegion =
  7659. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7660. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7661. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7662. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7663. HelperValStmt = buildPreInits(Context, Captures);
  7664. }
  7665. return new (Context) OMPNumThreadsClause(
  7666. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7667. }
  7668. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7669. OpenMPClauseKind CKind,
  7670. bool StrictlyPositive) {
  7671. if (!E)
  7672. return ExprError();
  7673. if (E->isValueDependent() || E->isTypeDependent() ||
  7674. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7675. return E;
  7676. llvm::APSInt Result;
  7677. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7678. if (ICE.isInvalid())
  7679. return ExprError();
  7680. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7681. (!StrictlyPositive && !Result.isNonNegative())) {
  7682. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7683. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7684. << E->getSourceRange();
  7685. return ExprError();
  7686. }
  7687. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7688. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7689. << E->getSourceRange();
  7690. return ExprError();
  7691. }
  7692. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7693. DSAStack->setAssociatedLoops(Result.getExtValue());
  7694. else if (CKind == OMPC_ordered)
  7695. DSAStack->setAssociatedLoops(Result.getExtValue());
  7696. return ICE;
  7697. }
  7698. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7699. SourceLocation LParenLoc,
  7700. SourceLocation EndLoc) {
  7701. // OpenMP [2.8.1, simd construct, Description]
  7702. // The parameter of the safelen clause must be a constant
  7703. // positive integer expression.
  7704. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7705. if (Safelen.isInvalid())
  7706. return nullptr;
  7707. return new (Context)
  7708. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7709. }
  7710. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  7711. SourceLocation LParenLoc,
  7712. SourceLocation EndLoc) {
  7713. // OpenMP [2.8.1, simd construct, Description]
  7714. // The parameter of the simdlen clause must be a constant
  7715. // positive integer expression.
  7716. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  7717. if (Simdlen.isInvalid())
  7718. return nullptr;
  7719. return new (Context)
  7720. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  7721. }
  7722. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  7723. SourceLocation StartLoc,
  7724. SourceLocation LParenLoc,
  7725. SourceLocation EndLoc) {
  7726. // OpenMP [2.7.1, loop construct, Description]
  7727. // OpenMP [2.8.1, simd construct, Description]
  7728. // OpenMP [2.9.6, distribute construct, Description]
  7729. // The parameter of the collapse clause must be a constant
  7730. // positive integer expression.
  7731. ExprResult NumForLoopsResult =
  7732. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  7733. if (NumForLoopsResult.isInvalid())
  7734. return nullptr;
  7735. return new (Context)
  7736. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  7737. }
  7738. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  7739. SourceLocation EndLoc,
  7740. SourceLocation LParenLoc,
  7741. Expr *NumForLoops) {
  7742. // OpenMP [2.7.1, loop construct, Description]
  7743. // OpenMP [2.8.1, simd construct, Description]
  7744. // OpenMP [2.9.6, distribute construct, Description]
  7745. // The parameter of the ordered clause must be a constant
  7746. // positive integer expression if any.
  7747. if (NumForLoops && LParenLoc.isValid()) {
  7748. ExprResult NumForLoopsResult =
  7749. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  7750. if (NumForLoopsResult.isInvalid())
  7751. return nullptr;
  7752. NumForLoops = NumForLoopsResult.get();
  7753. } else
  7754. NumForLoops = nullptr;
  7755. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  7756. return new (Context)
  7757. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  7758. }
  7759. OMPClause *Sema::ActOnOpenMPSimpleClause(
  7760. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  7761. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  7762. OMPClause *Res = nullptr;
  7763. switch (Kind) {
  7764. case OMPC_default:
  7765. Res =
  7766. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  7767. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  7768. break;
  7769. case OMPC_proc_bind:
  7770. Res = ActOnOpenMPProcBindClause(
  7771. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  7772. LParenLoc, EndLoc);
  7773. break;
  7774. case OMPC_if:
  7775. case OMPC_final:
  7776. case OMPC_num_threads:
  7777. case OMPC_safelen:
  7778. case OMPC_simdlen:
  7779. case OMPC_collapse:
  7780. case OMPC_schedule:
  7781. case OMPC_private:
  7782. case OMPC_firstprivate:
  7783. case OMPC_lastprivate:
  7784. case OMPC_shared:
  7785. case OMPC_reduction:
  7786. case OMPC_task_reduction:
  7787. case OMPC_in_reduction:
  7788. case OMPC_linear:
  7789. case OMPC_aligned:
  7790. case OMPC_copyin:
  7791. case OMPC_copyprivate:
  7792. case OMPC_ordered:
  7793. case OMPC_nowait:
  7794. case OMPC_untied:
  7795. case OMPC_mergeable:
  7796. case OMPC_threadprivate:
  7797. case OMPC_flush:
  7798. case OMPC_read:
  7799. case OMPC_write:
  7800. case OMPC_update:
  7801. case OMPC_capture:
  7802. case OMPC_seq_cst:
  7803. case OMPC_depend:
  7804. case OMPC_device:
  7805. case OMPC_threads:
  7806. case OMPC_simd:
  7807. case OMPC_map:
  7808. case OMPC_num_teams:
  7809. case OMPC_thread_limit:
  7810. case OMPC_priority:
  7811. case OMPC_grainsize:
  7812. case OMPC_nogroup:
  7813. case OMPC_num_tasks:
  7814. case OMPC_hint:
  7815. case OMPC_dist_schedule:
  7816. case OMPC_defaultmap:
  7817. case OMPC_unknown:
  7818. case OMPC_uniform:
  7819. case OMPC_to:
  7820. case OMPC_from:
  7821. case OMPC_use_device_ptr:
  7822. case OMPC_is_device_ptr:
  7823. llvm_unreachable("Clause is not allowed.");
  7824. }
  7825. return Res;
  7826. }
  7827. static std::string
  7828. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  7829. ArrayRef<unsigned> Exclude = llvm::None) {
  7830. std::string Values;
  7831. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  7832. unsigned Skipped = Exclude.size();
  7833. auto S = Exclude.begin(), E = Exclude.end();
  7834. for (unsigned i = First; i < Last; ++i) {
  7835. if (std::find(S, E, i) != E) {
  7836. --Skipped;
  7837. continue;
  7838. }
  7839. Values += "'";
  7840. Values += getOpenMPSimpleClauseTypeName(K, i);
  7841. Values += "'";
  7842. if (i == Bound - Skipped)
  7843. Values += " or ";
  7844. else if (i != Bound + 1 - Skipped)
  7845. Values += ", ";
  7846. }
  7847. return Values;
  7848. }
  7849. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  7850. SourceLocation KindKwLoc,
  7851. SourceLocation StartLoc,
  7852. SourceLocation LParenLoc,
  7853. SourceLocation EndLoc) {
  7854. if (Kind == OMPC_DEFAULT_unknown) {
  7855. static_assert(OMPC_DEFAULT_unknown > 0,
  7856. "OMPC_DEFAULT_unknown not greater than 0");
  7857. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7858. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  7859. /*Last=*/OMPC_DEFAULT_unknown)
  7860. << getOpenMPClauseName(OMPC_default);
  7861. return nullptr;
  7862. }
  7863. switch (Kind) {
  7864. case OMPC_DEFAULT_none:
  7865. DSAStack->setDefaultDSANone(KindKwLoc);
  7866. break;
  7867. case OMPC_DEFAULT_shared:
  7868. DSAStack->setDefaultDSAShared(KindKwLoc);
  7869. break;
  7870. case OMPC_DEFAULT_unknown:
  7871. llvm_unreachable("Clause kind is not allowed.");
  7872. break;
  7873. }
  7874. return new (Context)
  7875. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7876. }
  7877. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  7878. SourceLocation KindKwLoc,
  7879. SourceLocation StartLoc,
  7880. SourceLocation LParenLoc,
  7881. SourceLocation EndLoc) {
  7882. if (Kind == OMPC_PROC_BIND_unknown) {
  7883. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7884. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  7885. /*Last=*/OMPC_PROC_BIND_unknown)
  7886. << getOpenMPClauseName(OMPC_proc_bind);
  7887. return nullptr;
  7888. }
  7889. return new (Context)
  7890. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7891. }
  7892. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  7893. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  7894. SourceLocation StartLoc, SourceLocation LParenLoc,
  7895. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  7896. SourceLocation EndLoc) {
  7897. OMPClause *Res = nullptr;
  7898. switch (Kind) {
  7899. case OMPC_schedule:
  7900. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  7901. assert(Argument.size() == NumberOfElements &&
  7902. ArgumentLoc.size() == NumberOfElements);
  7903. Res = ActOnOpenMPScheduleClause(
  7904. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  7905. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  7906. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  7907. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  7908. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  7909. break;
  7910. case OMPC_if:
  7911. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  7912. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  7913. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  7914. DelimLoc, EndLoc);
  7915. break;
  7916. case OMPC_dist_schedule:
  7917. Res = ActOnOpenMPDistScheduleClause(
  7918. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  7919. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  7920. break;
  7921. case OMPC_defaultmap:
  7922. enum { Modifier, DefaultmapKind };
  7923. Res = ActOnOpenMPDefaultmapClause(
  7924. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  7925. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  7926. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  7927. EndLoc);
  7928. break;
  7929. case OMPC_final:
  7930. case OMPC_num_threads:
  7931. case OMPC_safelen:
  7932. case OMPC_simdlen:
  7933. case OMPC_collapse:
  7934. case OMPC_default:
  7935. case OMPC_proc_bind:
  7936. case OMPC_private:
  7937. case OMPC_firstprivate:
  7938. case OMPC_lastprivate:
  7939. case OMPC_shared:
  7940. case OMPC_reduction:
  7941. case OMPC_task_reduction:
  7942. case OMPC_in_reduction:
  7943. case OMPC_linear:
  7944. case OMPC_aligned:
  7945. case OMPC_copyin:
  7946. case OMPC_copyprivate:
  7947. case OMPC_ordered:
  7948. case OMPC_nowait:
  7949. case OMPC_untied:
  7950. case OMPC_mergeable:
  7951. case OMPC_threadprivate:
  7952. case OMPC_flush:
  7953. case OMPC_read:
  7954. case OMPC_write:
  7955. case OMPC_update:
  7956. case OMPC_capture:
  7957. case OMPC_seq_cst:
  7958. case OMPC_depend:
  7959. case OMPC_device:
  7960. case OMPC_threads:
  7961. case OMPC_simd:
  7962. case OMPC_map:
  7963. case OMPC_num_teams:
  7964. case OMPC_thread_limit:
  7965. case OMPC_priority:
  7966. case OMPC_grainsize:
  7967. case OMPC_nogroup:
  7968. case OMPC_num_tasks:
  7969. case OMPC_hint:
  7970. case OMPC_unknown:
  7971. case OMPC_uniform:
  7972. case OMPC_to:
  7973. case OMPC_from:
  7974. case OMPC_use_device_ptr:
  7975. case OMPC_is_device_ptr:
  7976. llvm_unreachable("Clause is not allowed.");
  7977. }
  7978. return Res;
  7979. }
  7980. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  7981. OpenMPScheduleClauseModifier M2,
  7982. SourceLocation M1Loc, SourceLocation M2Loc) {
  7983. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  7984. SmallVector<unsigned, 2> Excluded;
  7985. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  7986. Excluded.push_back(M2);
  7987. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  7988. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  7989. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  7990. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  7991. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  7992. << getListOfPossibleValues(OMPC_schedule,
  7993. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  7994. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  7995. Excluded)
  7996. << getOpenMPClauseName(OMPC_schedule);
  7997. return true;
  7998. }
  7999. return false;
  8000. }
  8001. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8002. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8003. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8004. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8005. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8006. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8007. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8008. return nullptr;
  8009. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8010. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8011. // but not both.
  8012. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8013. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8014. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8015. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8016. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8017. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8018. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8019. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8020. return nullptr;
  8021. }
  8022. if (Kind == OMPC_SCHEDULE_unknown) {
  8023. std::string Values;
  8024. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8025. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8026. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8027. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8028. Exclude);
  8029. } else {
  8030. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8031. /*Last=*/OMPC_SCHEDULE_unknown);
  8032. }
  8033. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8034. << Values << getOpenMPClauseName(OMPC_schedule);
  8035. return nullptr;
  8036. }
  8037. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8038. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8039. // schedule(guided).
  8040. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8041. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8042. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8043. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8044. diag::err_omp_schedule_nonmonotonic_static);
  8045. return nullptr;
  8046. }
  8047. Expr *ValExpr = ChunkSize;
  8048. Stmt *HelperValStmt = nullptr;
  8049. if (ChunkSize) {
  8050. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8051. !ChunkSize->isInstantiationDependent() &&
  8052. !ChunkSize->containsUnexpandedParameterPack()) {
  8053. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8054. ExprResult Val =
  8055. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8056. if (Val.isInvalid())
  8057. return nullptr;
  8058. ValExpr = Val.get();
  8059. // OpenMP [2.7.1, Restrictions]
  8060. // chunk_size must be a loop invariant integer expression with a positive
  8061. // value.
  8062. llvm::APSInt Result;
  8063. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8064. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8065. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8066. << "schedule" << 1 << ChunkSize->getSourceRange();
  8067. return nullptr;
  8068. }
  8069. } else if (getOpenMPCaptureRegionForClause(
  8070. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8071. OMPD_unknown &&
  8072. !CurContext->isDependentContext()) {
  8073. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  8074. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8075. HelperValStmt = buildPreInits(Context, Captures);
  8076. }
  8077. }
  8078. }
  8079. return new (Context)
  8080. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8081. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8082. }
  8083. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8084. SourceLocation StartLoc,
  8085. SourceLocation EndLoc) {
  8086. OMPClause *Res = nullptr;
  8087. switch (Kind) {
  8088. case OMPC_ordered:
  8089. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8090. break;
  8091. case OMPC_nowait:
  8092. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8093. break;
  8094. case OMPC_untied:
  8095. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8096. break;
  8097. case OMPC_mergeable:
  8098. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8099. break;
  8100. case OMPC_read:
  8101. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8102. break;
  8103. case OMPC_write:
  8104. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8105. break;
  8106. case OMPC_update:
  8107. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8108. break;
  8109. case OMPC_capture:
  8110. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8111. break;
  8112. case OMPC_seq_cst:
  8113. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8114. break;
  8115. case OMPC_threads:
  8116. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8117. break;
  8118. case OMPC_simd:
  8119. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8120. break;
  8121. case OMPC_nogroup:
  8122. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8123. break;
  8124. case OMPC_if:
  8125. case OMPC_final:
  8126. case OMPC_num_threads:
  8127. case OMPC_safelen:
  8128. case OMPC_simdlen:
  8129. case OMPC_collapse:
  8130. case OMPC_schedule:
  8131. case OMPC_private:
  8132. case OMPC_firstprivate:
  8133. case OMPC_lastprivate:
  8134. case OMPC_shared:
  8135. case OMPC_reduction:
  8136. case OMPC_task_reduction:
  8137. case OMPC_in_reduction:
  8138. case OMPC_linear:
  8139. case OMPC_aligned:
  8140. case OMPC_copyin:
  8141. case OMPC_copyprivate:
  8142. case OMPC_default:
  8143. case OMPC_proc_bind:
  8144. case OMPC_threadprivate:
  8145. case OMPC_flush:
  8146. case OMPC_depend:
  8147. case OMPC_device:
  8148. case OMPC_map:
  8149. case OMPC_num_teams:
  8150. case OMPC_thread_limit:
  8151. case OMPC_priority:
  8152. case OMPC_grainsize:
  8153. case OMPC_num_tasks:
  8154. case OMPC_hint:
  8155. case OMPC_dist_schedule:
  8156. case OMPC_defaultmap:
  8157. case OMPC_unknown:
  8158. case OMPC_uniform:
  8159. case OMPC_to:
  8160. case OMPC_from:
  8161. case OMPC_use_device_ptr:
  8162. case OMPC_is_device_ptr:
  8163. llvm_unreachable("Clause is not allowed.");
  8164. }
  8165. return Res;
  8166. }
  8167. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8168. SourceLocation EndLoc) {
  8169. DSAStack->setNowaitRegion();
  8170. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8171. }
  8172. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8173. SourceLocation EndLoc) {
  8174. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8175. }
  8176. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8177. SourceLocation EndLoc) {
  8178. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8179. }
  8180. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8181. SourceLocation EndLoc) {
  8182. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8183. }
  8184. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8185. SourceLocation EndLoc) {
  8186. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8187. }
  8188. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8189. SourceLocation EndLoc) {
  8190. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8191. }
  8192. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8193. SourceLocation EndLoc) {
  8194. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8195. }
  8196. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8197. SourceLocation EndLoc) {
  8198. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8199. }
  8200. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8201. SourceLocation EndLoc) {
  8202. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8203. }
  8204. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8205. SourceLocation EndLoc) {
  8206. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8207. }
  8208. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8209. SourceLocation EndLoc) {
  8210. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8211. }
  8212. OMPClause *Sema::ActOnOpenMPVarListClause(
  8213. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8214. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8215. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8216. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8217. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8218. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8219. SourceLocation DepLinMapLoc) {
  8220. OMPClause *Res = nullptr;
  8221. switch (Kind) {
  8222. case OMPC_private:
  8223. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8224. break;
  8225. case OMPC_firstprivate:
  8226. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8227. break;
  8228. case OMPC_lastprivate:
  8229. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8230. break;
  8231. case OMPC_shared:
  8232. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8233. break;
  8234. case OMPC_reduction:
  8235. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8236. EndLoc, ReductionIdScopeSpec, ReductionId);
  8237. break;
  8238. case OMPC_task_reduction:
  8239. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8240. EndLoc, ReductionIdScopeSpec,
  8241. ReductionId);
  8242. break;
  8243. case OMPC_in_reduction:
  8244. Res =
  8245. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8246. EndLoc, ReductionIdScopeSpec, ReductionId);
  8247. break;
  8248. case OMPC_linear:
  8249. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8250. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8251. break;
  8252. case OMPC_aligned:
  8253. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8254. ColonLoc, EndLoc);
  8255. break;
  8256. case OMPC_copyin:
  8257. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8258. break;
  8259. case OMPC_copyprivate:
  8260. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8261. break;
  8262. case OMPC_flush:
  8263. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8264. break;
  8265. case OMPC_depend:
  8266. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8267. StartLoc, LParenLoc, EndLoc);
  8268. break;
  8269. case OMPC_map:
  8270. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8271. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8272. LParenLoc, EndLoc);
  8273. break;
  8274. case OMPC_to:
  8275. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8276. break;
  8277. case OMPC_from:
  8278. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8279. break;
  8280. case OMPC_use_device_ptr:
  8281. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8282. break;
  8283. case OMPC_is_device_ptr:
  8284. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8285. break;
  8286. case OMPC_if:
  8287. case OMPC_final:
  8288. case OMPC_num_threads:
  8289. case OMPC_safelen:
  8290. case OMPC_simdlen:
  8291. case OMPC_collapse:
  8292. case OMPC_default:
  8293. case OMPC_proc_bind:
  8294. case OMPC_schedule:
  8295. case OMPC_ordered:
  8296. case OMPC_nowait:
  8297. case OMPC_untied:
  8298. case OMPC_mergeable:
  8299. case OMPC_threadprivate:
  8300. case OMPC_read:
  8301. case OMPC_write:
  8302. case OMPC_update:
  8303. case OMPC_capture:
  8304. case OMPC_seq_cst:
  8305. case OMPC_device:
  8306. case OMPC_threads:
  8307. case OMPC_simd:
  8308. case OMPC_num_teams:
  8309. case OMPC_thread_limit:
  8310. case OMPC_priority:
  8311. case OMPC_grainsize:
  8312. case OMPC_nogroup:
  8313. case OMPC_num_tasks:
  8314. case OMPC_hint:
  8315. case OMPC_dist_schedule:
  8316. case OMPC_defaultmap:
  8317. case OMPC_unknown:
  8318. case OMPC_uniform:
  8319. llvm_unreachable("Clause is not allowed.");
  8320. }
  8321. return Res;
  8322. }
  8323. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8324. ExprObjectKind OK, SourceLocation Loc) {
  8325. ExprResult Res = BuildDeclRefExpr(
  8326. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8327. if (!Res.isUsable())
  8328. return ExprError();
  8329. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8330. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8331. if (!Res.isUsable())
  8332. return ExprError();
  8333. }
  8334. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8335. Res = DefaultLvalueConversion(Res.get());
  8336. if (!Res.isUsable())
  8337. return ExprError();
  8338. }
  8339. return Res;
  8340. }
  8341. static std::pair<ValueDecl *, bool>
  8342. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8343. SourceRange &ERange, bool AllowArraySection = false) {
  8344. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8345. RefExpr->containsUnexpandedParameterPack())
  8346. return std::make_pair(nullptr, true);
  8347. // OpenMP [3.1, C/C++]
  8348. // A list item is a variable name.
  8349. // OpenMP [2.9.3.3, Restrictions, p.1]
  8350. // A variable that is part of another variable (as an array or
  8351. // structure element) cannot appear in a private clause.
  8352. RefExpr = RefExpr->IgnoreParens();
  8353. enum {
  8354. NoArrayExpr = -1,
  8355. ArraySubscript = 0,
  8356. OMPArraySection = 1
  8357. } IsArrayExpr = NoArrayExpr;
  8358. if (AllowArraySection) {
  8359. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  8360. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  8361. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8362. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8363. RefExpr = Base;
  8364. IsArrayExpr = ArraySubscript;
  8365. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  8366. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  8367. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  8368. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8369. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8370. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8371. RefExpr = Base;
  8372. IsArrayExpr = OMPArraySection;
  8373. }
  8374. }
  8375. ELoc = RefExpr->getExprLoc();
  8376. ERange = RefExpr->getSourceRange();
  8377. RefExpr = RefExpr->IgnoreParenImpCasts();
  8378. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  8379. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  8380. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  8381. (S.getCurrentThisType().isNull() || !ME ||
  8382. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  8383. !isa<FieldDecl>(ME->getMemberDecl()))) {
  8384. if (IsArrayExpr != NoArrayExpr)
  8385. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  8386. << ERange;
  8387. else {
  8388. S.Diag(ELoc,
  8389. AllowArraySection
  8390. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  8391. : diag::err_omp_expected_var_name_member_expr)
  8392. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  8393. }
  8394. return std::make_pair(nullptr, false);
  8395. }
  8396. return std::make_pair(
  8397. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  8398. }
  8399. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  8400. SourceLocation StartLoc,
  8401. SourceLocation LParenLoc,
  8402. SourceLocation EndLoc) {
  8403. SmallVector<Expr *, 8> Vars;
  8404. SmallVector<Expr *, 8> PrivateCopies;
  8405. for (auto &RefExpr : VarList) {
  8406. assert(RefExpr && "NULL expr in OpenMP private clause.");
  8407. SourceLocation ELoc;
  8408. SourceRange ERange;
  8409. Expr *SimpleRefExpr = RefExpr;
  8410. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8411. if (Res.second) {
  8412. // It will be analyzed later.
  8413. Vars.push_back(RefExpr);
  8414. PrivateCopies.push_back(nullptr);
  8415. }
  8416. ValueDecl *D = Res.first;
  8417. if (!D)
  8418. continue;
  8419. QualType Type = D->getType();
  8420. auto *VD = dyn_cast<VarDecl>(D);
  8421. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8422. // A variable that appears in a private clause must not have an incomplete
  8423. // type or a reference type.
  8424. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  8425. continue;
  8426. Type = Type.getNonReferenceType();
  8427. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8428. // in a Construct]
  8429. // Variables with the predetermined data-sharing attributes may not be
  8430. // listed in data-sharing attributes clauses, except for the cases
  8431. // listed below. For these exceptions only, listing a predetermined
  8432. // variable in a data-sharing attribute clause is allowed and overrides
  8433. // the variable's predetermined data-sharing attributes.
  8434. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8435. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  8436. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8437. << getOpenMPClauseName(OMPC_private);
  8438. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8439. continue;
  8440. }
  8441. auto CurrDir = DSAStack->getCurrentDirective();
  8442. // Variably modified types are not supported for tasks.
  8443. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8444. isOpenMPTaskingDirective(CurrDir)) {
  8445. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8446. << getOpenMPClauseName(OMPC_private) << Type
  8447. << getOpenMPDirectiveName(CurrDir);
  8448. bool IsDecl =
  8449. !VD ||
  8450. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8451. Diag(D->getLocation(),
  8452. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8453. << D;
  8454. continue;
  8455. }
  8456. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8457. // A list item cannot appear in both a map clause and a data-sharing
  8458. // attribute clause on the same construct
  8459. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  8460. CurrDir == OMPD_target_teams ||
  8461. CurrDir == OMPD_target_teams_distribute ||
  8462. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  8463. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  8464. CurrDir == OMPD_target_teams_distribute_simd ||
  8465. CurrDir == OMPD_target_parallel_for_simd ||
  8466. CurrDir == OMPD_target_parallel_for) {
  8467. OpenMPClauseKind ConflictKind;
  8468. if (DSAStack->checkMappableExprComponentListsForDecl(
  8469. VD, /*CurrentRegionOnly=*/true,
  8470. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8471. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8472. ConflictKind = WhereFoundClauseKind;
  8473. return true;
  8474. })) {
  8475. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8476. << getOpenMPClauseName(OMPC_private)
  8477. << getOpenMPClauseName(ConflictKind)
  8478. << getOpenMPDirectiveName(CurrDir);
  8479. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8480. continue;
  8481. }
  8482. }
  8483. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8484. // A variable of class type (or array thereof) that appears in a private
  8485. // clause requires an accessible, unambiguous default constructor for the
  8486. // class type.
  8487. // Generate helper private variable and initialize it with the default
  8488. // value. The address of the original variable is replaced by the address of
  8489. // the new private variable in CodeGen. This new variable is not added to
  8490. // IdResolver, so the code in the OpenMP region uses original variable for
  8491. // proper diagnostics.
  8492. Type = Type.getUnqualifiedType();
  8493. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8494. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8495. ActOnUninitializedDecl(VDPrivate);
  8496. if (VDPrivate->isInvalidDecl())
  8497. continue;
  8498. auto VDPrivateRefExpr = buildDeclRefExpr(
  8499. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8500. DeclRefExpr *Ref = nullptr;
  8501. if (!VD && !CurContext->isDependentContext())
  8502. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8503. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8504. Vars.push_back((VD || CurContext->isDependentContext())
  8505. ? RefExpr->IgnoreParens()
  8506. : Ref);
  8507. PrivateCopies.push_back(VDPrivateRefExpr);
  8508. }
  8509. if (Vars.empty())
  8510. return nullptr;
  8511. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8512. PrivateCopies);
  8513. }
  8514. namespace {
  8515. class DiagsUninitializedSeveretyRAII {
  8516. private:
  8517. DiagnosticsEngine &Diags;
  8518. SourceLocation SavedLoc;
  8519. bool IsIgnored;
  8520. public:
  8521. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8522. bool IsIgnored)
  8523. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8524. if (!IsIgnored) {
  8525. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8526. /*Map*/ diag::Severity::Ignored, Loc);
  8527. }
  8528. }
  8529. ~DiagsUninitializedSeveretyRAII() {
  8530. if (!IsIgnored)
  8531. Diags.popMappings(SavedLoc);
  8532. }
  8533. };
  8534. }
  8535. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8536. SourceLocation StartLoc,
  8537. SourceLocation LParenLoc,
  8538. SourceLocation EndLoc) {
  8539. SmallVector<Expr *, 8> Vars;
  8540. SmallVector<Expr *, 8> PrivateCopies;
  8541. SmallVector<Expr *, 8> Inits;
  8542. SmallVector<Decl *, 4> ExprCaptures;
  8543. bool IsImplicitClause =
  8544. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8545. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  8546. for (auto &RefExpr : VarList) {
  8547. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8548. SourceLocation ELoc;
  8549. SourceRange ERange;
  8550. Expr *SimpleRefExpr = RefExpr;
  8551. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8552. if (Res.second) {
  8553. // It will be analyzed later.
  8554. Vars.push_back(RefExpr);
  8555. PrivateCopies.push_back(nullptr);
  8556. Inits.push_back(nullptr);
  8557. }
  8558. ValueDecl *D = Res.first;
  8559. if (!D)
  8560. continue;
  8561. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8562. QualType Type = D->getType();
  8563. auto *VD = dyn_cast<VarDecl>(D);
  8564. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8565. // A variable that appears in a private clause must not have an incomplete
  8566. // type or a reference type.
  8567. if (RequireCompleteType(ELoc, Type,
  8568. diag::err_omp_firstprivate_incomplete_type))
  8569. continue;
  8570. Type = Type.getNonReferenceType();
  8571. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8572. // A variable of class type (or array thereof) that appears in a private
  8573. // clause requires an accessible, unambiguous copy constructor for the
  8574. // class type.
  8575. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8576. // If an implicit firstprivate variable found it was checked already.
  8577. DSAStackTy::DSAVarData TopDVar;
  8578. if (!IsImplicitClause) {
  8579. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8580. TopDVar = DVar;
  8581. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8582. bool IsConstant = ElemType.isConstant(Context);
  8583. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8584. // A list item that specifies a given variable may not appear in more
  8585. // than one clause on the same directive, except that a variable may be
  8586. // specified in both firstprivate and lastprivate clauses.
  8587. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8588. // A list item may appear in a firstprivate or lastprivate clause but not
  8589. // both.
  8590. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8591. (isOpenMPDistributeDirective(CurrDir) ||
  8592. DVar.CKind != OMPC_lastprivate) &&
  8593. DVar.RefExpr) {
  8594. Diag(ELoc, diag::err_omp_wrong_dsa)
  8595. << getOpenMPClauseName(DVar.CKind)
  8596. << getOpenMPClauseName(OMPC_firstprivate);
  8597. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8598. continue;
  8599. }
  8600. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8601. // in a Construct]
  8602. // Variables with the predetermined data-sharing attributes may not be
  8603. // listed in data-sharing attributes clauses, except for the cases
  8604. // listed below. For these exceptions only, listing a predetermined
  8605. // variable in a data-sharing attribute clause is allowed and overrides
  8606. // the variable's predetermined data-sharing attributes.
  8607. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8608. // in a Construct, C/C++, p.2]
  8609. // Variables with const-qualified type having no mutable member may be
  8610. // listed in a firstprivate clause, even if they are static data members.
  8611. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8612. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8613. Diag(ELoc, diag::err_omp_wrong_dsa)
  8614. << getOpenMPClauseName(DVar.CKind)
  8615. << getOpenMPClauseName(OMPC_firstprivate);
  8616. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8617. continue;
  8618. }
  8619. // OpenMP [2.9.3.4, Restrictions, p.2]
  8620. // A list item that is private within a parallel region must not appear
  8621. // in a firstprivate clause on a worksharing construct if any of the
  8622. // worksharing regions arising from the worksharing construct ever bind
  8623. // to any of the parallel regions arising from the parallel construct.
  8624. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8625. // A list item that is private within a teams region must not appear in a
  8626. // firstprivate clause on a distribute construct if any of the distribute
  8627. // regions arising from the distribute construct ever bind to any of the
  8628. // teams regions arising from the teams construct.
  8629. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8630. // A list item that appears in a reduction clause of a teams construct
  8631. // must not appear in a firstprivate clause on a distribute construct if
  8632. // any of the distribute regions arising from the distribute construct
  8633. // ever bind to any of the teams regions arising from the teams construct.
  8634. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8635. isOpenMPDistributeDirective(CurrDir)) &&
  8636. !isOpenMPParallelDirective(CurrDir) &&
  8637. !isOpenMPTeamsDirective(CurrDir)) {
  8638. DVar = DSAStack->getImplicitDSA(D, true);
  8639. if (DVar.CKind != OMPC_shared &&
  8640. (isOpenMPParallelDirective(DVar.DKind) ||
  8641. isOpenMPTeamsDirective(DVar.DKind) ||
  8642. DVar.DKind == OMPD_unknown)) {
  8643. Diag(ELoc, diag::err_omp_required_access)
  8644. << getOpenMPClauseName(OMPC_firstprivate)
  8645. << getOpenMPClauseName(OMPC_shared);
  8646. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8647. continue;
  8648. }
  8649. }
  8650. // OpenMP [2.9.3.4, Restrictions, p.3]
  8651. // A list item that appears in a reduction clause of a parallel construct
  8652. // must not appear in a firstprivate clause on a worksharing or task
  8653. // construct if any of the worksharing or task regions arising from the
  8654. // worksharing or task construct ever bind to any of the parallel regions
  8655. // arising from the parallel construct.
  8656. // OpenMP [2.9.3.4, Restrictions, p.4]
  8657. // A list item that appears in a reduction clause in worksharing
  8658. // construct must not appear in a firstprivate clause in a task construct
  8659. // encountered during execution of any of the worksharing regions arising
  8660. // from the worksharing construct.
  8661. if (isOpenMPTaskingDirective(CurrDir)) {
  8662. DVar = DSAStack->hasInnermostDSA(
  8663. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  8664. [](OpenMPDirectiveKind K) -> bool {
  8665. return isOpenMPParallelDirective(K) ||
  8666. isOpenMPWorksharingDirective(K) ||
  8667. isOpenMPTeamsDirective(K);
  8668. },
  8669. /*FromParent=*/true);
  8670. if (DVar.CKind == OMPC_reduction &&
  8671. (isOpenMPParallelDirective(DVar.DKind) ||
  8672. isOpenMPWorksharingDirective(DVar.DKind) ||
  8673. isOpenMPTeamsDirective(DVar.DKind))) {
  8674. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8675. << getOpenMPDirectiveName(DVar.DKind);
  8676. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8677. continue;
  8678. }
  8679. }
  8680. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8681. // A list item cannot appear in both a map clause and a data-sharing
  8682. // attribute clause on the same construct
  8683. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8684. OpenMPClauseKind ConflictKind;
  8685. if (DSAStack->checkMappableExprComponentListsForDecl(
  8686. VD, /*CurrentRegionOnly=*/true,
  8687. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8688. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8689. ConflictKind = WhereFoundClauseKind;
  8690. return true;
  8691. })) {
  8692. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8693. << getOpenMPClauseName(OMPC_firstprivate)
  8694. << getOpenMPClauseName(ConflictKind)
  8695. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8696. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8697. continue;
  8698. }
  8699. }
  8700. }
  8701. // Variably modified types are not supported for tasks.
  8702. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8703. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8704. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8705. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8706. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8707. bool IsDecl =
  8708. !VD ||
  8709. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8710. Diag(D->getLocation(),
  8711. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8712. << D;
  8713. continue;
  8714. }
  8715. Type = Type.getUnqualifiedType();
  8716. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8717. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8718. // Generate helper private variable and initialize it with the value of the
  8719. // original variable. The address of the original variable is replaced by
  8720. // the address of the new private variable in the CodeGen. This new variable
  8721. // is not added to IdResolver, so the code in the OpenMP region uses
  8722. // original variable for proper diagnostics and variable capturing.
  8723. Expr *VDInitRefExpr = nullptr;
  8724. // For arrays generate initializer for single element and replace it by the
  8725. // original array element in CodeGen.
  8726. if (Type->isArrayType()) {
  8727. auto VDInit =
  8728. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  8729. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  8730. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  8731. ElemType = ElemType.getUnqualifiedType();
  8732. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  8733. ".firstprivate.temp");
  8734. InitializedEntity Entity =
  8735. InitializedEntity::InitializeVariable(VDInitTemp);
  8736. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  8737. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  8738. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  8739. if (Result.isInvalid())
  8740. VDPrivate->setInvalidDecl();
  8741. else
  8742. VDPrivate->setInit(Result.getAs<Expr>());
  8743. // Remove temp variable declaration.
  8744. Context.Deallocate(VDInitTemp);
  8745. } else {
  8746. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  8747. ".firstprivate.temp");
  8748. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  8749. RefExpr->getExprLoc());
  8750. AddInitializerToDecl(VDPrivate,
  8751. DefaultLvalueConversion(VDInitRefExpr).get(),
  8752. /*DirectInit=*/false);
  8753. }
  8754. if (VDPrivate->isInvalidDecl()) {
  8755. if (IsImplicitClause) {
  8756. Diag(RefExpr->getExprLoc(),
  8757. diag::note_omp_task_predetermined_firstprivate_here);
  8758. }
  8759. continue;
  8760. }
  8761. CurContext->addDecl(VDPrivate);
  8762. auto VDPrivateRefExpr = buildDeclRefExpr(
  8763. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  8764. RefExpr->getExprLoc());
  8765. DeclRefExpr *Ref = nullptr;
  8766. if (!VD && !CurContext->isDependentContext()) {
  8767. if (TopDVar.CKind == OMPC_lastprivate)
  8768. Ref = TopDVar.PrivateCopy;
  8769. else {
  8770. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8771. if (!IsOpenMPCapturedDecl(D))
  8772. ExprCaptures.push_back(Ref->getDecl());
  8773. }
  8774. }
  8775. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  8776. Vars.push_back((VD || CurContext->isDependentContext())
  8777. ? RefExpr->IgnoreParens()
  8778. : Ref);
  8779. PrivateCopies.push_back(VDPrivateRefExpr);
  8780. Inits.push_back(VDInitRefExpr);
  8781. }
  8782. if (Vars.empty())
  8783. return nullptr;
  8784. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8785. Vars, PrivateCopies, Inits,
  8786. buildPreInits(Context, ExprCaptures));
  8787. }
  8788. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  8789. SourceLocation StartLoc,
  8790. SourceLocation LParenLoc,
  8791. SourceLocation EndLoc) {
  8792. SmallVector<Expr *, 8> Vars;
  8793. SmallVector<Expr *, 8> SrcExprs;
  8794. SmallVector<Expr *, 8> DstExprs;
  8795. SmallVector<Expr *, 8> AssignmentOps;
  8796. SmallVector<Decl *, 4> ExprCaptures;
  8797. SmallVector<Expr *, 4> ExprPostUpdates;
  8798. for (auto &RefExpr : VarList) {
  8799. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8800. SourceLocation ELoc;
  8801. SourceRange ERange;
  8802. Expr *SimpleRefExpr = RefExpr;
  8803. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8804. if (Res.second) {
  8805. // It will be analyzed later.
  8806. Vars.push_back(RefExpr);
  8807. SrcExprs.push_back(nullptr);
  8808. DstExprs.push_back(nullptr);
  8809. AssignmentOps.push_back(nullptr);
  8810. }
  8811. ValueDecl *D = Res.first;
  8812. if (!D)
  8813. continue;
  8814. QualType Type = D->getType();
  8815. auto *VD = dyn_cast<VarDecl>(D);
  8816. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  8817. // A variable that appears in a lastprivate clause must not have an
  8818. // incomplete type or a reference type.
  8819. if (RequireCompleteType(ELoc, Type,
  8820. diag::err_omp_lastprivate_incomplete_type))
  8821. continue;
  8822. Type = Type.getNonReferenceType();
  8823. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8824. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8825. // in a Construct]
  8826. // Variables with the predetermined data-sharing attributes may not be
  8827. // listed in data-sharing attributes clauses, except for the cases
  8828. // listed below.
  8829. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8830. // A list item may appear in a firstprivate or lastprivate clause but not
  8831. // both.
  8832. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8833. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  8834. (isOpenMPDistributeDirective(CurrDir) ||
  8835. DVar.CKind != OMPC_firstprivate) &&
  8836. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  8837. Diag(ELoc, diag::err_omp_wrong_dsa)
  8838. << getOpenMPClauseName(DVar.CKind)
  8839. << getOpenMPClauseName(OMPC_lastprivate);
  8840. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8841. continue;
  8842. }
  8843. // OpenMP [2.14.3.5, Restrictions, p.2]
  8844. // A list item that is private within a parallel region, or that appears in
  8845. // the reduction clause of a parallel construct, must not appear in a
  8846. // lastprivate clause on a worksharing construct if any of the corresponding
  8847. // worksharing regions ever binds to any of the corresponding parallel
  8848. // regions.
  8849. DSAStackTy::DSAVarData TopDVar = DVar;
  8850. if (isOpenMPWorksharingDirective(CurrDir) &&
  8851. !isOpenMPParallelDirective(CurrDir) &&
  8852. !isOpenMPTeamsDirective(CurrDir)) {
  8853. DVar = DSAStack->getImplicitDSA(D, true);
  8854. if (DVar.CKind != OMPC_shared) {
  8855. Diag(ELoc, diag::err_omp_required_access)
  8856. << getOpenMPClauseName(OMPC_lastprivate)
  8857. << getOpenMPClauseName(OMPC_shared);
  8858. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8859. continue;
  8860. }
  8861. }
  8862. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  8863. // A variable of class type (or array thereof) that appears in a
  8864. // lastprivate clause requires an accessible, unambiguous default
  8865. // constructor for the class type, unless the list item is also specified
  8866. // in a firstprivate clause.
  8867. // A variable of class type (or array thereof) that appears in a
  8868. // lastprivate clause requires an accessible, unambiguous copy assignment
  8869. // operator for the class type.
  8870. Type = Context.getBaseElementType(Type).getNonReferenceType();
  8871. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  8872. Type.getUnqualifiedType(), ".lastprivate.src",
  8873. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8874. auto *PseudoSrcExpr =
  8875. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  8876. auto *DstVD =
  8877. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  8878. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8879. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8880. // For arrays generate assignment operation for single element and replace
  8881. // it by the original array element in CodeGen.
  8882. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  8883. PseudoDstExpr, PseudoSrcExpr);
  8884. if (AssignmentOp.isInvalid())
  8885. continue;
  8886. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8887. /*DiscardedValue=*/true);
  8888. if (AssignmentOp.isInvalid())
  8889. continue;
  8890. DeclRefExpr *Ref = nullptr;
  8891. if (!VD && !CurContext->isDependentContext()) {
  8892. if (TopDVar.CKind == OMPC_firstprivate)
  8893. Ref = TopDVar.PrivateCopy;
  8894. else {
  8895. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8896. if (!IsOpenMPCapturedDecl(D))
  8897. ExprCaptures.push_back(Ref->getDecl());
  8898. }
  8899. if (TopDVar.CKind == OMPC_firstprivate ||
  8900. (!IsOpenMPCapturedDecl(D) &&
  8901. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  8902. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8903. if (!RefRes.isUsable())
  8904. continue;
  8905. ExprResult PostUpdateRes =
  8906. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  8907. RefRes.get());
  8908. if (!PostUpdateRes.isUsable())
  8909. continue;
  8910. ExprPostUpdates.push_back(
  8911. IgnoredValueConversions(PostUpdateRes.get()).get());
  8912. }
  8913. }
  8914. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  8915. Vars.push_back((VD || CurContext->isDependentContext())
  8916. ? RefExpr->IgnoreParens()
  8917. : Ref);
  8918. SrcExprs.push_back(PseudoSrcExpr);
  8919. DstExprs.push_back(PseudoDstExpr);
  8920. AssignmentOps.push_back(AssignmentOp.get());
  8921. }
  8922. if (Vars.empty())
  8923. return nullptr;
  8924. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8925. Vars, SrcExprs, DstExprs, AssignmentOps,
  8926. buildPreInits(Context, ExprCaptures),
  8927. buildPostUpdate(*this, ExprPostUpdates));
  8928. }
  8929. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  8930. SourceLocation StartLoc,
  8931. SourceLocation LParenLoc,
  8932. SourceLocation EndLoc) {
  8933. SmallVector<Expr *, 8> Vars;
  8934. for (auto &RefExpr : VarList) {
  8935. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8936. SourceLocation ELoc;
  8937. SourceRange ERange;
  8938. Expr *SimpleRefExpr = RefExpr;
  8939. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8940. if (Res.second) {
  8941. // It will be analyzed later.
  8942. Vars.push_back(RefExpr);
  8943. }
  8944. ValueDecl *D = Res.first;
  8945. if (!D)
  8946. continue;
  8947. auto *VD = dyn_cast<VarDecl>(D);
  8948. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8949. // in a Construct]
  8950. // Variables with the predetermined data-sharing attributes may not be
  8951. // listed in data-sharing attributes clauses, except for the cases
  8952. // listed below. For these exceptions only, listing a predetermined
  8953. // variable in a data-sharing attribute clause is allowed and overrides
  8954. // the variable's predetermined data-sharing attributes.
  8955. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8956. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  8957. DVar.RefExpr) {
  8958. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8959. << getOpenMPClauseName(OMPC_shared);
  8960. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8961. continue;
  8962. }
  8963. DeclRefExpr *Ref = nullptr;
  8964. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  8965. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8966. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  8967. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  8968. ? RefExpr->IgnoreParens()
  8969. : Ref);
  8970. }
  8971. if (Vars.empty())
  8972. return nullptr;
  8973. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  8974. }
  8975. namespace {
  8976. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  8977. DSAStackTy *Stack;
  8978. public:
  8979. bool VisitDeclRefExpr(DeclRefExpr *E) {
  8980. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  8981. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  8982. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  8983. return false;
  8984. if (DVar.CKind != OMPC_unknown)
  8985. return true;
  8986. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  8987. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  8988. /*FromParent=*/true);
  8989. if (DVarPrivate.CKind != OMPC_unknown)
  8990. return true;
  8991. return false;
  8992. }
  8993. return false;
  8994. }
  8995. bool VisitStmt(Stmt *S) {
  8996. for (auto Child : S->children()) {
  8997. if (Child && Visit(Child))
  8998. return true;
  8999. }
  9000. return false;
  9001. }
  9002. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9003. };
  9004. } // namespace
  9005. namespace {
  9006. // Transform MemberExpression for specified FieldDecl of current class to
  9007. // DeclRefExpr to specified OMPCapturedExprDecl.
  9008. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9009. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9010. ValueDecl *Field;
  9011. DeclRefExpr *CapturedExpr;
  9012. public:
  9013. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9014. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9015. ExprResult TransformMemberExpr(MemberExpr *E) {
  9016. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9017. E->getMemberDecl() == Field) {
  9018. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9019. return CapturedExpr;
  9020. }
  9021. return BaseTransform::TransformMemberExpr(E);
  9022. }
  9023. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9024. };
  9025. } // namespace
  9026. template <typename T>
  9027. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  9028. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  9029. for (auto &Set : Lookups) {
  9030. for (auto *D : Set) {
  9031. if (auto Res = Gen(cast<ValueDecl>(D)))
  9032. return Res;
  9033. }
  9034. }
  9035. return T();
  9036. }
  9037. static ExprResult
  9038. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9039. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9040. const DeclarationNameInfo &ReductionId, QualType Ty,
  9041. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9042. if (ReductionIdScopeSpec.isInvalid())
  9043. return ExprError();
  9044. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9045. if (S) {
  9046. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9047. Lookup.suppressDiagnostics();
  9048. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9049. auto *D = Lookup.getRepresentativeDecl();
  9050. do {
  9051. S = S->getParent();
  9052. } while (S && !S->isDeclScope(D));
  9053. if (S)
  9054. S = S->getParent();
  9055. Lookups.push_back(UnresolvedSet<8>());
  9056. Lookups.back().append(Lookup.begin(), Lookup.end());
  9057. Lookup.clear();
  9058. }
  9059. } else if (auto *ULE =
  9060. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9061. Lookups.push_back(UnresolvedSet<8>());
  9062. Decl *PrevD = nullptr;
  9063. for (auto *D : ULE->decls()) {
  9064. if (D == PrevD)
  9065. Lookups.push_back(UnresolvedSet<8>());
  9066. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9067. Lookups.back().addDecl(DRD);
  9068. PrevD = D;
  9069. }
  9070. }
  9071. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9072. Ty->isInstantiationDependentType() ||
  9073. Ty->containsUnexpandedParameterPack() ||
  9074. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  9075. return !D->isInvalidDecl() &&
  9076. (D->getType()->isDependentType() ||
  9077. D->getType()->isInstantiationDependentType() ||
  9078. D->getType()->containsUnexpandedParameterPack());
  9079. })) {
  9080. UnresolvedSet<8> ResSet;
  9081. for (auto &Set : Lookups) {
  9082. ResSet.append(Set.begin(), Set.end());
  9083. // The last item marks the end of all declarations at the specified scope.
  9084. ResSet.addDecl(Set[Set.size() - 1]);
  9085. }
  9086. return UnresolvedLookupExpr::Create(
  9087. SemaRef.Context, /*NamingClass=*/nullptr,
  9088. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9089. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9090. }
  9091. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9092. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9093. if (!D->isInvalidDecl() &&
  9094. SemaRef.Context.hasSameType(D->getType(), Ty))
  9095. return D;
  9096. return nullptr;
  9097. }))
  9098. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9099. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9100. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9101. if (!D->isInvalidDecl() &&
  9102. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9103. !Ty.isMoreQualifiedThan(D->getType()))
  9104. return D;
  9105. return nullptr;
  9106. })) {
  9107. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9108. /*DetectVirtual=*/false);
  9109. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9110. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9111. VD->getType().getUnqualifiedType()))) {
  9112. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9113. /*DiagID=*/0) !=
  9114. Sema::AR_inaccessible) {
  9115. SemaRef.BuildBasePathArray(Paths, BasePath);
  9116. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9117. }
  9118. }
  9119. }
  9120. }
  9121. if (ReductionIdScopeSpec.isSet()) {
  9122. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9123. return ExprError();
  9124. }
  9125. return ExprEmpty();
  9126. }
  9127. namespace {
  9128. /// Data for the reduction-based clauses.
  9129. struct ReductionData {
  9130. /// List of original reduction items.
  9131. SmallVector<Expr *, 8> Vars;
  9132. /// List of private copies of the reduction items.
  9133. SmallVector<Expr *, 8> Privates;
  9134. /// LHS expressions for the reduction_op expressions.
  9135. SmallVector<Expr *, 8> LHSs;
  9136. /// RHS expressions for the reduction_op expressions.
  9137. SmallVector<Expr *, 8> RHSs;
  9138. /// Reduction operation expression.
  9139. SmallVector<Expr *, 8> ReductionOps;
  9140. /// Taskgroup descriptors for the corresponding reduction items in
  9141. /// in_reduction clauses.
  9142. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9143. /// List of captures for clause.
  9144. SmallVector<Decl *, 4> ExprCaptures;
  9145. /// List of postupdate expressions.
  9146. SmallVector<Expr *, 4> ExprPostUpdates;
  9147. ReductionData() = delete;
  9148. /// Reserves required memory for the reduction data.
  9149. ReductionData(unsigned Size) {
  9150. Vars.reserve(Size);
  9151. Privates.reserve(Size);
  9152. LHSs.reserve(Size);
  9153. RHSs.reserve(Size);
  9154. ReductionOps.reserve(Size);
  9155. TaskgroupDescriptors.reserve(Size);
  9156. ExprCaptures.reserve(Size);
  9157. ExprPostUpdates.reserve(Size);
  9158. }
  9159. /// Stores reduction item and reduction operation only (required for dependent
  9160. /// reduction item).
  9161. void push(Expr *Item, Expr *ReductionOp) {
  9162. Vars.emplace_back(Item);
  9163. Privates.emplace_back(nullptr);
  9164. LHSs.emplace_back(nullptr);
  9165. RHSs.emplace_back(nullptr);
  9166. ReductionOps.emplace_back(ReductionOp);
  9167. TaskgroupDescriptors.emplace_back(nullptr);
  9168. }
  9169. /// Stores reduction data.
  9170. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9171. Expr *TaskgroupDescriptor) {
  9172. Vars.emplace_back(Item);
  9173. Privates.emplace_back(Private);
  9174. LHSs.emplace_back(LHS);
  9175. RHSs.emplace_back(RHS);
  9176. ReductionOps.emplace_back(ReductionOp);
  9177. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9178. }
  9179. };
  9180. } // namespace
  9181. static bool CheckOMPArraySectionConstantForReduction(
  9182. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9183. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9184. const Expr *Length = OASE->getLength();
  9185. if (Length == nullptr) {
  9186. // For array sections of the form [1:] or [:], we would need to analyze
  9187. // the lower bound...
  9188. if (OASE->getColonLoc().isValid())
  9189. return false;
  9190. // This is an array subscript which has implicit length 1!
  9191. SingleElement = true;
  9192. ArraySizes.push_back(llvm::APSInt::get(1));
  9193. } else {
  9194. llvm::APSInt ConstantLengthValue;
  9195. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9196. return false;
  9197. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9198. ArraySizes.push_back(ConstantLengthValue);
  9199. }
  9200. // Get the base of this array section and walk up from there.
  9201. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9202. // We require length = 1 for all array sections except the right-most to
  9203. // guarantee that the memory region is contiguous and has no holes in it.
  9204. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9205. Length = TempOASE->getLength();
  9206. if (Length == nullptr) {
  9207. // For array sections of the form [1:] or [:], we would need to analyze
  9208. // the lower bound...
  9209. if (OASE->getColonLoc().isValid())
  9210. return false;
  9211. // This is an array subscript which has implicit length 1!
  9212. ArraySizes.push_back(llvm::APSInt::get(1));
  9213. } else {
  9214. llvm::APSInt ConstantLengthValue;
  9215. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9216. ConstantLengthValue.getSExtValue() != 1)
  9217. return false;
  9218. ArraySizes.push_back(ConstantLengthValue);
  9219. }
  9220. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9221. }
  9222. // If we have a single element, we don't need to add the implicit lengths.
  9223. if (!SingleElement) {
  9224. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9225. // Has implicit length 1!
  9226. ArraySizes.push_back(llvm::APSInt::get(1));
  9227. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9228. }
  9229. }
  9230. // This array section can be privatized as a single value or as a constant
  9231. // sized array.
  9232. return true;
  9233. }
  9234. static bool ActOnOMPReductionKindClause(
  9235. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9236. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9237. SourceLocation ColonLoc, SourceLocation EndLoc,
  9238. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9239. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9240. auto DN = ReductionId.getName();
  9241. auto OOK = DN.getCXXOverloadedOperator();
  9242. BinaryOperatorKind BOK = BO_Comma;
  9243. ASTContext &Context = S.Context;
  9244. // OpenMP [2.14.3.6, reduction clause]
  9245. // C
  9246. // reduction-identifier is either an identifier or one of the following
  9247. // operators: +, -, *, &, |, ^, && and ||
  9248. // C++
  9249. // reduction-identifier is either an id-expression or one of the following
  9250. // operators: +, -, *, &, |, ^, && and ||
  9251. switch (OOK) {
  9252. case OO_Plus:
  9253. case OO_Minus:
  9254. BOK = BO_Add;
  9255. break;
  9256. case OO_Star:
  9257. BOK = BO_Mul;
  9258. break;
  9259. case OO_Amp:
  9260. BOK = BO_And;
  9261. break;
  9262. case OO_Pipe:
  9263. BOK = BO_Or;
  9264. break;
  9265. case OO_Caret:
  9266. BOK = BO_Xor;
  9267. break;
  9268. case OO_AmpAmp:
  9269. BOK = BO_LAnd;
  9270. break;
  9271. case OO_PipePipe:
  9272. BOK = BO_LOr;
  9273. break;
  9274. case OO_New:
  9275. case OO_Delete:
  9276. case OO_Array_New:
  9277. case OO_Array_Delete:
  9278. case OO_Slash:
  9279. case OO_Percent:
  9280. case OO_Tilde:
  9281. case OO_Exclaim:
  9282. case OO_Equal:
  9283. case OO_Less:
  9284. case OO_Greater:
  9285. case OO_LessEqual:
  9286. case OO_GreaterEqual:
  9287. case OO_PlusEqual:
  9288. case OO_MinusEqual:
  9289. case OO_StarEqual:
  9290. case OO_SlashEqual:
  9291. case OO_PercentEqual:
  9292. case OO_CaretEqual:
  9293. case OO_AmpEqual:
  9294. case OO_PipeEqual:
  9295. case OO_LessLess:
  9296. case OO_GreaterGreater:
  9297. case OO_LessLessEqual:
  9298. case OO_GreaterGreaterEqual:
  9299. case OO_EqualEqual:
  9300. case OO_ExclaimEqual:
  9301. case OO_Spaceship:
  9302. case OO_PlusPlus:
  9303. case OO_MinusMinus:
  9304. case OO_Comma:
  9305. case OO_ArrowStar:
  9306. case OO_Arrow:
  9307. case OO_Call:
  9308. case OO_Subscript:
  9309. case OO_Conditional:
  9310. case OO_Coawait:
  9311. case NUM_OVERLOADED_OPERATORS:
  9312. llvm_unreachable("Unexpected reduction identifier");
  9313. case OO_None:
  9314. if (auto *II = DN.getAsIdentifierInfo()) {
  9315. if (II->isStr("max"))
  9316. BOK = BO_GT;
  9317. else if (II->isStr("min"))
  9318. BOK = BO_LT;
  9319. }
  9320. break;
  9321. }
  9322. SourceRange ReductionIdRange;
  9323. if (ReductionIdScopeSpec.isValid())
  9324. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  9325. else
  9326. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  9327. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  9328. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  9329. bool FirstIter = true;
  9330. for (auto RefExpr : VarList) {
  9331. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  9332. // OpenMP [2.1, C/C++]
  9333. // A list item is a variable or array section, subject to the restrictions
  9334. // specified in Section 2.4 on page 42 and in each of the sections
  9335. // describing clauses and directives for which a list appears.
  9336. // OpenMP [2.14.3.3, Restrictions, p.1]
  9337. // A variable that is part of another variable (as an array or
  9338. // structure element) cannot appear in a private clause.
  9339. if (!FirstIter && IR != ER)
  9340. ++IR;
  9341. FirstIter = false;
  9342. SourceLocation ELoc;
  9343. SourceRange ERange;
  9344. Expr *SimpleRefExpr = RefExpr;
  9345. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  9346. /*AllowArraySection=*/true);
  9347. if (Res.second) {
  9348. // Try to find 'declare reduction' corresponding construct before using
  9349. // builtin/overloaded operators.
  9350. QualType Type = Context.DependentTy;
  9351. CXXCastPath BasePath;
  9352. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9353. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9354. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9355. Expr *ReductionOp = nullptr;
  9356. if (S.CurContext->isDependentContext() &&
  9357. (DeclareReductionRef.isUnset() ||
  9358. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  9359. ReductionOp = DeclareReductionRef.get();
  9360. // It will be analyzed later.
  9361. RD.push(RefExpr, ReductionOp);
  9362. }
  9363. ValueDecl *D = Res.first;
  9364. if (!D)
  9365. continue;
  9366. Expr *TaskgroupDescriptor = nullptr;
  9367. QualType Type;
  9368. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  9369. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  9370. if (ASE)
  9371. Type = ASE->getType().getNonReferenceType();
  9372. else if (OASE) {
  9373. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  9374. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  9375. Type = ATy->getElementType();
  9376. else
  9377. Type = BaseType->getPointeeType();
  9378. Type = Type.getNonReferenceType();
  9379. } else
  9380. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  9381. auto *VD = dyn_cast<VarDecl>(D);
  9382. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9383. // A variable that appears in a private clause must not have an incomplete
  9384. // type or a reference type.
  9385. if (S.RequireCompleteType(ELoc, Type,
  9386. diag::err_omp_reduction_incomplete_type))
  9387. continue;
  9388. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9389. // A list item that appears in a reduction clause must not be
  9390. // const-qualified.
  9391. if (Type.getNonReferenceType().isConstant(Context)) {
  9392. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  9393. if (!ASE && !OASE) {
  9394. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9395. VarDecl::DeclarationOnly;
  9396. S.Diag(D->getLocation(),
  9397. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9398. << D;
  9399. }
  9400. continue;
  9401. }
  9402. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  9403. // If a list-item is a reference type then it must bind to the same object
  9404. // for all threads of the team.
  9405. if (!ASE && !OASE && VD) {
  9406. VarDecl *VDDef = VD->getDefinition();
  9407. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  9408. DSARefChecker Check(Stack);
  9409. if (Check.Visit(VDDef->getInit())) {
  9410. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  9411. << getOpenMPClauseName(ClauseKind) << ERange;
  9412. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  9413. continue;
  9414. }
  9415. }
  9416. }
  9417. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9418. // in a Construct]
  9419. // Variables with the predetermined data-sharing attributes may not be
  9420. // listed in data-sharing attributes clauses, except for the cases
  9421. // listed below. For these exceptions only, listing a predetermined
  9422. // variable in a data-sharing attribute clause is allowed and overrides
  9423. // the variable's predetermined data-sharing attributes.
  9424. // OpenMP [2.14.3.6, Restrictions, p.3]
  9425. // Any number of reduction clauses can be specified on the directive,
  9426. // but a list item can appear only once in the reduction clauses for that
  9427. // directive.
  9428. DSAStackTy::DSAVarData DVar;
  9429. DVar = Stack->getTopDSA(D, false);
  9430. if (DVar.CKind == OMPC_reduction) {
  9431. S.Diag(ELoc, diag::err_omp_once_referenced)
  9432. << getOpenMPClauseName(ClauseKind);
  9433. if (DVar.RefExpr)
  9434. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  9435. continue;
  9436. } else if (DVar.CKind != OMPC_unknown) {
  9437. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  9438. << getOpenMPClauseName(DVar.CKind)
  9439. << getOpenMPClauseName(OMPC_reduction);
  9440. ReportOriginalDSA(S, Stack, D, DVar);
  9441. continue;
  9442. }
  9443. // OpenMP [2.14.3.6, Restrictions, p.1]
  9444. // A list item that appears in a reduction clause of a worksharing
  9445. // construct must be shared in the parallel regions to which any of the
  9446. // worksharing regions arising from the worksharing construct bind.
  9447. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  9448. if (isOpenMPWorksharingDirective(CurrDir) &&
  9449. !isOpenMPParallelDirective(CurrDir) &&
  9450. !isOpenMPTeamsDirective(CurrDir)) {
  9451. DVar = Stack->getImplicitDSA(D, true);
  9452. if (DVar.CKind != OMPC_shared) {
  9453. S.Diag(ELoc, diag::err_omp_required_access)
  9454. << getOpenMPClauseName(OMPC_reduction)
  9455. << getOpenMPClauseName(OMPC_shared);
  9456. ReportOriginalDSA(S, Stack, D, DVar);
  9457. continue;
  9458. }
  9459. }
  9460. // Try to find 'declare reduction' corresponding construct before using
  9461. // builtin/overloaded operators.
  9462. CXXCastPath BasePath;
  9463. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9464. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9465. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9466. if (DeclareReductionRef.isInvalid())
  9467. continue;
  9468. if (S.CurContext->isDependentContext() &&
  9469. (DeclareReductionRef.isUnset() ||
  9470. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9471. RD.push(RefExpr, DeclareReductionRef.get());
  9472. continue;
  9473. }
  9474. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9475. // Not allowed reduction identifier is found.
  9476. S.Diag(ReductionId.getLocStart(),
  9477. diag::err_omp_unknown_reduction_identifier)
  9478. << Type << ReductionIdRange;
  9479. continue;
  9480. }
  9481. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9482. // The type of a list item that appears in a reduction clause must be valid
  9483. // for the reduction-identifier. For a max or min reduction in C, the type
  9484. // of the list item must be an allowed arithmetic data type: char, int,
  9485. // float, double, or _Bool, possibly modified with long, short, signed, or
  9486. // unsigned. For a max or min reduction in C++, the type of the list item
  9487. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9488. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9489. if (DeclareReductionRef.isUnset()) {
  9490. if ((BOK == BO_GT || BOK == BO_LT) &&
  9491. !(Type->isScalarType() ||
  9492. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9493. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9494. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9495. if (!ASE && !OASE) {
  9496. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9497. VarDecl::DeclarationOnly;
  9498. S.Diag(D->getLocation(),
  9499. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9500. << D;
  9501. }
  9502. continue;
  9503. }
  9504. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9505. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9506. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9507. << getOpenMPClauseName(ClauseKind);
  9508. if (!ASE && !OASE) {
  9509. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9510. VarDecl::DeclarationOnly;
  9511. S.Diag(D->getLocation(),
  9512. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9513. << D;
  9514. }
  9515. continue;
  9516. }
  9517. }
  9518. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9519. auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9520. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9521. auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9522. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9523. auto PrivateTy = Type;
  9524. // Try if we can determine constant lengths for all array sections and avoid
  9525. // the VLA.
  9526. bool ConstantLengthOASE = false;
  9527. if (OASE) {
  9528. bool SingleElement;
  9529. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9530. ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
  9531. Context, OASE, SingleElement, ArraySizes);
  9532. // If we don't have a single element, we must emit a constant array type.
  9533. if (ConstantLengthOASE && !SingleElement) {
  9534. for (auto &Size : ArraySizes) {
  9535. PrivateTy = Context.getConstantArrayType(
  9536. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9537. }
  9538. }
  9539. }
  9540. if ((OASE && !ConstantLengthOASE) ||
  9541. (!OASE && !ASE &&
  9542. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9543. if (!Context.getTargetInfo().isVLASupported() &&
  9544. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  9545. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  9546. S.Diag(ELoc, diag::note_vla_unsupported);
  9547. continue;
  9548. }
  9549. // For arrays/array sections only:
  9550. // Create pseudo array type for private copy. The size for this array will
  9551. // be generated during codegen.
  9552. // For array subscripts or single variables Private Ty is the same as Type
  9553. // (type of the variable or single array element).
  9554. PrivateTy = Context.getVariableArrayType(
  9555. Type,
  9556. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9557. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9558. } else if (!ASE && !OASE &&
  9559. Context.getAsArrayType(D->getType().getNonReferenceType()))
  9560. PrivateTy = D->getType().getNonReferenceType();
  9561. // Private copy.
  9562. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9563. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9564. // Add initializer for private variable.
  9565. Expr *Init = nullptr;
  9566. auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9567. auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9568. if (DeclareReductionRef.isUsable()) {
  9569. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9570. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9571. if (DRD->getInitializer()) {
  9572. Init = DRDRef;
  9573. RHSVD->setInit(DRDRef);
  9574. RHSVD->setInitStyle(VarDecl::CallInit);
  9575. }
  9576. } else {
  9577. switch (BOK) {
  9578. case BO_Add:
  9579. case BO_Xor:
  9580. case BO_Or:
  9581. case BO_LOr:
  9582. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9583. if (Type->isScalarType() || Type->isAnyComplexType())
  9584. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9585. break;
  9586. case BO_Mul:
  9587. case BO_LAnd:
  9588. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9589. // '*' and '&&' reduction ops - initializer is '1'.
  9590. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9591. }
  9592. break;
  9593. case BO_And: {
  9594. // '&' reduction op - initializer is '~0'.
  9595. QualType OrigType = Type;
  9596. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9597. Type = ComplexTy->getElementType();
  9598. if (Type->isRealFloatingType()) {
  9599. llvm::APFloat InitValue =
  9600. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9601. /*isIEEE=*/true);
  9602. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9603. Type, ELoc);
  9604. } else if (Type->isScalarType()) {
  9605. auto Size = Context.getTypeSize(Type);
  9606. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9607. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9608. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9609. }
  9610. if (Init && OrigType->isAnyComplexType()) {
  9611. // Init = 0xFFFF + 0xFFFFi;
  9612. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9613. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9614. }
  9615. Type = OrigType;
  9616. break;
  9617. }
  9618. case BO_LT:
  9619. case BO_GT: {
  9620. // 'min' reduction op - initializer is 'Largest representable number in
  9621. // the reduction list item type'.
  9622. // 'max' reduction op - initializer is 'Least representable number in
  9623. // the reduction list item type'.
  9624. if (Type->isIntegerType() || Type->isPointerType()) {
  9625. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9626. auto Size = Context.getTypeSize(Type);
  9627. QualType IntTy =
  9628. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9629. llvm::APInt InitValue =
  9630. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9631. : llvm::APInt::getMinValue(Size)
  9632. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9633. : llvm::APInt::getMaxValue(Size);
  9634. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9635. if (Type->isPointerType()) {
  9636. // Cast to pointer type.
  9637. auto CastExpr = S.BuildCStyleCastExpr(
  9638. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9639. if (CastExpr.isInvalid())
  9640. continue;
  9641. Init = CastExpr.get();
  9642. }
  9643. } else if (Type->isRealFloatingType()) {
  9644. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9645. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9646. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9647. Type, ELoc);
  9648. }
  9649. break;
  9650. }
  9651. case BO_PtrMemD:
  9652. case BO_PtrMemI:
  9653. case BO_MulAssign:
  9654. case BO_Div:
  9655. case BO_Rem:
  9656. case BO_Sub:
  9657. case BO_Shl:
  9658. case BO_Shr:
  9659. case BO_LE:
  9660. case BO_GE:
  9661. case BO_EQ:
  9662. case BO_NE:
  9663. case BO_AndAssign:
  9664. case BO_XorAssign:
  9665. case BO_OrAssign:
  9666. case BO_Assign:
  9667. case BO_AddAssign:
  9668. case BO_SubAssign:
  9669. case BO_DivAssign:
  9670. case BO_RemAssign:
  9671. case BO_ShlAssign:
  9672. case BO_ShrAssign:
  9673. case BO_Comma:
  9674. llvm_unreachable("Unexpected reduction operation");
  9675. }
  9676. }
  9677. if (Init && DeclareReductionRef.isUnset())
  9678. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9679. else if (!Init)
  9680. S.ActOnUninitializedDecl(RHSVD);
  9681. if (RHSVD->isInvalidDecl())
  9682. continue;
  9683. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9684. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9685. << Type << ReductionIdRange;
  9686. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9687. VarDecl::DeclarationOnly;
  9688. S.Diag(D->getLocation(),
  9689. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9690. << D;
  9691. continue;
  9692. }
  9693. // Store initializer for single element in private copy. Will be used during
  9694. // codegen.
  9695. PrivateVD->setInit(RHSVD->getInit());
  9696. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9697. auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9698. ExprResult ReductionOp;
  9699. if (DeclareReductionRef.isUsable()) {
  9700. QualType RedTy = DeclareReductionRef.get()->getType();
  9701. QualType PtrRedTy = Context.getPointerType(RedTy);
  9702. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9703. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9704. if (!BasePath.empty()) {
  9705. LHS = S.DefaultLvalueConversion(LHS.get());
  9706. RHS = S.DefaultLvalueConversion(RHS.get());
  9707. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9708. CK_UncheckedDerivedToBase, LHS.get(),
  9709. &BasePath, LHS.get()->getValueKind());
  9710. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9711. CK_UncheckedDerivedToBase, RHS.get(),
  9712. &BasePath, RHS.get()->getValueKind());
  9713. }
  9714. FunctionProtoType::ExtProtoInfo EPI;
  9715. QualType Params[] = {PtrRedTy, PtrRedTy};
  9716. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  9717. auto *OVE = new (Context) OpaqueValueExpr(
  9718. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  9719. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  9720. Expr *Args[] = {LHS.get(), RHS.get()};
  9721. ReductionOp = new (Context)
  9722. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  9723. } else {
  9724. ReductionOp = S.BuildBinOp(
  9725. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  9726. if (ReductionOp.isUsable()) {
  9727. if (BOK != BO_LT && BOK != BO_GT) {
  9728. ReductionOp =
  9729. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9730. BO_Assign, LHSDRE, ReductionOp.get());
  9731. } else {
  9732. auto *ConditionalOp = new (Context)
  9733. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  9734. Type, VK_LValue, OK_Ordinary);
  9735. ReductionOp =
  9736. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9737. BO_Assign, LHSDRE, ConditionalOp);
  9738. }
  9739. if (ReductionOp.isUsable())
  9740. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  9741. }
  9742. if (!ReductionOp.isUsable())
  9743. continue;
  9744. }
  9745. // OpenMP [2.15.4.6, Restrictions, p.2]
  9746. // A list item that appears in an in_reduction clause of a task construct
  9747. // must appear in a task_reduction clause of a construct associated with a
  9748. // taskgroup region that includes the participating task in its taskgroup
  9749. // set. The construct associated with the innermost region that meets this
  9750. // condition must specify the same reduction-identifier as the in_reduction
  9751. // clause.
  9752. if (ClauseKind == OMPC_in_reduction) {
  9753. SourceRange ParentSR;
  9754. BinaryOperatorKind ParentBOK;
  9755. const Expr *ParentReductionOp;
  9756. Expr *ParentBOKTD, *ParentReductionOpTD;
  9757. DSAStackTy::DSAVarData ParentBOKDSA =
  9758. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  9759. ParentBOKTD);
  9760. DSAStackTy::DSAVarData ParentReductionOpDSA =
  9761. Stack->getTopMostTaskgroupReductionData(
  9762. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  9763. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  9764. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  9765. if (!IsParentBOK && !IsParentReductionOp) {
  9766. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  9767. continue;
  9768. }
  9769. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  9770. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  9771. IsParentReductionOp) {
  9772. bool EmitError = true;
  9773. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  9774. llvm::FoldingSetNodeID RedId, ParentRedId;
  9775. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  9776. DeclareReductionRef.get()->Profile(RedId, Context,
  9777. /*Canonical=*/true);
  9778. EmitError = RedId != ParentRedId;
  9779. }
  9780. if (EmitError) {
  9781. S.Diag(ReductionId.getLocStart(),
  9782. diag::err_omp_reduction_identifier_mismatch)
  9783. << ReductionIdRange << RefExpr->getSourceRange();
  9784. S.Diag(ParentSR.getBegin(),
  9785. diag::note_omp_previous_reduction_identifier)
  9786. << ParentSR
  9787. << (IsParentBOK ? ParentBOKDSA.RefExpr
  9788. : ParentReductionOpDSA.RefExpr)
  9789. ->getSourceRange();
  9790. continue;
  9791. }
  9792. }
  9793. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  9794. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  9795. }
  9796. DeclRefExpr *Ref = nullptr;
  9797. Expr *VarsExpr = RefExpr->IgnoreParens();
  9798. if (!VD && !S.CurContext->isDependentContext()) {
  9799. if (ASE || OASE) {
  9800. TransformExprToCaptures RebuildToCapture(S, D);
  9801. VarsExpr =
  9802. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  9803. Ref = RebuildToCapture.getCapturedExpr();
  9804. } else {
  9805. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  9806. }
  9807. if (!S.IsOpenMPCapturedDecl(D)) {
  9808. RD.ExprCaptures.emplace_back(Ref->getDecl());
  9809. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9810. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  9811. if (!RefRes.isUsable())
  9812. continue;
  9813. ExprResult PostUpdateRes =
  9814. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9815. RefRes.get());
  9816. if (!PostUpdateRes.isUsable())
  9817. continue;
  9818. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  9819. Stack->getCurrentDirective() == OMPD_taskgroup) {
  9820. S.Diag(RefExpr->getExprLoc(),
  9821. diag::err_omp_reduction_non_addressable_expression)
  9822. << RefExpr->getSourceRange();
  9823. continue;
  9824. }
  9825. RD.ExprPostUpdates.emplace_back(
  9826. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  9827. }
  9828. }
  9829. }
  9830. // All reduction items are still marked as reduction (to do not increase
  9831. // code base size).
  9832. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  9833. if (CurrDir == OMPD_taskgroup) {
  9834. if (DeclareReductionRef.isUsable())
  9835. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  9836. DeclareReductionRef.get());
  9837. else
  9838. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  9839. }
  9840. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  9841. TaskgroupDescriptor);
  9842. }
  9843. return RD.Vars.empty();
  9844. }
  9845. OMPClause *Sema::ActOnOpenMPReductionClause(
  9846. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9847. SourceLocation ColonLoc, SourceLocation EndLoc,
  9848. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9849. ArrayRef<Expr *> UnresolvedReductions) {
  9850. ReductionData RD(VarList.size());
  9851. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  9852. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9853. ReductionIdScopeSpec, ReductionId,
  9854. UnresolvedReductions, RD))
  9855. return nullptr;
  9856. return OMPReductionClause::Create(
  9857. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9858. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9859. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9860. buildPreInits(Context, RD.ExprCaptures),
  9861. buildPostUpdate(*this, RD.ExprPostUpdates));
  9862. }
  9863. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  9864. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9865. SourceLocation ColonLoc, SourceLocation EndLoc,
  9866. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9867. ArrayRef<Expr *> UnresolvedReductions) {
  9868. ReductionData RD(VarList.size());
  9869. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
  9870. VarList, StartLoc, LParenLoc, ColonLoc,
  9871. EndLoc, ReductionIdScopeSpec, ReductionId,
  9872. UnresolvedReductions, RD))
  9873. return nullptr;
  9874. return OMPTaskReductionClause::Create(
  9875. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9876. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9877. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9878. buildPreInits(Context, RD.ExprCaptures),
  9879. buildPostUpdate(*this, RD.ExprPostUpdates));
  9880. }
  9881. OMPClause *Sema::ActOnOpenMPInReductionClause(
  9882. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9883. SourceLocation ColonLoc, SourceLocation EndLoc,
  9884. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9885. ArrayRef<Expr *> UnresolvedReductions) {
  9886. ReductionData RD(VarList.size());
  9887. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  9888. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9889. ReductionIdScopeSpec, ReductionId,
  9890. UnresolvedReductions, RD))
  9891. return nullptr;
  9892. return OMPInReductionClause::Create(
  9893. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9894. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9895. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  9896. buildPreInits(Context, RD.ExprCaptures),
  9897. buildPostUpdate(*this, RD.ExprPostUpdates));
  9898. }
  9899. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  9900. SourceLocation LinLoc) {
  9901. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  9902. LinKind == OMPC_LINEAR_unknown) {
  9903. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  9904. return true;
  9905. }
  9906. return false;
  9907. }
  9908. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  9909. OpenMPLinearClauseKind LinKind,
  9910. QualType Type) {
  9911. auto *VD = dyn_cast_or_null<VarDecl>(D);
  9912. // A variable must not have an incomplete type or a reference type.
  9913. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  9914. return true;
  9915. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  9916. !Type->isReferenceType()) {
  9917. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  9918. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  9919. return true;
  9920. }
  9921. Type = Type.getNonReferenceType();
  9922. // A list item must not be const-qualified.
  9923. if (Type.isConstant(Context)) {
  9924. Diag(ELoc, diag::err_omp_const_variable)
  9925. << getOpenMPClauseName(OMPC_linear);
  9926. if (D) {
  9927. bool IsDecl =
  9928. !VD ||
  9929. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9930. Diag(D->getLocation(),
  9931. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9932. << D;
  9933. }
  9934. return true;
  9935. }
  9936. // A list item must be of integral or pointer type.
  9937. Type = Type.getUnqualifiedType().getCanonicalType();
  9938. const auto *Ty = Type.getTypePtrOrNull();
  9939. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  9940. !Ty->isPointerType())) {
  9941. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  9942. if (D) {
  9943. bool IsDecl =
  9944. !VD ||
  9945. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9946. Diag(D->getLocation(),
  9947. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9948. << D;
  9949. }
  9950. return true;
  9951. }
  9952. return false;
  9953. }
  9954. OMPClause *Sema::ActOnOpenMPLinearClause(
  9955. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  9956. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  9957. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9958. SmallVector<Expr *, 8> Vars;
  9959. SmallVector<Expr *, 8> Privates;
  9960. SmallVector<Expr *, 8> Inits;
  9961. SmallVector<Decl *, 4> ExprCaptures;
  9962. SmallVector<Expr *, 4> ExprPostUpdates;
  9963. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  9964. LinKind = OMPC_LINEAR_val;
  9965. for (auto &RefExpr : VarList) {
  9966. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9967. SourceLocation ELoc;
  9968. SourceRange ERange;
  9969. Expr *SimpleRefExpr = RefExpr;
  9970. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9971. /*AllowArraySection=*/false);
  9972. if (Res.second) {
  9973. // It will be analyzed later.
  9974. Vars.push_back(RefExpr);
  9975. Privates.push_back(nullptr);
  9976. Inits.push_back(nullptr);
  9977. }
  9978. ValueDecl *D = Res.first;
  9979. if (!D)
  9980. continue;
  9981. QualType Type = D->getType();
  9982. auto *VD = dyn_cast<VarDecl>(D);
  9983. // OpenMP [2.14.3.7, linear clause]
  9984. // A list-item cannot appear in more than one linear clause.
  9985. // A list-item that appears in a linear clause cannot appear in any
  9986. // other data-sharing attribute clause.
  9987. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  9988. if (DVar.RefExpr) {
  9989. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9990. << getOpenMPClauseName(OMPC_linear);
  9991. ReportOriginalDSA(*this, DSAStack, D, DVar);
  9992. continue;
  9993. }
  9994. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  9995. continue;
  9996. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  9997. // Build private copy of original var.
  9998. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  9999. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10000. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10001. // Build var to save initial value.
  10002. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10003. Expr *InitExpr;
  10004. DeclRefExpr *Ref = nullptr;
  10005. if (!VD && !CurContext->isDependentContext()) {
  10006. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10007. if (!IsOpenMPCapturedDecl(D)) {
  10008. ExprCaptures.push_back(Ref->getDecl());
  10009. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10010. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10011. if (!RefRes.isUsable())
  10012. continue;
  10013. ExprResult PostUpdateRes =
  10014. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10015. SimpleRefExpr, RefRes.get());
  10016. if (!PostUpdateRes.isUsable())
  10017. continue;
  10018. ExprPostUpdates.push_back(
  10019. IgnoredValueConversions(PostUpdateRes.get()).get());
  10020. }
  10021. }
  10022. }
  10023. if (LinKind == OMPC_LINEAR_uval)
  10024. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10025. else
  10026. InitExpr = VD ? SimpleRefExpr : Ref;
  10027. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10028. /*DirectInit=*/false);
  10029. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10030. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10031. Vars.push_back((VD || CurContext->isDependentContext())
  10032. ? RefExpr->IgnoreParens()
  10033. : Ref);
  10034. Privates.push_back(PrivateRef);
  10035. Inits.push_back(InitRef);
  10036. }
  10037. if (Vars.empty())
  10038. return nullptr;
  10039. Expr *StepExpr = Step;
  10040. Expr *CalcStepExpr = nullptr;
  10041. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10042. !Step->isInstantiationDependent() &&
  10043. !Step->containsUnexpandedParameterPack()) {
  10044. SourceLocation StepLoc = Step->getLocStart();
  10045. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10046. if (Val.isInvalid())
  10047. return nullptr;
  10048. StepExpr = Val.get();
  10049. // Build var to save the step value.
  10050. VarDecl *SaveVar =
  10051. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10052. ExprResult SaveRef =
  10053. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10054. ExprResult CalcStep =
  10055. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10056. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10057. // Warn about zero linear step (it would be probably better specified as
  10058. // making corresponding variables 'const').
  10059. llvm::APSInt Result;
  10060. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10061. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10062. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10063. << (Vars.size() > 1);
  10064. if (!IsConstant && CalcStep.isUsable()) {
  10065. // Calculate the step beforehand instead of doing this on each iteration.
  10066. // (This is not used if the number of iterations may be kfold-ed).
  10067. CalcStepExpr = CalcStep.get();
  10068. }
  10069. }
  10070. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10071. ColonLoc, EndLoc, Vars, Privates, Inits,
  10072. StepExpr, CalcStepExpr,
  10073. buildPreInits(Context, ExprCaptures),
  10074. buildPostUpdate(*this, ExprPostUpdates));
  10075. }
  10076. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10077. Expr *NumIterations, Sema &SemaRef,
  10078. Scope *S, DSAStackTy *Stack) {
  10079. // Walk the vars and build update/final expressions for the CodeGen.
  10080. SmallVector<Expr *, 8> Updates;
  10081. SmallVector<Expr *, 8> Finals;
  10082. Expr *Step = Clause.getStep();
  10083. Expr *CalcStep = Clause.getCalcStep();
  10084. // OpenMP [2.14.3.7, linear clause]
  10085. // If linear-step is not specified it is assumed to be 1.
  10086. if (Step == nullptr)
  10087. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10088. else if (CalcStep) {
  10089. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10090. }
  10091. bool HasErrors = false;
  10092. auto CurInit = Clause.inits().begin();
  10093. auto CurPrivate = Clause.privates().begin();
  10094. auto LinKind = Clause.getModifier();
  10095. for (auto &RefExpr : Clause.varlists()) {
  10096. SourceLocation ELoc;
  10097. SourceRange ERange;
  10098. Expr *SimpleRefExpr = RefExpr;
  10099. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  10100. /*AllowArraySection=*/false);
  10101. ValueDecl *D = Res.first;
  10102. if (Res.second || !D) {
  10103. Updates.push_back(nullptr);
  10104. Finals.push_back(nullptr);
  10105. HasErrors = true;
  10106. continue;
  10107. }
  10108. auto &&Info = Stack->isLoopControlVariable(D);
  10109. // OpenMP [2.15.11, distribute simd Construct]
  10110. // A list item may not appear in a linear clause, unless it is the loop
  10111. // iteration variable.
  10112. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10113. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10114. SemaRef.Diag(ELoc,
  10115. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10116. Updates.push_back(nullptr);
  10117. Finals.push_back(nullptr);
  10118. HasErrors = true;
  10119. continue;
  10120. }
  10121. Expr *InitExpr = *CurInit;
  10122. // Build privatized reference to the current linear var.
  10123. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10124. Expr *CapturedRef;
  10125. if (LinKind == OMPC_LINEAR_uval)
  10126. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10127. else
  10128. CapturedRef =
  10129. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10130. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10131. /*RefersToCapture=*/true);
  10132. // Build update: Var = InitExpr + IV * Step
  10133. ExprResult Update;
  10134. if (!Info.first) {
  10135. Update =
  10136. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10137. InitExpr, IV, Step, /* Subtract */ false);
  10138. } else
  10139. Update = *CurPrivate;
  10140. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  10141. /*DiscardedValue=*/true);
  10142. // Build final: Var = InitExpr + NumIterations * Step
  10143. ExprResult Final;
  10144. if (!Info.first) {
  10145. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10146. InitExpr, NumIterations, Step,
  10147. /* Subtract */ false);
  10148. } else
  10149. Final = *CurPrivate;
  10150. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  10151. /*DiscardedValue=*/true);
  10152. if (!Update.isUsable() || !Final.isUsable()) {
  10153. Updates.push_back(nullptr);
  10154. Finals.push_back(nullptr);
  10155. HasErrors = true;
  10156. } else {
  10157. Updates.push_back(Update.get());
  10158. Finals.push_back(Final.get());
  10159. }
  10160. ++CurInit;
  10161. ++CurPrivate;
  10162. }
  10163. Clause.setUpdates(Updates);
  10164. Clause.setFinals(Finals);
  10165. return HasErrors;
  10166. }
  10167. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10168. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10169. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10170. SmallVector<Expr *, 8> Vars;
  10171. for (auto &RefExpr : VarList) {
  10172. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10173. SourceLocation ELoc;
  10174. SourceRange ERange;
  10175. Expr *SimpleRefExpr = RefExpr;
  10176. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10177. /*AllowArraySection=*/false);
  10178. if (Res.second) {
  10179. // It will be analyzed later.
  10180. Vars.push_back(RefExpr);
  10181. }
  10182. ValueDecl *D = Res.first;
  10183. if (!D)
  10184. continue;
  10185. QualType QType = D->getType();
  10186. auto *VD = dyn_cast<VarDecl>(D);
  10187. // OpenMP [2.8.1, simd construct, Restrictions]
  10188. // The type of list items appearing in the aligned clause must be
  10189. // array, pointer, reference to array, or reference to pointer.
  10190. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10191. const Type *Ty = QType.getTypePtrOrNull();
  10192. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10193. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10194. << QType << getLangOpts().CPlusPlus << ERange;
  10195. bool IsDecl =
  10196. !VD ||
  10197. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10198. Diag(D->getLocation(),
  10199. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10200. << D;
  10201. continue;
  10202. }
  10203. // OpenMP [2.8.1, simd construct, Restrictions]
  10204. // A list-item cannot appear in more than one aligned clause.
  10205. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10206. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10207. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10208. << getOpenMPClauseName(OMPC_aligned);
  10209. continue;
  10210. }
  10211. DeclRefExpr *Ref = nullptr;
  10212. if (!VD && IsOpenMPCapturedDecl(D))
  10213. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10214. Vars.push_back(DefaultFunctionArrayConversion(
  10215. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10216. .get());
  10217. }
  10218. // OpenMP [2.8.1, simd construct, Description]
  10219. // The parameter of the aligned clause, alignment, must be a constant
  10220. // positive integer expression.
  10221. // If no optional parameter is specified, implementation-defined default
  10222. // alignments for SIMD instructions on the target platforms are assumed.
  10223. if (Alignment != nullptr) {
  10224. ExprResult AlignResult =
  10225. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10226. if (AlignResult.isInvalid())
  10227. return nullptr;
  10228. Alignment = AlignResult.get();
  10229. }
  10230. if (Vars.empty())
  10231. return nullptr;
  10232. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10233. EndLoc, Vars, Alignment);
  10234. }
  10235. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10236. SourceLocation StartLoc,
  10237. SourceLocation LParenLoc,
  10238. SourceLocation EndLoc) {
  10239. SmallVector<Expr *, 8> Vars;
  10240. SmallVector<Expr *, 8> SrcExprs;
  10241. SmallVector<Expr *, 8> DstExprs;
  10242. SmallVector<Expr *, 8> AssignmentOps;
  10243. for (auto &RefExpr : VarList) {
  10244. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10245. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10246. // It will be analyzed later.
  10247. Vars.push_back(RefExpr);
  10248. SrcExprs.push_back(nullptr);
  10249. DstExprs.push_back(nullptr);
  10250. AssignmentOps.push_back(nullptr);
  10251. continue;
  10252. }
  10253. SourceLocation ELoc = RefExpr->getExprLoc();
  10254. // OpenMP [2.1, C/C++]
  10255. // A list item is a variable name.
  10256. // OpenMP [2.14.4.1, Restrictions, p.1]
  10257. // A list item that appears in a copyin clause must be threadprivate.
  10258. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  10259. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  10260. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  10261. << 0 << RefExpr->getSourceRange();
  10262. continue;
  10263. }
  10264. Decl *D = DE->getDecl();
  10265. VarDecl *VD = cast<VarDecl>(D);
  10266. QualType Type = VD->getType();
  10267. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  10268. // It will be analyzed later.
  10269. Vars.push_back(DE);
  10270. SrcExprs.push_back(nullptr);
  10271. DstExprs.push_back(nullptr);
  10272. AssignmentOps.push_back(nullptr);
  10273. continue;
  10274. }
  10275. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  10276. // A list item that appears in a copyin clause must be threadprivate.
  10277. if (!DSAStack->isThreadPrivate(VD)) {
  10278. Diag(ELoc, diag::err_omp_required_access)
  10279. << getOpenMPClauseName(OMPC_copyin)
  10280. << getOpenMPDirectiveName(OMPD_threadprivate);
  10281. continue;
  10282. }
  10283. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10284. // A variable of class type (or array thereof) that appears in a
  10285. // copyin clause requires an accessible, unambiguous copy assignment
  10286. // operator for the class type.
  10287. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10288. auto *SrcVD =
  10289. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  10290. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10291. auto *PseudoSrcExpr = buildDeclRefExpr(
  10292. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  10293. auto *DstVD =
  10294. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  10295. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10296. auto *PseudoDstExpr =
  10297. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  10298. // For arrays generate assignment operation for single element and replace
  10299. // it by the original array element in CodeGen.
  10300. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  10301. PseudoDstExpr, PseudoSrcExpr);
  10302. if (AssignmentOp.isInvalid())
  10303. continue;
  10304. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  10305. /*DiscardedValue=*/true);
  10306. if (AssignmentOp.isInvalid())
  10307. continue;
  10308. DSAStack->addDSA(VD, DE, OMPC_copyin);
  10309. Vars.push_back(DE);
  10310. SrcExprs.push_back(PseudoSrcExpr);
  10311. DstExprs.push_back(PseudoDstExpr);
  10312. AssignmentOps.push_back(AssignmentOp.get());
  10313. }
  10314. if (Vars.empty())
  10315. return nullptr;
  10316. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10317. SrcExprs, DstExprs, AssignmentOps);
  10318. }
  10319. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  10320. SourceLocation StartLoc,
  10321. SourceLocation LParenLoc,
  10322. SourceLocation EndLoc) {
  10323. SmallVector<Expr *, 8> Vars;
  10324. SmallVector<Expr *, 8> SrcExprs;
  10325. SmallVector<Expr *, 8> DstExprs;
  10326. SmallVector<Expr *, 8> AssignmentOps;
  10327. for (auto &RefExpr : VarList) {
  10328. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10329. SourceLocation ELoc;
  10330. SourceRange ERange;
  10331. Expr *SimpleRefExpr = RefExpr;
  10332. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10333. /*AllowArraySection=*/false);
  10334. if (Res.second) {
  10335. // It will be analyzed later.
  10336. Vars.push_back(RefExpr);
  10337. SrcExprs.push_back(nullptr);
  10338. DstExprs.push_back(nullptr);
  10339. AssignmentOps.push_back(nullptr);
  10340. }
  10341. ValueDecl *D = Res.first;
  10342. if (!D)
  10343. continue;
  10344. QualType Type = D->getType();
  10345. auto *VD = dyn_cast<VarDecl>(D);
  10346. // OpenMP [2.14.4.2, Restrictions, p.2]
  10347. // A list item that appears in a copyprivate clause may not appear in a
  10348. // private or firstprivate clause on the single construct.
  10349. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  10350. auto DVar = DSAStack->getTopDSA(D, false);
  10351. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  10352. DVar.RefExpr) {
  10353. Diag(ELoc, diag::err_omp_wrong_dsa)
  10354. << getOpenMPClauseName(DVar.CKind)
  10355. << getOpenMPClauseName(OMPC_copyprivate);
  10356. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10357. continue;
  10358. }
  10359. // OpenMP [2.11.4.2, Restrictions, p.1]
  10360. // All list items that appear in a copyprivate clause must be either
  10361. // threadprivate or private in the enclosing context.
  10362. if (DVar.CKind == OMPC_unknown) {
  10363. DVar = DSAStack->getImplicitDSA(D, false);
  10364. if (DVar.CKind == OMPC_shared) {
  10365. Diag(ELoc, diag::err_omp_required_access)
  10366. << getOpenMPClauseName(OMPC_copyprivate)
  10367. << "threadprivate or private in the enclosing context";
  10368. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10369. continue;
  10370. }
  10371. }
  10372. }
  10373. // Variably modified types are not supported.
  10374. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  10375. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10376. << getOpenMPClauseName(OMPC_copyprivate) << Type
  10377. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10378. bool IsDecl =
  10379. !VD ||
  10380. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10381. Diag(D->getLocation(),
  10382. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10383. << D;
  10384. continue;
  10385. }
  10386. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10387. // A variable of class type (or array thereof) that appears in a
  10388. // copyin clause requires an accessible, unambiguous copy assignment
  10389. // operator for the class type.
  10390. Type = Context.getBaseElementType(Type.getNonReferenceType())
  10391. .getUnqualifiedType();
  10392. auto *SrcVD =
  10393. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  10394. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10395. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  10396. auto *DstVD =
  10397. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  10398. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10399. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10400. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10401. PseudoDstExpr, PseudoSrcExpr);
  10402. if (AssignmentOp.isInvalid())
  10403. continue;
  10404. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  10405. /*DiscardedValue=*/true);
  10406. if (AssignmentOp.isInvalid())
  10407. continue;
  10408. // No need to mark vars as copyprivate, they are already threadprivate or
  10409. // implicitly private.
  10410. assert(VD || IsOpenMPCapturedDecl(D));
  10411. Vars.push_back(
  10412. VD ? RefExpr->IgnoreParens()
  10413. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  10414. SrcExprs.push_back(PseudoSrcExpr);
  10415. DstExprs.push_back(PseudoDstExpr);
  10416. AssignmentOps.push_back(AssignmentOp.get());
  10417. }
  10418. if (Vars.empty())
  10419. return nullptr;
  10420. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10421. Vars, SrcExprs, DstExprs, AssignmentOps);
  10422. }
  10423. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  10424. SourceLocation StartLoc,
  10425. SourceLocation LParenLoc,
  10426. SourceLocation EndLoc) {
  10427. if (VarList.empty())
  10428. return nullptr;
  10429. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  10430. }
  10431. OMPClause *
  10432. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  10433. SourceLocation DepLoc, SourceLocation ColonLoc,
  10434. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10435. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10436. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  10437. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  10438. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10439. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  10440. return nullptr;
  10441. }
  10442. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  10443. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  10444. DepKind == OMPC_DEPEND_sink)) {
  10445. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  10446. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10447. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  10448. /*Last=*/OMPC_DEPEND_unknown, Except)
  10449. << getOpenMPClauseName(OMPC_depend);
  10450. return nullptr;
  10451. }
  10452. SmallVector<Expr *, 8> Vars;
  10453. DSAStackTy::OperatorOffsetTy OpsOffs;
  10454. llvm::APSInt DepCounter(/*BitWidth=*/32);
  10455. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  10456. if (DepKind == OMPC_DEPEND_sink) {
  10457. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  10458. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  10459. TotalDepCount.setIsUnsigned(/*Val=*/true);
  10460. }
  10461. }
  10462. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  10463. DSAStack->getParentOrderedRegionParam()) {
  10464. for (auto &RefExpr : VarList) {
  10465. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  10466. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10467. // It will be analyzed later.
  10468. Vars.push_back(RefExpr);
  10469. continue;
  10470. }
  10471. SourceLocation ELoc = RefExpr->getExprLoc();
  10472. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  10473. if (DepKind == OMPC_DEPEND_sink) {
  10474. if (DepCounter >= TotalDepCount) {
  10475. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  10476. continue;
  10477. }
  10478. ++DepCounter;
  10479. // OpenMP [2.13.9, Summary]
  10480. // depend(dependence-type : vec), where dependence-type is:
  10481. // 'sink' and where vec is the iteration vector, which has the form:
  10482. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  10483. // where n is the value specified by the ordered clause in the loop
  10484. // directive, xi denotes the loop iteration variable of the i-th nested
  10485. // loop associated with the loop directive, and di is a constant
  10486. // non-negative integer.
  10487. if (CurContext->isDependentContext()) {
  10488. // It will be analyzed later.
  10489. Vars.push_back(RefExpr);
  10490. continue;
  10491. }
  10492. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10493. OverloadedOperatorKind OOK = OO_None;
  10494. SourceLocation OOLoc;
  10495. Expr *LHS = SimpleExpr;
  10496. Expr *RHS = nullptr;
  10497. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10498. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10499. OOLoc = BO->getOperatorLoc();
  10500. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10501. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10502. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10503. OOK = OCE->getOperator();
  10504. OOLoc = OCE->getOperatorLoc();
  10505. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10506. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10507. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10508. OOK = MCE->getMethodDecl()
  10509. ->getNameInfo()
  10510. .getName()
  10511. .getCXXOverloadedOperator();
  10512. OOLoc = MCE->getCallee()->getExprLoc();
  10513. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10514. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10515. }
  10516. SourceLocation ELoc;
  10517. SourceRange ERange;
  10518. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10519. /*AllowArraySection=*/false);
  10520. if (Res.second) {
  10521. // It will be analyzed later.
  10522. Vars.push_back(RefExpr);
  10523. }
  10524. ValueDecl *D = Res.first;
  10525. if (!D)
  10526. continue;
  10527. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10528. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10529. continue;
  10530. }
  10531. if (RHS) {
  10532. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10533. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10534. if (RHSRes.isInvalid())
  10535. continue;
  10536. }
  10537. if (!CurContext->isDependentContext() &&
  10538. DSAStack->getParentOrderedRegionParam() &&
  10539. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10540. ValueDecl* VD = DSAStack->getParentLoopControlVariable(
  10541. DepCounter.getZExtValue());
  10542. if (VD) {
  10543. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10544. << 1 << VD;
  10545. } else {
  10546. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10547. }
  10548. continue;
  10549. }
  10550. OpsOffs.push_back({RHS, OOK});
  10551. } else {
  10552. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10553. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10554. (ASE &&
  10555. !ASE->getBase()
  10556. ->getType()
  10557. .getNonReferenceType()
  10558. ->isPointerType() &&
  10559. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10560. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10561. << RefExpr->getSourceRange();
  10562. continue;
  10563. }
  10564. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10565. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10566. ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  10567. RefExpr->IgnoreParenImpCasts());
  10568. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10569. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10570. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10571. << RefExpr->getSourceRange();
  10572. continue;
  10573. }
  10574. }
  10575. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10576. }
  10577. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10578. TotalDepCount > VarList.size() &&
  10579. DSAStack->getParentOrderedRegionParam() &&
  10580. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10581. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
  10582. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10583. }
  10584. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10585. Vars.empty())
  10586. return nullptr;
  10587. }
  10588. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10589. DepKind, DepLoc, ColonLoc, Vars);
  10590. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  10591. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10592. return C;
  10593. }
  10594. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10595. SourceLocation LParenLoc,
  10596. SourceLocation EndLoc) {
  10597. Expr *ValExpr = Device;
  10598. Stmt *HelperValStmt = nullptr;
  10599. // OpenMP [2.9.1, Restrictions]
  10600. // The device expression must evaluate to a non-negative integer value.
  10601. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10602. /*StrictlyPositive=*/false))
  10603. return nullptr;
  10604. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10605. OpenMPDirectiveKind CaptureRegion =
  10606. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  10607. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10608. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  10609. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10610. HelperValStmt = buildPreInits(Context, Captures);
  10611. }
  10612. return new (Context)
  10613. OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
  10614. }
  10615. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10616. DSAStackTy *Stack, QualType QTy) {
  10617. NamedDecl *ND;
  10618. if (QTy->isIncompleteType(&ND)) {
  10619. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10620. return false;
  10621. }
  10622. return true;
  10623. }
  10624. /// \brief Return true if it can be proven that the provided array expression
  10625. /// (array section or array subscript) does NOT specify the whole size of the
  10626. /// array whose base type is \a BaseQTy.
  10627. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10628. const Expr *E,
  10629. QualType BaseQTy) {
  10630. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10631. // If this is an array subscript, it refers to the whole size if the size of
  10632. // the dimension is constant and equals 1. Also, an array section assumes the
  10633. // format of an array subscript if no colon is used.
  10634. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10635. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10636. return ATy->getSize().getSExtValue() != 1;
  10637. // Size can't be evaluated statically.
  10638. return false;
  10639. }
  10640. assert(OASE && "Expecting array section if not an array subscript.");
  10641. auto *LowerBound = OASE->getLowerBound();
  10642. auto *Length = OASE->getLength();
  10643. // If there is a lower bound that does not evaluates to zero, we are not
  10644. // covering the whole dimension.
  10645. if (LowerBound) {
  10646. llvm::APSInt ConstLowerBound;
  10647. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10648. return false; // Can't get the integer value as a constant.
  10649. if (ConstLowerBound.getSExtValue())
  10650. return true;
  10651. }
  10652. // If we don't have a length we covering the whole dimension.
  10653. if (!Length)
  10654. return false;
  10655. // If the base is a pointer, we don't have a way to get the size of the
  10656. // pointee.
  10657. if (BaseQTy->isPointerType())
  10658. return false;
  10659. // We can only check if the length is the same as the size of the dimension
  10660. // if we have a constant array.
  10661. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10662. if (!CATy)
  10663. return false;
  10664. llvm::APSInt ConstLength;
  10665. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10666. return false; // Can't get the integer value as a constant.
  10667. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10668. }
  10669. // Return true if it can be proven that the provided array expression (array
  10670. // section or array subscript) does NOT specify a single element of the array
  10671. // whose base type is \a BaseQTy.
  10672. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10673. const Expr *E,
  10674. QualType BaseQTy) {
  10675. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10676. // An array subscript always refer to a single element. Also, an array section
  10677. // assumes the format of an array subscript if no colon is used.
  10678. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10679. return false;
  10680. assert(OASE && "Expecting array section if not an array subscript.");
  10681. auto *Length = OASE->getLength();
  10682. // If we don't have a length we have to check if the array has unitary size
  10683. // for this dimension. Also, we should always expect a length if the base type
  10684. // is pointer.
  10685. if (!Length) {
  10686. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10687. return ATy->getSize().getSExtValue() != 1;
  10688. // We cannot assume anything.
  10689. return false;
  10690. }
  10691. // Check if the length evaluates to 1.
  10692. llvm::APSInt ConstLength;
  10693. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10694. return false; // Can't get the integer value as a constant.
  10695. return ConstLength.getSExtValue() != 1;
  10696. }
  10697. // Return the expression of the base of the mappable expression or null if it
  10698. // cannot be determined and do all the necessary checks to see if the expression
  10699. // is valid as a standalone mappable expression. In the process, record all the
  10700. // components of the expression.
  10701. static Expr *CheckMapClauseExpressionBase(
  10702. Sema &SemaRef, Expr *E,
  10703. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10704. OpenMPClauseKind CKind, bool NoDiagnose) {
  10705. SourceLocation ELoc = E->getExprLoc();
  10706. SourceRange ERange = E->getSourceRange();
  10707. // The base of elements of list in a map clause have to be either:
  10708. // - a reference to variable or field.
  10709. // - a member expression.
  10710. // - an array expression.
  10711. //
  10712. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  10713. // reference to 'r'.
  10714. //
  10715. // If we have:
  10716. //
  10717. // struct SS {
  10718. // Bla S;
  10719. // foo() {
  10720. // #pragma omp target map (S.Arr[:12]);
  10721. // }
  10722. // }
  10723. //
  10724. // We want to retrieve the member expression 'this->S';
  10725. Expr *RelevantExpr = nullptr;
  10726. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  10727. // If a list item is an array section, it must specify contiguous storage.
  10728. //
  10729. // For this restriction it is sufficient that we make sure only references
  10730. // to variables or fields and array expressions, and that no array sections
  10731. // exist except in the rightmost expression (unless they cover the whole
  10732. // dimension of the array). E.g. these would be invalid:
  10733. //
  10734. // r.ArrS[3:5].Arr[6:7]
  10735. //
  10736. // r.ArrS[3:5].x
  10737. //
  10738. // but these would be valid:
  10739. // r.ArrS[3].Arr[6:7]
  10740. //
  10741. // r.ArrS[3].x
  10742. bool AllowUnitySizeArraySection = true;
  10743. bool AllowWholeSizeArraySection = true;
  10744. while (!RelevantExpr) {
  10745. E = E->IgnoreParenImpCasts();
  10746. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  10747. if (!isa<VarDecl>(CurE->getDecl()))
  10748. return nullptr;
  10749. RelevantExpr = CurE;
  10750. // If we got a reference to a declaration, we should not expect any array
  10751. // section before that.
  10752. AllowUnitySizeArraySection = false;
  10753. AllowWholeSizeArraySection = false;
  10754. // Record the component.
  10755. CurComponents.emplace_back(CurE, CurE->getDecl());
  10756. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  10757. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  10758. if (isa<CXXThisExpr>(BaseE))
  10759. // We found a base expression: this->Val.
  10760. RelevantExpr = CurE;
  10761. else
  10762. E = BaseE;
  10763. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  10764. if (!NoDiagnose) {
  10765. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  10766. << CurE->getSourceRange();
  10767. return nullptr;
  10768. }
  10769. if (RelevantExpr)
  10770. return nullptr;
  10771. continue;
  10772. }
  10773. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  10774. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  10775. // A bit-field cannot appear in a map clause.
  10776. //
  10777. if (FD->isBitField()) {
  10778. if (!NoDiagnose) {
  10779. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  10780. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  10781. return nullptr;
  10782. }
  10783. if (RelevantExpr)
  10784. return nullptr;
  10785. continue;
  10786. }
  10787. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10788. // If the type of a list item is a reference to a type T then the type
  10789. // will be considered to be T for all purposes of this clause.
  10790. QualType CurType = BaseE->getType().getNonReferenceType();
  10791. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  10792. // A list item cannot be a variable that is a member of a structure with
  10793. // a union type.
  10794. //
  10795. if (auto *RT = CurType->getAs<RecordType>()) {
  10796. if (RT->isUnionType()) {
  10797. if (!NoDiagnose) {
  10798. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  10799. << CurE->getSourceRange();
  10800. return nullptr;
  10801. }
  10802. continue;
  10803. }
  10804. }
  10805. // If we got a member expression, we should not expect any array section
  10806. // before that:
  10807. //
  10808. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  10809. // If a list item is an element of a structure, only the rightmost symbol
  10810. // of the variable reference can be an array section.
  10811. //
  10812. AllowUnitySizeArraySection = false;
  10813. AllowWholeSizeArraySection = false;
  10814. // Record the component.
  10815. CurComponents.emplace_back(CurE, FD);
  10816. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  10817. E = CurE->getBase()->IgnoreParenImpCasts();
  10818. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  10819. if (!NoDiagnose) {
  10820. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10821. << 0 << CurE->getSourceRange();
  10822. return nullptr;
  10823. }
  10824. continue;
  10825. }
  10826. // If we got an array subscript that express the whole dimension we
  10827. // can have any array expressions before. If it only expressing part of
  10828. // the dimension, we can only have unitary-size array expressions.
  10829. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  10830. E->getType()))
  10831. AllowWholeSizeArraySection = false;
  10832. // Record the component - we don't have any declaration associated.
  10833. CurComponents.emplace_back(CurE, nullptr);
  10834. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  10835. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  10836. E = CurE->getBase()->IgnoreParenImpCasts();
  10837. QualType CurType =
  10838. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10839. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10840. // If the type of a list item is a reference to a type T then the type
  10841. // will be considered to be T for all purposes of this clause.
  10842. if (CurType->isReferenceType())
  10843. CurType = CurType->getPointeeType();
  10844. bool IsPointer = CurType->isAnyPointerType();
  10845. if (!IsPointer && !CurType->isArrayType()) {
  10846. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10847. << 0 << CurE->getSourceRange();
  10848. return nullptr;
  10849. }
  10850. bool NotWhole =
  10851. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  10852. bool NotUnity =
  10853. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  10854. if (AllowWholeSizeArraySection) {
  10855. // Any array section is currently allowed. Allowing a whole size array
  10856. // section implies allowing a unity array section as well.
  10857. //
  10858. // If this array section refers to the whole dimension we can still
  10859. // accept other array sections before this one, except if the base is a
  10860. // pointer. Otherwise, only unitary sections are accepted.
  10861. if (NotWhole || IsPointer)
  10862. AllowWholeSizeArraySection = false;
  10863. } else if (AllowUnitySizeArraySection && NotUnity) {
  10864. // A unity or whole array section is not allowed and that is not
  10865. // compatible with the properties of the current array section.
  10866. SemaRef.Diag(
  10867. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  10868. << CurE->getSourceRange();
  10869. return nullptr;
  10870. }
  10871. // Record the component - we don't have any declaration associated.
  10872. CurComponents.emplace_back(CurE, nullptr);
  10873. } else {
  10874. if (!NoDiagnose) {
  10875. // If nothing else worked, this is not a valid map clause expression.
  10876. SemaRef.Diag(
  10877. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  10878. << ERange;
  10879. }
  10880. return nullptr;
  10881. }
  10882. }
  10883. return RelevantExpr;
  10884. }
  10885. // Return true if expression E associated with value VD has conflicts with other
  10886. // map information.
  10887. static bool CheckMapConflicts(
  10888. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  10889. bool CurrentRegionOnly,
  10890. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  10891. OpenMPClauseKind CKind) {
  10892. assert(VD && E);
  10893. SourceLocation ELoc = E->getExprLoc();
  10894. SourceRange ERange = E->getSourceRange();
  10895. // In order to easily check the conflicts we need to match each component of
  10896. // the expression under test with the components of the expressions that are
  10897. // already in the stack.
  10898. assert(!CurComponents.empty() && "Map clause expression with no components!");
  10899. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  10900. "Map clause expression with unexpected base!");
  10901. // Variables to help detecting enclosing problems in data environment nests.
  10902. bool IsEnclosedByDataEnvironmentExpr = false;
  10903. const Expr *EnclosingExpr = nullptr;
  10904. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  10905. VD, CurrentRegionOnly,
  10906. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  10907. StackComponents,
  10908. OpenMPClauseKind) -> bool {
  10909. assert(!StackComponents.empty() &&
  10910. "Map clause expression with no components!");
  10911. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  10912. "Map clause expression with unexpected base!");
  10913. // The whole expression in the stack.
  10914. auto *RE = StackComponents.front().getAssociatedExpression();
  10915. // Expressions must start from the same base. Here we detect at which
  10916. // point both expressions diverge from each other and see if we can
  10917. // detect if the memory referred to both expressions is contiguous and
  10918. // do not overlap.
  10919. auto CI = CurComponents.rbegin();
  10920. auto CE = CurComponents.rend();
  10921. auto SI = StackComponents.rbegin();
  10922. auto SE = StackComponents.rend();
  10923. for (; CI != CE && SI != SE; ++CI, ++SI) {
  10924. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  10925. // At most one list item can be an array item derived from a given
  10926. // variable in map clauses of the same construct.
  10927. if (CurrentRegionOnly &&
  10928. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  10929. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  10930. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  10931. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  10932. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  10933. diag::err_omp_multiple_array_items_in_map_clause)
  10934. << CI->getAssociatedExpression()->getSourceRange();
  10935. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  10936. diag::note_used_here)
  10937. << SI->getAssociatedExpression()->getSourceRange();
  10938. return true;
  10939. }
  10940. // Do both expressions have the same kind?
  10941. if (CI->getAssociatedExpression()->getStmtClass() !=
  10942. SI->getAssociatedExpression()->getStmtClass())
  10943. break;
  10944. // Are we dealing with different variables/fields?
  10945. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  10946. break;
  10947. }
  10948. // Check if the extra components of the expressions in the enclosing
  10949. // data environment are redundant for the current base declaration.
  10950. // If they are, the maps completely overlap, which is legal.
  10951. for (; SI != SE; ++SI) {
  10952. QualType Type;
  10953. if (auto *ASE =
  10954. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  10955. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  10956. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  10957. SI->getAssociatedExpression())) {
  10958. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  10959. Type =
  10960. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10961. }
  10962. if (Type.isNull() || Type->isAnyPointerType() ||
  10963. CheckArrayExpressionDoesNotReferToWholeSize(
  10964. SemaRef, SI->getAssociatedExpression(), Type))
  10965. break;
  10966. }
  10967. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10968. // List items of map clauses in the same construct must not share
  10969. // original storage.
  10970. //
  10971. // If the expressions are exactly the same or one is a subset of the
  10972. // other, it means they are sharing storage.
  10973. if (CI == CE && SI == SE) {
  10974. if (CurrentRegionOnly) {
  10975. if (CKind == OMPC_map)
  10976. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10977. else {
  10978. assert(CKind == OMPC_to || CKind == OMPC_from);
  10979. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10980. << ERange;
  10981. }
  10982. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10983. << RE->getSourceRange();
  10984. return true;
  10985. } else {
  10986. // If we find the same expression in the enclosing data environment,
  10987. // that is legal.
  10988. IsEnclosedByDataEnvironmentExpr = true;
  10989. return false;
  10990. }
  10991. }
  10992. QualType DerivedType =
  10993. std::prev(CI)->getAssociatedDeclaration()->getType();
  10994. SourceLocation DerivedLoc =
  10995. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  10996. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10997. // If the type of a list item is a reference to a type T then the type
  10998. // will be considered to be T for all purposes of this clause.
  10999. DerivedType = DerivedType.getNonReferenceType();
  11000. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11001. // A variable for which the type is pointer and an array section
  11002. // derived from that variable must not appear as list items of map
  11003. // clauses of the same construct.
  11004. //
  11005. // Also, cover one of the cases in:
  11006. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11007. // If any part of the original storage of a list item has corresponding
  11008. // storage in the device data environment, all of the original storage
  11009. // must have corresponding storage in the device data environment.
  11010. //
  11011. if (DerivedType->isAnyPointerType()) {
  11012. if (CI == CE || SI == SE) {
  11013. SemaRef.Diag(
  11014. DerivedLoc,
  11015. diag::err_omp_pointer_mapped_along_with_derived_section)
  11016. << DerivedLoc;
  11017. } else {
  11018. assert(CI != CE && SI != SE);
  11019. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  11020. << DerivedLoc;
  11021. }
  11022. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11023. << RE->getSourceRange();
  11024. return true;
  11025. }
  11026. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11027. // List items of map clauses in the same construct must not share
  11028. // original storage.
  11029. //
  11030. // An expression is a subset of the other.
  11031. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11032. if (CKind == OMPC_map)
  11033. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11034. else {
  11035. assert(CKind == OMPC_to || CKind == OMPC_from);
  11036. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11037. << ERange;
  11038. }
  11039. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11040. << RE->getSourceRange();
  11041. return true;
  11042. }
  11043. // The current expression uses the same base as other expression in the
  11044. // data environment but does not contain it completely.
  11045. if (!CurrentRegionOnly && SI != SE)
  11046. EnclosingExpr = RE;
  11047. // The current expression is a subset of the expression in the data
  11048. // environment.
  11049. IsEnclosedByDataEnvironmentExpr |=
  11050. (!CurrentRegionOnly && CI != CE && SI == SE);
  11051. return false;
  11052. });
  11053. if (CurrentRegionOnly)
  11054. return FoundError;
  11055. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11056. // If any part of the original storage of a list item has corresponding
  11057. // storage in the device data environment, all of the original storage must
  11058. // have corresponding storage in the device data environment.
  11059. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11060. // If a list item is an element of a structure, and a different element of
  11061. // the structure has a corresponding list item in the device data environment
  11062. // prior to a task encountering the construct associated with the map clause,
  11063. // then the list item must also have a corresponding list item in the device
  11064. // data environment prior to the task encountering the construct.
  11065. //
  11066. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11067. SemaRef.Diag(ELoc,
  11068. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11069. << ERange;
  11070. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11071. << EnclosingExpr->getSourceRange();
  11072. return true;
  11073. }
  11074. return FoundError;
  11075. }
  11076. namespace {
  11077. // Utility struct that gathers all the related lists associated with a mappable
  11078. // expression.
  11079. struct MappableVarListInfo final {
  11080. // The list of expressions.
  11081. ArrayRef<Expr *> VarList;
  11082. // The list of processed expressions.
  11083. SmallVector<Expr *, 16> ProcessedVarList;
  11084. // The mappble components for each expression.
  11085. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11086. // The base declaration of the variable.
  11087. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11088. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11089. // We have a list of components and base declarations for each entry in the
  11090. // variable list.
  11091. VarComponents.reserve(VarList.size());
  11092. VarBaseDeclarations.reserve(VarList.size());
  11093. }
  11094. };
  11095. }
  11096. // Check the validity of the provided variable list for the provided clause kind
  11097. // \a CKind. In the check process the valid expressions, and mappable expression
  11098. // components and variables are extracted and used to fill \a Vars,
  11099. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11100. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11101. static void
  11102. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11103. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11104. SourceLocation StartLoc,
  11105. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11106. bool IsMapTypeImplicit = false) {
  11107. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11108. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11109. "Unexpected clause kind with mappable expressions!");
  11110. // Keep track of the mappable components and base declarations in this clause.
  11111. // Each entry in the list is going to have a list of components associated. We
  11112. // record each set of the components so that we can build the clause later on.
  11113. // In the end we should have the same amount of declarations and component
  11114. // lists.
  11115. for (auto &RE : MVLI.VarList) {
  11116. assert(RE && "Null expr in omp to/from/map clause");
  11117. SourceLocation ELoc = RE->getExprLoc();
  11118. auto *VE = RE->IgnoreParenLValueCasts();
  11119. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11120. VE->isInstantiationDependent() ||
  11121. VE->containsUnexpandedParameterPack()) {
  11122. // We can only analyze this information once the missing information is
  11123. // resolved.
  11124. MVLI.ProcessedVarList.push_back(RE);
  11125. continue;
  11126. }
  11127. auto *SimpleExpr = RE->IgnoreParenCasts();
  11128. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11129. SemaRef.Diag(ELoc,
  11130. diag::err_omp_expected_named_var_member_or_array_expression)
  11131. << RE->getSourceRange();
  11132. continue;
  11133. }
  11134. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11135. ValueDecl *CurDeclaration = nullptr;
  11136. // Obtain the array or member expression bases if required. Also, fill the
  11137. // components array with all the components identified in the process.
  11138. auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
  11139. CKind, /*NoDiagnose=*/false);
  11140. if (!BE)
  11141. continue;
  11142. assert(!CurComponents.empty() &&
  11143. "Invalid mappable expression information.");
  11144. // For the following checks, we rely on the base declaration which is
  11145. // expected to be associated with the last component. The declaration is
  11146. // expected to be a variable or a field (if 'this' is being mapped).
  11147. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11148. assert(CurDeclaration && "Null decl on map clause.");
  11149. assert(
  11150. CurDeclaration->isCanonicalDecl() &&
  11151. "Expecting components to have associated only canonical declarations.");
  11152. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11153. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11154. assert((VD || FD) && "Only variables or fields are expected here!");
  11155. (void)FD;
  11156. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11157. // threadprivate variables cannot appear in a map clause.
  11158. // OpenMP 4.5 [2.10.5, target update Construct]
  11159. // threadprivate variables cannot appear in a from clause.
  11160. if (VD && DSAS->isThreadPrivate(VD)) {
  11161. auto DVar = DSAS->getTopDSA(VD, false);
  11162. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11163. << getOpenMPClauseName(CKind);
  11164. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  11165. continue;
  11166. }
  11167. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11168. // A list item cannot appear in both a map clause and a data-sharing
  11169. // attribute clause on the same construct.
  11170. // Check conflicts with other map clause expressions. We check the conflicts
  11171. // with the current construct separately from the enclosing data
  11172. // environment, because the restrictions are different. We only have to
  11173. // check conflicts across regions for the map clauses.
  11174. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11175. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11176. break;
  11177. if (CKind == OMPC_map &&
  11178. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11179. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11180. break;
  11181. // OpenMP 4.5 [2.10.5, target update Construct]
  11182. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11183. // If the type of a list item is a reference to a type T then the type will
  11184. // be considered to be T for all purposes of this clause.
  11185. QualType Type = CurDeclaration->getType().getNonReferenceType();
  11186. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11187. // A list item in a to or from clause must have a mappable type.
  11188. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11189. // A list item must have a mappable type.
  11190. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11191. DSAS, Type))
  11192. continue;
  11193. if (CKind == OMPC_map) {
  11194. // target enter data
  11195. // OpenMP [2.10.2, Restrictions, p. 99]
  11196. // A map-type must be specified in all map clauses and must be either
  11197. // to or alloc.
  11198. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11199. if (DKind == OMPD_target_enter_data &&
  11200. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11201. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11202. << (IsMapTypeImplicit ? 1 : 0)
  11203. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11204. << getOpenMPDirectiveName(DKind);
  11205. continue;
  11206. }
  11207. // target exit_data
  11208. // OpenMP [2.10.3, Restrictions, p. 102]
  11209. // A map-type must be specified in all map clauses and must be either
  11210. // from, release, or delete.
  11211. if (DKind == OMPD_target_exit_data &&
  11212. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11213. MapType == OMPC_MAP_delete)) {
  11214. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11215. << (IsMapTypeImplicit ? 1 : 0)
  11216. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11217. << getOpenMPDirectiveName(DKind);
  11218. continue;
  11219. }
  11220. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11221. // A list item cannot appear in both a map clause and a data-sharing
  11222. // attribute clause on the same construct
  11223. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  11224. DKind == OMPD_target_teams_distribute ||
  11225. DKind == OMPD_target_teams_distribute_parallel_for ||
  11226. DKind == OMPD_target_teams_distribute_parallel_for_simd ||
  11227. DKind == OMPD_target_teams_distribute_simd) && VD) {
  11228. auto DVar = DSAS->getTopDSA(VD, false);
  11229. if (isOpenMPPrivate(DVar.CKind)) {
  11230. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11231. << getOpenMPClauseName(DVar.CKind)
  11232. << getOpenMPClauseName(OMPC_map)
  11233. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  11234. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  11235. continue;
  11236. }
  11237. }
  11238. }
  11239. // Save the current expression.
  11240. MVLI.ProcessedVarList.push_back(RE);
  11241. // Store the components in the stack so that they can be used to check
  11242. // against other clauses later on.
  11243. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  11244. /*WhereFoundClauseKind=*/OMPC_map);
  11245. // Save the components and declaration to create the clause. For purposes of
  11246. // the clause creation, any component list that has has base 'this' uses
  11247. // null as base declaration.
  11248. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11249. MVLI.VarComponents.back().append(CurComponents.begin(),
  11250. CurComponents.end());
  11251. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  11252. : CurDeclaration);
  11253. }
  11254. }
  11255. OMPClause *
  11256. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  11257. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  11258. SourceLocation MapLoc, SourceLocation ColonLoc,
  11259. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11260. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11261. MappableVarListInfo MVLI(VarList);
  11262. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  11263. MapType, IsMapTypeImplicit);
  11264. // We need to produce a map clause even if we don't have variables so that
  11265. // other diagnostics related with non-existing map clauses are accurate.
  11266. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11267. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11268. MVLI.VarComponents, MapTypeModifier, MapType,
  11269. IsMapTypeImplicit, MapLoc);
  11270. }
  11271. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  11272. TypeResult ParsedType) {
  11273. assert(ParsedType.isUsable());
  11274. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  11275. if (ReductionType.isNull())
  11276. return QualType();
  11277. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  11278. // A type name in a declare reduction directive cannot be a function type, an
  11279. // array type, a reference type, or a type qualified with const, volatile or
  11280. // restrict.
  11281. if (ReductionType.hasQualifiers()) {
  11282. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  11283. return QualType();
  11284. }
  11285. if (ReductionType->isFunctionType()) {
  11286. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  11287. return QualType();
  11288. }
  11289. if (ReductionType->isReferenceType()) {
  11290. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  11291. return QualType();
  11292. }
  11293. if (ReductionType->isArrayType()) {
  11294. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  11295. return QualType();
  11296. }
  11297. return ReductionType;
  11298. }
  11299. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  11300. Scope *S, DeclContext *DC, DeclarationName Name,
  11301. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  11302. AccessSpecifier AS, Decl *PrevDeclInScope) {
  11303. SmallVector<Decl *, 8> Decls;
  11304. Decls.reserve(ReductionTypes.size());
  11305. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  11306. forRedeclarationInCurContext());
  11307. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  11308. // A reduction-identifier may not be re-declared in the current scope for the
  11309. // same type or for a type that is compatible according to the base language
  11310. // rules.
  11311. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  11312. OMPDeclareReductionDecl *PrevDRD = nullptr;
  11313. bool InCompoundScope = true;
  11314. if (S != nullptr) {
  11315. // Find previous declaration with the same name not referenced in other
  11316. // declarations.
  11317. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  11318. InCompoundScope =
  11319. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  11320. LookupName(Lookup, S);
  11321. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  11322. /*AllowInlineNamespace=*/false);
  11323. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  11324. auto Filter = Lookup.makeFilter();
  11325. while (Filter.hasNext()) {
  11326. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  11327. if (InCompoundScope) {
  11328. auto I = UsedAsPrevious.find(PrevDecl);
  11329. if (I == UsedAsPrevious.end())
  11330. UsedAsPrevious[PrevDecl] = false;
  11331. if (auto *D = PrevDecl->getPrevDeclInScope())
  11332. UsedAsPrevious[D] = true;
  11333. }
  11334. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  11335. PrevDecl->getLocation();
  11336. }
  11337. Filter.done();
  11338. if (InCompoundScope) {
  11339. for (auto &PrevData : UsedAsPrevious) {
  11340. if (!PrevData.second) {
  11341. PrevDRD = PrevData.first;
  11342. break;
  11343. }
  11344. }
  11345. }
  11346. } else if (PrevDeclInScope != nullptr) {
  11347. auto *PrevDRDInScope = PrevDRD =
  11348. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  11349. do {
  11350. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  11351. PrevDRDInScope->getLocation();
  11352. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  11353. } while (PrevDRDInScope != nullptr);
  11354. }
  11355. for (auto &TyData : ReductionTypes) {
  11356. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  11357. bool Invalid = false;
  11358. if (I != PreviousRedeclTypes.end()) {
  11359. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  11360. << TyData.first;
  11361. Diag(I->second, diag::note_previous_definition);
  11362. Invalid = true;
  11363. }
  11364. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  11365. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  11366. Name, TyData.first, PrevDRD);
  11367. DC->addDecl(DRD);
  11368. DRD->setAccess(AS);
  11369. Decls.push_back(DRD);
  11370. if (Invalid)
  11371. DRD->setInvalidDecl();
  11372. else
  11373. PrevDRD = DRD;
  11374. }
  11375. return DeclGroupPtrTy::make(
  11376. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  11377. }
  11378. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  11379. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11380. // Enter new function scope.
  11381. PushFunctionScope();
  11382. getCurFunction()->setHasBranchProtectedScope();
  11383. getCurFunction()->setHasOMPDeclareReductionCombiner();
  11384. if (S != nullptr)
  11385. PushDeclContext(S, DRD);
  11386. else
  11387. CurContext = DRD;
  11388. PushExpressionEvaluationContext(
  11389. ExpressionEvaluationContext::PotentiallyEvaluated);
  11390. QualType ReductionType = DRD->getType();
  11391. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  11392. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  11393. // uses semantics of argument handles by value, but it should be passed by
  11394. // reference. C lang does not support references, so pass all parameters as
  11395. // pointers.
  11396. // Create 'T omp_in;' variable.
  11397. auto *OmpInParm =
  11398. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  11399. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  11400. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  11401. // uses semantics of argument handles by value, but it should be passed by
  11402. // reference. C lang does not support references, so pass all parameters as
  11403. // pointers.
  11404. // Create 'T omp_out;' variable.
  11405. auto *OmpOutParm =
  11406. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  11407. if (S != nullptr) {
  11408. PushOnScopeChains(OmpInParm, S);
  11409. PushOnScopeChains(OmpOutParm, S);
  11410. } else {
  11411. DRD->addDecl(OmpInParm);
  11412. DRD->addDecl(OmpOutParm);
  11413. }
  11414. }
  11415. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  11416. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11417. DiscardCleanupsInEvaluationContext();
  11418. PopExpressionEvaluationContext();
  11419. PopDeclContext();
  11420. PopFunctionScopeInfo();
  11421. if (Combiner != nullptr)
  11422. DRD->setCombiner(Combiner);
  11423. else
  11424. DRD->setInvalidDecl();
  11425. }
  11426. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  11427. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11428. // Enter new function scope.
  11429. PushFunctionScope();
  11430. getCurFunction()->setHasBranchProtectedScope();
  11431. if (S != nullptr)
  11432. PushDeclContext(S, DRD);
  11433. else
  11434. CurContext = DRD;
  11435. PushExpressionEvaluationContext(
  11436. ExpressionEvaluationContext::PotentiallyEvaluated);
  11437. QualType ReductionType = DRD->getType();
  11438. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  11439. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  11440. // uses semantics of argument handles by value, but it should be passed by
  11441. // reference. C lang does not support references, so pass all parameters as
  11442. // pointers.
  11443. // Create 'T omp_priv;' variable.
  11444. auto *OmpPrivParm =
  11445. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  11446. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  11447. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  11448. // uses semantics of argument handles by value, but it should be passed by
  11449. // reference. C lang does not support references, so pass all parameters as
  11450. // pointers.
  11451. // Create 'T omp_orig;' variable.
  11452. auto *OmpOrigParm =
  11453. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  11454. if (S != nullptr) {
  11455. PushOnScopeChains(OmpPrivParm, S);
  11456. PushOnScopeChains(OmpOrigParm, S);
  11457. } else {
  11458. DRD->addDecl(OmpPrivParm);
  11459. DRD->addDecl(OmpOrigParm);
  11460. }
  11461. return OmpPrivParm;
  11462. }
  11463. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  11464. VarDecl *OmpPrivParm) {
  11465. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11466. DiscardCleanupsInEvaluationContext();
  11467. PopExpressionEvaluationContext();
  11468. PopDeclContext();
  11469. PopFunctionScopeInfo();
  11470. if (Initializer != nullptr) {
  11471. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  11472. } else if (OmpPrivParm->hasInit()) {
  11473. DRD->setInitializer(OmpPrivParm->getInit(),
  11474. OmpPrivParm->isDirectInit()
  11475. ? OMPDeclareReductionDecl::DirectInit
  11476. : OMPDeclareReductionDecl::CopyInit);
  11477. } else {
  11478. DRD->setInvalidDecl();
  11479. }
  11480. }
  11481. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  11482. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  11483. for (auto *D : DeclReductions.get()) {
  11484. if (IsValid) {
  11485. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11486. if (S != nullptr)
  11487. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  11488. } else
  11489. D->setInvalidDecl();
  11490. }
  11491. return DeclReductions;
  11492. }
  11493. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  11494. SourceLocation StartLoc,
  11495. SourceLocation LParenLoc,
  11496. SourceLocation EndLoc) {
  11497. Expr *ValExpr = NumTeams;
  11498. Stmt *HelperValStmt = nullptr;
  11499. // OpenMP [teams Constrcut, Restrictions]
  11500. // The num_teams expression must evaluate to a positive integer value.
  11501. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11502. /*StrictlyPositive=*/true))
  11503. return nullptr;
  11504. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11505. OpenMPDirectiveKind CaptureRegion =
  11506. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11507. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11508. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11509. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11510. HelperValStmt = buildPreInits(Context, Captures);
  11511. }
  11512. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11513. StartLoc, LParenLoc, EndLoc);
  11514. }
  11515. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11516. SourceLocation StartLoc,
  11517. SourceLocation LParenLoc,
  11518. SourceLocation EndLoc) {
  11519. Expr *ValExpr = ThreadLimit;
  11520. Stmt *HelperValStmt = nullptr;
  11521. // OpenMP [teams Constrcut, Restrictions]
  11522. // The thread_limit expression must evaluate to a positive integer value.
  11523. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11524. /*StrictlyPositive=*/true))
  11525. return nullptr;
  11526. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11527. OpenMPDirectiveKind CaptureRegion =
  11528. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11529. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11530. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11531. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11532. HelperValStmt = buildPreInits(Context, Captures);
  11533. }
  11534. return new (Context) OMPThreadLimitClause(
  11535. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11536. }
  11537. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11538. SourceLocation StartLoc,
  11539. SourceLocation LParenLoc,
  11540. SourceLocation EndLoc) {
  11541. Expr *ValExpr = Priority;
  11542. // OpenMP [2.9.1, task Constrcut]
  11543. // The priority-value is a non-negative numerical scalar expression.
  11544. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11545. /*StrictlyPositive=*/false))
  11546. return nullptr;
  11547. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11548. }
  11549. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11550. SourceLocation StartLoc,
  11551. SourceLocation LParenLoc,
  11552. SourceLocation EndLoc) {
  11553. Expr *ValExpr = Grainsize;
  11554. // OpenMP [2.9.2, taskloop Constrcut]
  11555. // The parameter of the grainsize clause must be a positive integer
  11556. // expression.
  11557. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11558. /*StrictlyPositive=*/true))
  11559. return nullptr;
  11560. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11561. }
  11562. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11563. SourceLocation StartLoc,
  11564. SourceLocation LParenLoc,
  11565. SourceLocation EndLoc) {
  11566. Expr *ValExpr = NumTasks;
  11567. // OpenMP [2.9.2, taskloop Constrcut]
  11568. // The parameter of the num_tasks clause must be a positive integer
  11569. // expression.
  11570. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11571. /*StrictlyPositive=*/true))
  11572. return nullptr;
  11573. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11574. }
  11575. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11576. SourceLocation LParenLoc,
  11577. SourceLocation EndLoc) {
  11578. // OpenMP [2.13.2, critical construct, Description]
  11579. // ... where hint-expression is an integer constant expression that evaluates
  11580. // to a valid lock hint.
  11581. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11582. if (HintExpr.isInvalid())
  11583. return nullptr;
  11584. return new (Context)
  11585. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11586. }
  11587. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11588. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11589. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11590. SourceLocation EndLoc) {
  11591. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11592. std::string Values;
  11593. Values += "'";
  11594. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11595. Values += "'";
  11596. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11597. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11598. return nullptr;
  11599. }
  11600. Expr *ValExpr = ChunkSize;
  11601. Stmt *HelperValStmt = nullptr;
  11602. if (ChunkSize) {
  11603. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11604. !ChunkSize->isInstantiationDependent() &&
  11605. !ChunkSize->containsUnexpandedParameterPack()) {
  11606. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11607. ExprResult Val =
  11608. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11609. if (Val.isInvalid())
  11610. return nullptr;
  11611. ValExpr = Val.get();
  11612. // OpenMP [2.7.1, Restrictions]
  11613. // chunk_size must be a loop invariant integer expression with a positive
  11614. // value.
  11615. llvm::APSInt Result;
  11616. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11617. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11618. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11619. << "dist_schedule" << ChunkSize->getSourceRange();
  11620. return nullptr;
  11621. }
  11622. } else if (getOpenMPCaptureRegionForClause(
  11623. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  11624. OMPD_unknown &&
  11625. !CurContext->isDependentContext()) {
  11626. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11627. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11628. HelperValStmt = buildPreInits(Context, Captures);
  11629. }
  11630. }
  11631. }
  11632. return new (Context)
  11633. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11634. Kind, ValExpr, HelperValStmt);
  11635. }
  11636. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11637. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11638. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11639. SourceLocation KindLoc, SourceLocation EndLoc) {
  11640. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11641. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11642. std::string Value;
  11643. SourceLocation Loc;
  11644. Value += "'";
  11645. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11646. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11647. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11648. Loc = MLoc;
  11649. } else {
  11650. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11651. OMPC_DEFAULTMAP_scalar);
  11652. Loc = KindLoc;
  11653. }
  11654. Value += "'";
  11655. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11656. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11657. return nullptr;
  11658. }
  11659. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11660. return new (Context)
  11661. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11662. }
  11663. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11664. DeclContext *CurLexicalContext = getCurLexicalContext();
  11665. if (!CurLexicalContext->isFileContext() &&
  11666. !CurLexicalContext->isExternCContext() &&
  11667. !CurLexicalContext->isExternCXXContext() &&
  11668. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11669. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11670. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11671. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11672. Diag(Loc, diag::err_omp_region_not_file_context);
  11673. return false;
  11674. }
  11675. if (IsInOpenMPDeclareTargetContext) {
  11676. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11677. return false;
  11678. }
  11679. IsInOpenMPDeclareTargetContext = true;
  11680. return true;
  11681. }
  11682. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11683. assert(IsInOpenMPDeclareTargetContext &&
  11684. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11685. IsInOpenMPDeclareTargetContext = false;
  11686. }
  11687. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11688. CXXScopeSpec &ScopeSpec,
  11689. const DeclarationNameInfo &Id,
  11690. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11691. NamedDeclSetType &SameDirectiveDecls) {
  11692. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11693. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11694. if (Lookup.isAmbiguous())
  11695. return;
  11696. Lookup.suppressDiagnostics();
  11697. if (!Lookup.isSingleResult()) {
  11698. if (TypoCorrection Corrected =
  11699. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  11700. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  11701. CTK_ErrorRecovery)) {
  11702. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  11703. << Id.getName());
  11704. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  11705. return;
  11706. }
  11707. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  11708. return;
  11709. }
  11710. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  11711. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  11712. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  11713. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  11714. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  11715. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  11716. ND->addAttr(A);
  11717. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11718. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  11719. checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
  11720. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  11721. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  11722. << Id.getName();
  11723. }
  11724. } else
  11725. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  11726. }
  11727. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  11728. Sema &SemaRef, Decl *D) {
  11729. if (!D)
  11730. return;
  11731. Decl *LD = nullptr;
  11732. if (isa<TagDecl>(D)) {
  11733. LD = cast<TagDecl>(D)->getDefinition();
  11734. } else if (isa<VarDecl>(D)) {
  11735. LD = cast<VarDecl>(D)->getDefinition();
  11736. // If this is an implicit variable that is legal and we do not need to do
  11737. // anything.
  11738. if (cast<VarDecl>(D)->isImplicit()) {
  11739. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11740. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11741. D->addAttr(A);
  11742. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11743. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11744. return;
  11745. }
  11746. } else if (isa<FunctionDecl>(D)) {
  11747. const FunctionDecl *FD = nullptr;
  11748. if (cast<FunctionDecl>(D)->hasBody(FD))
  11749. LD = const_cast<FunctionDecl *>(FD);
  11750. // If the definition is associated with the current declaration in the
  11751. // target region (it can be e.g. a lambda) that is legal and we do not need
  11752. // to do anything else.
  11753. if (LD == D) {
  11754. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11755. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11756. D->addAttr(A);
  11757. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11758. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11759. return;
  11760. }
  11761. }
  11762. if (!LD)
  11763. LD = D;
  11764. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11765. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  11766. // Outlined declaration is not declared target.
  11767. if (LD->isOutOfLine()) {
  11768. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11769. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11770. } else {
  11771. DeclContext *DC = LD->getDeclContext();
  11772. while (DC) {
  11773. if (isa<FunctionDecl>(DC) &&
  11774. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  11775. break;
  11776. DC = DC->getParent();
  11777. }
  11778. if (DC)
  11779. return;
  11780. // Is not declared in target context.
  11781. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11782. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11783. }
  11784. // Mark decl as declared target to prevent further diagnostic.
  11785. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11786. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11787. D->addAttr(A);
  11788. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11789. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11790. }
  11791. }
  11792. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  11793. Sema &SemaRef, DSAStackTy *Stack,
  11794. ValueDecl *VD) {
  11795. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  11796. return true;
  11797. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  11798. return false;
  11799. return true;
  11800. }
  11801. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
  11802. if (!D || D->isInvalidDecl())
  11803. return;
  11804. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  11805. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  11806. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  11807. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  11808. if (DSAStack->isThreadPrivate(VD)) {
  11809. Diag(SL, diag::err_omp_threadprivate_in_target);
  11810. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  11811. return;
  11812. }
  11813. }
  11814. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  11815. // Problem if any with var declared with incomplete type will be reported
  11816. // as normal, so no need to check it here.
  11817. if ((E || !VD->getType()->isIncompleteType()) &&
  11818. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  11819. // Mark decl as declared target to prevent further diagnostic.
  11820. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  11821. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11822. Context, OMPDeclareTargetDeclAttr::MT_To);
  11823. VD->addAttr(A);
  11824. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11825. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  11826. }
  11827. return;
  11828. }
  11829. }
  11830. if (!E) {
  11831. // Checking declaration inside declare target region.
  11832. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11833. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  11834. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11835. Context, OMPDeclareTargetDeclAttr::MT_To);
  11836. D->addAttr(A);
  11837. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11838. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11839. }
  11840. return;
  11841. }
  11842. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  11843. }
  11844. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  11845. SourceLocation StartLoc,
  11846. SourceLocation LParenLoc,
  11847. SourceLocation EndLoc) {
  11848. MappableVarListInfo MVLI(VarList);
  11849. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  11850. if (MVLI.ProcessedVarList.empty())
  11851. return nullptr;
  11852. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11853. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11854. MVLI.VarComponents);
  11855. }
  11856. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  11857. SourceLocation StartLoc,
  11858. SourceLocation LParenLoc,
  11859. SourceLocation EndLoc) {
  11860. MappableVarListInfo MVLI(VarList);
  11861. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  11862. if (MVLI.ProcessedVarList.empty())
  11863. return nullptr;
  11864. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11865. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11866. MVLI.VarComponents);
  11867. }
  11868. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  11869. SourceLocation StartLoc,
  11870. SourceLocation LParenLoc,
  11871. SourceLocation EndLoc) {
  11872. MappableVarListInfo MVLI(VarList);
  11873. SmallVector<Expr *, 8> PrivateCopies;
  11874. SmallVector<Expr *, 8> Inits;
  11875. for (auto &RefExpr : VarList) {
  11876. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  11877. SourceLocation ELoc;
  11878. SourceRange ERange;
  11879. Expr *SimpleRefExpr = RefExpr;
  11880. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11881. if (Res.second) {
  11882. // It will be analyzed later.
  11883. MVLI.ProcessedVarList.push_back(RefExpr);
  11884. PrivateCopies.push_back(nullptr);
  11885. Inits.push_back(nullptr);
  11886. }
  11887. ValueDecl *D = Res.first;
  11888. if (!D)
  11889. continue;
  11890. QualType Type = D->getType();
  11891. Type = Type.getNonReferenceType().getUnqualifiedType();
  11892. auto *VD = dyn_cast<VarDecl>(D);
  11893. // Item should be a pointer or reference to pointer.
  11894. if (!Type->isPointerType()) {
  11895. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  11896. << 0 << RefExpr->getSourceRange();
  11897. continue;
  11898. }
  11899. // Build the private variable and the expression that refers to it.
  11900. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  11901. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11902. if (VDPrivate->isInvalidDecl())
  11903. continue;
  11904. CurContext->addDecl(VDPrivate);
  11905. auto VDPrivateRefExpr = buildDeclRefExpr(
  11906. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11907. // Add temporary variable to initialize the private copy of the pointer.
  11908. auto *VDInit =
  11909. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  11910. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11911. RefExpr->getExprLoc());
  11912. AddInitializerToDecl(VDPrivate,
  11913. DefaultLvalueConversion(VDInitRefExpr).get(),
  11914. /*DirectInit=*/false);
  11915. // If required, build a capture to implement the privatization initialized
  11916. // with the current list item value.
  11917. DeclRefExpr *Ref = nullptr;
  11918. if (!VD)
  11919. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11920. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  11921. PrivateCopies.push_back(VDPrivateRefExpr);
  11922. Inits.push_back(VDInitRefExpr);
  11923. // We need to add a data sharing attribute for this variable to make sure it
  11924. // is correctly captured. A variable that shows up in a use_device_ptr has
  11925. // similar properties of a first private variable.
  11926. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11927. // Create a mappable component for the list item. List items in this clause
  11928. // only need a component.
  11929. MVLI.VarBaseDeclarations.push_back(D);
  11930. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11931. MVLI.VarComponents.back().push_back(
  11932. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  11933. }
  11934. if (MVLI.ProcessedVarList.empty())
  11935. return nullptr;
  11936. return OMPUseDevicePtrClause::Create(
  11937. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11938. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11939. }
  11940. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  11941. SourceLocation StartLoc,
  11942. SourceLocation LParenLoc,
  11943. SourceLocation EndLoc) {
  11944. MappableVarListInfo MVLI(VarList);
  11945. for (auto &RefExpr : VarList) {
  11946. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  11947. SourceLocation ELoc;
  11948. SourceRange ERange;
  11949. Expr *SimpleRefExpr = RefExpr;
  11950. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11951. if (Res.second) {
  11952. // It will be analyzed later.
  11953. MVLI.ProcessedVarList.push_back(RefExpr);
  11954. }
  11955. ValueDecl *D = Res.first;
  11956. if (!D)
  11957. continue;
  11958. QualType Type = D->getType();
  11959. // item should be a pointer or array or reference to pointer or array
  11960. if (!Type.getNonReferenceType()->isPointerType() &&
  11961. !Type.getNonReferenceType()->isArrayType()) {
  11962. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  11963. << 0 << RefExpr->getSourceRange();
  11964. continue;
  11965. }
  11966. // Check if the declaration in the clause does not show up in any data
  11967. // sharing attribute.
  11968. auto DVar = DSAStack->getTopDSA(D, false);
  11969. if (isOpenMPPrivate(DVar.CKind)) {
  11970. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11971. << getOpenMPClauseName(DVar.CKind)
  11972. << getOpenMPClauseName(OMPC_is_device_ptr)
  11973. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11974. ReportOriginalDSA(*this, DSAStack, D, DVar);
  11975. continue;
  11976. }
  11977. Expr *ConflictExpr;
  11978. if (DSAStack->checkMappableExprComponentListsForDecl(
  11979. D, /*CurrentRegionOnly=*/true,
  11980. [&ConflictExpr](
  11981. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  11982. OpenMPClauseKind) -> bool {
  11983. ConflictExpr = R.front().getAssociatedExpression();
  11984. return true;
  11985. })) {
  11986. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  11987. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  11988. << ConflictExpr->getSourceRange();
  11989. continue;
  11990. }
  11991. // Store the components in the stack so that they can be used to check
  11992. // against other clauses later on.
  11993. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  11994. DSAStack->addMappableExpressionComponents(
  11995. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  11996. // Record the expression we've just processed.
  11997. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  11998. // Create a mappable component for the list item. List items in this clause
  11999. // only need a component. We use a null declaration to signal fields in
  12000. // 'this'.
  12001. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12002. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12003. "Unexpected device pointer expression!");
  12004. MVLI.VarBaseDeclarations.push_back(
  12005. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12006. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12007. MVLI.VarComponents.back().push_back(MC);
  12008. }
  12009. if (MVLI.ProcessedVarList.empty())
  12010. return nullptr;
  12011. return OMPIsDevicePtrClause::Create(
  12012. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12013. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12014. }