SemaOpenMP.cpp 296 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250
  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/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Basic/OpenMPKinds.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/Lookup.h"
  28. #include "clang/Sema/Scope.h"
  29. #include "clang/Sema/ScopeInfo.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. using namespace clang;
  32. // HLSL Change Starts
  33. // No OpenMP Sema support, so simply skip all of this compilation.
  34. // Here are enough stubs to link the current targets.
  35. #if 1
  36. //===----------------------------------------------------------------------===//
  37. // Stack of data-sharing attributes for variables
  38. //===----------------------------------------------------------------------===//
  39. void Sema::InitDataSharingAttributesStack() {
  40. llvm_unreachable("HLSL does not support OpenMP constructs");
  41. }
  42. bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
  43. llvm_unreachable("HLSL does not support OpenMP constructs");
  44. }
  45. bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
  46. llvm_unreachable("HLSL does not support OpenMP constructs");
  47. }
  48. void Sema::DestroyDataSharingAttributesStack() {
  49. llvm_unreachable("HLSL does not support OpenMP constructs");
  50. }
  51. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  52. const DeclarationNameInfo &DirName,
  53. Scope *CurScope, SourceLocation Loc) {
  54. llvm_unreachable("HLSL does not support OpenMP constructs");
  55. }
  56. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  57. llvm_unreachable("HLSL does not support OpenMP constructs");
  58. }
  59. void Sema::EndOpenMPClause() {
  60. llvm_unreachable("HLSL does not support OpenMP constructs");
  61. }
  62. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  63. llvm_unreachable("HLSL does not support OpenMP constructs");
  64. }
  65. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  66. CXXScopeSpec &ScopeSpec,
  67. const DeclarationNameInfo &Id) {
  68. llvm_unreachable("HLSL does not support OpenMP constructs");
  69. }
  70. Sema::DeclGroupPtrTy
  71. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  72. ArrayRef<Expr *> VarList) {
  73. llvm_unreachable("HLSL does not support OpenMP constructs");
  74. }
  75. OMPThreadPrivateDecl *
  76. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  77. llvm_unreachable("HLSL does not support OpenMP constructs");
  78. }
  79. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  80. llvm_unreachable("HLSL does not support OpenMP constructs");
  81. }
  82. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  83. ArrayRef<OMPClause *> Clauses) {
  84. llvm_unreachable("HLSL does not support OpenMP constructs");
  85. }
  86. StmtResult Sema::ActOnOpenMPExecutableDirective(
  87. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  88. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  89. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  90. llvm_unreachable("HLSL does not support OpenMP constructs");
  91. }
  92. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  93. Stmt *AStmt,
  94. SourceLocation StartLoc,
  95. SourceLocation EndLoc) {
  96. llvm_unreachable("HLSL does not support OpenMP constructs");
  97. }
  98. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  99. llvm_unreachable("HLSL does not support OpenMP constructs");
  100. }
  101. StmtResult Sema::ActOnOpenMPSimdDirective(
  102. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  103. SourceLocation EndLoc,
  104. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  105. llvm_unreachable("HLSL does not support OpenMP constructs");
  106. }
  107. StmtResult Sema::ActOnOpenMPForDirective(
  108. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  109. SourceLocation EndLoc,
  110. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  111. llvm_unreachable("HLSL does not support OpenMP constructs");
  112. }
  113. StmtResult Sema::ActOnOpenMPForSimdDirective(
  114. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  115. SourceLocation EndLoc,
  116. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  117. llvm_unreachable("HLSL does not support OpenMP constructs");
  118. }
  119. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  120. Stmt *AStmt,
  121. SourceLocation StartLoc,
  122. SourceLocation EndLoc) {
  123. llvm_unreachable("HLSL does not support OpenMP constructs");
  124. }
  125. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  126. SourceLocation StartLoc,
  127. SourceLocation EndLoc) {
  128. llvm_unreachable("HLSL does not support OpenMP constructs");
  129. }
  130. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  131. Stmt *AStmt,
  132. SourceLocation StartLoc,
  133. SourceLocation EndLoc) {
  134. llvm_unreachable("HLSL does not support OpenMP constructs");
  135. }
  136. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  137. SourceLocation StartLoc,
  138. SourceLocation EndLoc) {
  139. llvm_unreachable("HLSL does not support OpenMP constructs");
  140. }
  141. StmtResult
  142. Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
  143. Stmt *AStmt, SourceLocation StartLoc,
  144. SourceLocation EndLoc) {
  145. llvm_unreachable("HLSL does not support OpenMP constructs");
  146. }
  147. StmtResult Sema::ActOnOpenMPParallelForDirective(
  148. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  149. SourceLocation EndLoc,
  150. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  151. llvm_unreachable("HLSL does not support OpenMP constructs");
  152. }
  153. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  154. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  155. SourceLocation EndLoc,
  156. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  157. llvm_unreachable("HLSL does not support OpenMP constructs");
  158. }
  159. StmtResult
  160. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  161. Stmt *AStmt, SourceLocation StartLoc,
  162. SourceLocation EndLoc) {
  163. llvm_unreachable("HLSL does not support OpenMP constructs");
  164. }
  165. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  166. Stmt *AStmt, SourceLocation StartLoc,
  167. SourceLocation EndLoc) {
  168. llvm_unreachable("HLSL does not support OpenMP constructs");
  169. }
  170. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  171. SourceLocation EndLoc) {
  172. llvm_unreachable("HLSL does not support OpenMP constructs");
  173. }
  174. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  175. SourceLocation EndLoc) {
  176. llvm_unreachable("HLSL does not support OpenMP constructs");
  177. }
  178. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  179. SourceLocation EndLoc) {
  180. llvm_unreachable("HLSL does not support OpenMP constructs");
  181. }
  182. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  183. SourceLocation StartLoc,
  184. SourceLocation EndLoc) {
  185. llvm_unreachable("HLSL does not support OpenMP constructs");
  186. }
  187. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  188. SourceLocation StartLoc,
  189. SourceLocation EndLoc) {
  190. llvm_unreachable("HLSL does not support OpenMP constructs");
  191. }
  192. StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
  193. SourceLocation StartLoc,
  194. SourceLocation EndLoc) {
  195. llvm_unreachable("HLSL does not support OpenMP constructs");
  196. }
  197. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  198. Stmt *AStmt,
  199. SourceLocation StartLoc,
  200. SourceLocation EndLoc) {
  201. llvm_unreachable("HLSL does not support OpenMP constructs");
  202. }
  203. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  204. Stmt *AStmt,
  205. SourceLocation StartLoc,
  206. SourceLocation EndLoc) {
  207. llvm_unreachable("HLSL does not support OpenMP constructs");
  208. }
  209. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  210. Stmt *AStmt, SourceLocation StartLoc,
  211. SourceLocation EndLoc) {
  212. llvm_unreachable("HLSL does not support OpenMP constructs");
  213. }
  214. StmtResult
  215. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  216. SourceLocation EndLoc,
  217. OpenMPDirectiveKind CancelRegion) {
  218. llvm_unreachable("HLSL does not support OpenMP constructs");
  219. }
  220. StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
  221. SourceLocation EndLoc,
  222. OpenMPDirectiveKind CancelRegion) {
  223. llvm_unreachable("HLSL does not support OpenMP constructs");
  224. }
  225. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  226. SourceLocation StartLoc,
  227. SourceLocation LParenLoc,
  228. SourceLocation EndLoc) {
  229. llvm_unreachable("HLSL does not support OpenMP constructs");
  230. }
  231. OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
  232. SourceLocation LParenLoc,
  233. SourceLocation EndLoc) {
  234. llvm_unreachable("HLSL does not support OpenMP constructs");
  235. }
  236. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  237. SourceLocation StartLoc,
  238. SourceLocation LParenLoc,
  239. SourceLocation EndLoc) {
  240. llvm_unreachable("HLSL does not support OpenMP constructs");
  241. }
  242. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  243. Expr *Op) {
  244. llvm_unreachable("HLSL does not support OpenMP constructs");
  245. }
  246. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  247. SourceLocation StartLoc,
  248. SourceLocation LParenLoc,
  249. SourceLocation EndLoc) {
  250. llvm_unreachable("HLSL does not support OpenMP constructs");
  251. }
  252. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  253. OpenMPClauseKind CKind) {
  254. llvm_unreachable("HLSL does not support OpenMP constructs");
  255. }
  256. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  257. SourceLocation LParenLoc,
  258. SourceLocation EndLoc) {
  259. llvm_unreachable("HLSL does not support OpenMP constructs");
  260. }
  261. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  262. SourceLocation StartLoc,
  263. SourceLocation LParenLoc,
  264. SourceLocation EndLoc) {
  265. llvm_unreachable("HLSL does not support OpenMP constructs");
  266. }
  267. OMPClause *Sema::ActOnOpenMPSimpleClause(
  268. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  269. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  270. llvm_unreachable("HLSL does not support OpenMP constructs");
  271. }
  272. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  273. SourceLocation KindKwLoc,
  274. SourceLocation StartLoc,
  275. SourceLocation LParenLoc,
  276. SourceLocation EndLoc) {
  277. llvm_unreachable("HLSL does not support OpenMP constructs");
  278. }
  279. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  280. SourceLocation KindKwLoc,
  281. SourceLocation StartLoc,
  282. SourceLocation LParenLoc,
  283. SourceLocation EndLoc) {
  284. llvm_unreachable("HLSL does not support OpenMP constructs");
  285. }
  286. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  287. OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
  288. SourceLocation StartLoc, SourceLocation LParenLoc,
  289. SourceLocation ArgumentLoc, SourceLocation CommaLoc,
  290. SourceLocation EndLoc) {
  291. llvm_unreachable("HLSL does not support OpenMP constructs");
  292. }
  293. OMPClause *Sema::ActOnOpenMPScheduleClause(
  294. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  295. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  296. SourceLocation EndLoc) {
  297. llvm_unreachable("HLSL does not support OpenMP constructs");
  298. }
  299. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  300. SourceLocation StartLoc,
  301. SourceLocation EndLoc) {
  302. llvm_unreachable("HLSL does not support OpenMP constructs");
  303. }
  304. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  305. SourceLocation EndLoc) {
  306. llvm_unreachable("HLSL does not support OpenMP constructs");
  307. }
  308. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  309. SourceLocation EndLoc) {
  310. llvm_unreachable("HLSL does not support OpenMP constructs");
  311. }
  312. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  313. SourceLocation EndLoc) {
  314. llvm_unreachable("HLSL does not support OpenMP constructs");
  315. }
  316. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  317. SourceLocation EndLoc) {
  318. llvm_unreachable("HLSL does not support OpenMP constructs");
  319. }
  320. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  321. SourceLocation EndLoc) {
  322. llvm_unreachable("HLSL does not support OpenMP constructs");
  323. }
  324. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  325. SourceLocation EndLoc) {
  326. llvm_unreachable("HLSL does not support OpenMP constructs");
  327. }
  328. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  329. SourceLocation EndLoc) {
  330. llvm_unreachable("HLSL does not support OpenMP constructs");
  331. }
  332. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  333. SourceLocation EndLoc) {
  334. llvm_unreachable("HLSL does not support OpenMP constructs");
  335. }
  336. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  337. SourceLocation EndLoc) {
  338. llvm_unreachable("HLSL does not support OpenMP constructs");
  339. }
  340. OMPClause *Sema::ActOnOpenMPVarListClause(
  341. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  342. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  343. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  344. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  345. SourceLocation DepLoc) {
  346. llvm_unreachable("HLSL does not support OpenMP constructs");
  347. }
  348. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  349. SourceLocation StartLoc,
  350. SourceLocation LParenLoc,
  351. SourceLocation EndLoc) {
  352. llvm_unreachable("HLSL does not support OpenMP constructs");
  353. }
  354. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  355. SourceLocation StartLoc,
  356. SourceLocation LParenLoc,
  357. SourceLocation EndLoc) {
  358. llvm_unreachable("HLSL does not support OpenMP constructs");
  359. }
  360. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  361. SourceLocation StartLoc,
  362. SourceLocation LParenLoc,
  363. SourceLocation EndLoc) {
  364. llvm_unreachable("HLSL does not support OpenMP constructs");
  365. }
  366. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  367. SourceLocation StartLoc,
  368. SourceLocation LParenLoc,
  369. SourceLocation EndLoc) {
  370. llvm_unreachable("HLSL does not support OpenMP constructs");
  371. }
  372. OMPClause *Sema::ActOnOpenMPReductionClause(
  373. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  374. SourceLocation ColonLoc, SourceLocation EndLoc,
  375. CXXScopeSpec &ReductionIdScopeSpec,
  376. const DeclarationNameInfo &ReductionId) {
  377. llvm_unreachable("HLSL does not support OpenMP constructs");
  378. }
  379. OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
  380. SourceLocation StartLoc,
  381. SourceLocation LParenLoc,
  382. SourceLocation ColonLoc,
  383. SourceLocation EndLoc) {
  384. llvm_unreachable("HLSL does not support OpenMP constructs");
  385. }
  386. OMPClause *Sema::ActOnOpenMPAlignedClause(
  387. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  388. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  389. llvm_unreachable("HLSL does not support OpenMP constructs");
  390. }
  391. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  392. SourceLocation StartLoc,
  393. SourceLocation LParenLoc,
  394. SourceLocation EndLoc) {
  395. llvm_unreachable("HLSL does not support OpenMP constructs");
  396. }
  397. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  398. SourceLocation StartLoc,
  399. SourceLocation LParenLoc,
  400. SourceLocation EndLoc) {
  401. llvm_unreachable("HLSL does not support OpenMP constructs");
  402. }
  403. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  404. SourceLocation StartLoc,
  405. SourceLocation LParenLoc,
  406. SourceLocation EndLoc) {
  407. llvm_unreachable("HLSL does not support OpenMP constructs");
  408. }
  409. OMPClause *
  410. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  411. SourceLocation DepLoc, SourceLocation ColonLoc,
  412. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  413. SourceLocation LParenLoc, SourceLocation EndLoc) {
  414. llvm_unreachable("HLSL does not support OpenMP constructs");
  415. }
  416. #else
  417. // HLSL Change Ends
  418. //===----------------------------------------------------------------------===//
  419. // Stack of data-sharing attributes for variables
  420. //===----------------------------------------------------------------------===//
  421. namespace {
  422. /// \brief Default data sharing attributes, which can be applied to directive.
  423. enum DefaultDataSharingAttributes {
  424. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  425. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  426. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
  427. };
  428. template <class T> struct MatchesAny {
  429. explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
  430. bool operator()(T Kind) {
  431. for (auto KindEl : Arr)
  432. if (KindEl == Kind)
  433. return true;
  434. return false;
  435. }
  436. private:
  437. ArrayRef<T> Arr;
  438. };
  439. struct MatchesAlways {
  440. MatchesAlways() {}
  441. template <class T> bool operator()(T) { return true; }
  442. };
  443. typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
  444. typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
  445. /// \brief Stack for tracking declarations used in OpenMP directives and
  446. /// clauses and their data-sharing attributes.
  447. class DSAStackTy {
  448. public:
  449. struct DSAVarData {
  450. OpenMPDirectiveKind DKind;
  451. OpenMPClauseKind CKind;
  452. DeclRefExpr *RefExpr;
  453. SourceLocation ImplicitDSALoc;
  454. DSAVarData()
  455. : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
  456. ImplicitDSALoc() {}
  457. };
  458. private:
  459. struct DSAInfo {
  460. OpenMPClauseKind Attributes;
  461. DeclRefExpr *RefExpr;
  462. };
  463. typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
  464. typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
  465. typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
  466. struct SharingMapTy {
  467. DeclSAMapTy SharingMap;
  468. AlignedMapTy AlignedMap;
  469. LoopControlVariablesSetTy LCVSet;
  470. DefaultDataSharingAttributes DefaultAttr;
  471. SourceLocation DefaultAttrLoc;
  472. OpenMPDirectiveKind Directive;
  473. DeclarationNameInfo DirectiveName;
  474. Scope *CurScope;
  475. SourceLocation ConstructLoc;
  476. bool OrderedRegion;
  477. bool NowaitRegion;
  478. unsigned CollapseNumber;
  479. SourceLocation InnerTeamsRegionLoc;
  480. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  481. Scope *CurScope, SourceLocation Loc)
  482. : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
  483. Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
  484. ConstructLoc(Loc), OrderedRegion(false), NowaitRegion(false),
  485. CollapseNumber(1), InnerTeamsRegionLoc() {}
  486. SharingMapTy()
  487. : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
  488. Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
  489. ConstructLoc(), OrderedRegion(false), NowaitRegion(false),
  490. CollapseNumber(1), InnerTeamsRegionLoc() {}
  491. };
  492. typedef SmallVector<SharingMapTy, 64> StackTy;
  493. /// \brief Stack of used declaration and their data-sharing attributes.
  494. StackTy Stack;
  495. /// \brief true, if check for DSA must be from parent directive, false, if
  496. /// from current directive.
  497. OpenMPClauseKind ClauseKindMode;
  498. Sema &SemaRef;
  499. bool ForceCapturing;
  500. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  501. DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
  502. /// \brief Checks if the variable is a local for OpenMP region.
  503. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  504. public:
  505. explicit DSAStackTy(Sema &S)
  506. : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
  507. ForceCapturing(false) {}
  508. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  509. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  510. bool isForceVarCapturing() const { return ForceCapturing; }
  511. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  512. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  513. Scope *CurScope, SourceLocation Loc) {
  514. Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
  515. Stack.back().DefaultAttrLoc = Loc;
  516. }
  517. void pop() {
  518. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
  519. Stack.pop_back();
  520. }
  521. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  522. /// add it and return NULL; otherwise return previous occurrence's expression
  523. /// for diagnostics.
  524. DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
  525. /// \brief Register specified variable as loop control variable.
  526. void addLoopControlVariable(VarDecl *D);
  527. /// \brief Check if the specified variable is a loop control variable for
  528. /// current region.
  529. bool isLoopControlVariable(VarDecl *D);
  530. /// \brief Adds explicit data sharing attribute to the specified declaration.
  531. void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
  532. /// \brief Returns data sharing attributes from top of the stack for the
  533. /// specified declaration.
  534. DSAVarData getTopDSA(VarDecl *D, bool FromParent);
  535. /// \brief Returns data-sharing attributes for the specified declaration.
  536. DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
  537. /// \brief Checks if the specified variables has data-sharing attributes which
  538. /// match specified \a CPred predicate in any directive which matches \a DPred
  539. /// predicate.
  540. template <class ClausesPredicate, class DirectivesPredicate>
  541. DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
  542. DirectivesPredicate DPred, bool FromParent);
  543. /// \brief Checks if the specified variables has data-sharing attributes which
  544. /// match specified \a CPred predicate in any innermost directive which
  545. /// matches \a DPred predicate.
  546. template <class ClausesPredicate, class DirectivesPredicate>
  547. DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  548. DirectivesPredicate DPred,
  549. bool FromParent);
  550. /// \brief Checks if the specified variables has explicit data-sharing
  551. /// attributes which match specified \a CPred predicate at the specified
  552. /// OpenMP region.
  553. bool hasExplicitDSA(VarDecl *D,
  554. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  555. unsigned Level);
  556. /// \brief Finds a directive which matches specified \a DPred predicate.
  557. template <class NamedDirectivesPredicate>
  558. bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
  559. /// \brief Returns currently analyzed directive.
  560. OpenMPDirectiveKind getCurrentDirective() const {
  561. return Stack.back().Directive;
  562. }
  563. /// \brief Returns parent directive.
  564. OpenMPDirectiveKind getParentDirective() const {
  565. if (Stack.size() > 2)
  566. return Stack[Stack.size() - 2].Directive;
  567. return OMPD_unknown;
  568. }
  569. /// \brief Set default data sharing attribute to none.
  570. void setDefaultDSANone(SourceLocation Loc) {
  571. Stack.back().DefaultAttr = DSA_none;
  572. Stack.back().DefaultAttrLoc = Loc;
  573. }
  574. /// \brief Set default data sharing attribute to shared.
  575. void setDefaultDSAShared(SourceLocation Loc) {
  576. Stack.back().DefaultAttr = DSA_shared;
  577. Stack.back().DefaultAttrLoc = Loc;
  578. }
  579. DefaultDataSharingAttributes getDefaultDSA() const {
  580. return Stack.back().DefaultAttr;
  581. }
  582. SourceLocation getDefaultDSALocation() const {
  583. return Stack.back().DefaultAttrLoc;
  584. }
  585. /// \brief Checks if the specified variable is a threadprivate.
  586. bool isThreadPrivate(VarDecl *D) {
  587. DSAVarData DVar = getTopDSA(D, false);
  588. return isOpenMPThreadPrivate(DVar.CKind);
  589. }
  590. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  591. void setOrderedRegion(bool IsOrdered = true) {
  592. Stack.back().OrderedRegion = IsOrdered;
  593. }
  594. /// \brief Returns true, if parent region is ordered (has associated
  595. /// 'ordered' clause), false - otherwise.
  596. bool isParentOrderedRegion() const {
  597. if (Stack.size() > 2)
  598. return Stack[Stack.size() - 2].OrderedRegion;
  599. return false;
  600. }
  601. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  602. void setNowaitRegion(bool IsNowait = true) {
  603. Stack.back().NowaitRegion = IsNowait;
  604. }
  605. /// \brief Returns true, if parent region is nowait (has associated
  606. /// 'nowait' clause), false - otherwise.
  607. bool isParentNowaitRegion() const {
  608. if (Stack.size() > 2)
  609. return Stack[Stack.size() - 2].NowaitRegion;
  610. return false;
  611. }
  612. /// \brief Set collapse value for the region.
  613. void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
  614. /// \brief Return collapse value for region.
  615. unsigned getCollapseNumber() const {
  616. return Stack.back().CollapseNumber;
  617. }
  618. /// \brief Marks current target region as one with closely nested teams
  619. /// region.
  620. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  621. if (Stack.size() > 2)
  622. Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
  623. }
  624. /// \brief Returns true, if current region has closely nested teams region.
  625. bool hasInnerTeamsRegion() const {
  626. return getInnerTeamsRegionLoc().isValid();
  627. }
  628. /// \brief Returns location of the nested teams region (if any).
  629. SourceLocation getInnerTeamsRegionLoc() const {
  630. if (Stack.size() > 1)
  631. return Stack.back().InnerTeamsRegionLoc;
  632. return SourceLocation();
  633. }
  634. Scope *getCurScope() const { return Stack.back().CurScope; }
  635. Scope *getCurScope() { return Stack.back().CurScope; }
  636. SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
  637. };
  638. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  639. return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
  640. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  641. }
  642. } // namespace
  643. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
  644. VarDecl *D) {
  645. D = D->getCanonicalDecl();
  646. DSAVarData DVar;
  647. if (Iter == std::prev(Stack.rend())) {
  648. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  649. // in a region but not in construct]
  650. // File-scope or namespace-scope variables referenced in called routines
  651. // in the region are shared unless they appear in a threadprivate
  652. // directive.
  653. if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  654. DVar.CKind = OMPC_shared;
  655. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  656. // in a region but not in construct]
  657. // Variables with static storage duration that are declared in called
  658. // routines in the region are shared.
  659. if (D->hasGlobalStorage())
  660. DVar.CKind = OMPC_shared;
  661. return DVar;
  662. }
  663. DVar.DKind = Iter->Directive;
  664. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  665. // in a Construct, C/C++, predetermined, p.1]
  666. // Variables with automatic storage duration that are declared in a scope
  667. // inside the construct are private.
  668. if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
  669. (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
  670. DVar.CKind = OMPC_private;
  671. return DVar;
  672. }
  673. // Explicitly specified attributes and local variables with predetermined
  674. // attributes.
  675. if (Iter->SharingMap.count(D)) {
  676. DVar.RefExpr = Iter->SharingMap[D].RefExpr;
  677. DVar.CKind = Iter->SharingMap[D].Attributes;
  678. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  679. return DVar;
  680. }
  681. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  682. // in a Construct, C/C++, implicitly determined, p.1]
  683. // In a parallel or task construct, the data-sharing attributes of these
  684. // variables are determined by the default clause, if present.
  685. switch (Iter->DefaultAttr) {
  686. case DSA_shared:
  687. DVar.CKind = OMPC_shared;
  688. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  689. return DVar;
  690. case DSA_none:
  691. return DVar;
  692. case DSA_unspecified:
  693. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  694. // in a Construct, implicitly determined, p.2]
  695. // In a parallel construct, if no default clause is present, these
  696. // variables are shared.
  697. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  698. if (isOpenMPParallelDirective(DVar.DKind) ||
  699. isOpenMPTeamsDirective(DVar.DKind)) {
  700. DVar.CKind = OMPC_shared;
  701. return DVar;
  702. }
  703. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  704. // in a Construct, implicitly determined, p.4]
  705. // In a task construct, if no default clause is present, a variable that in
  706. // the enclosing context is determined to be shared by all implicit tasks
  707. // bound to the current team is shared.
  708. if (DVar.DKind == OMPD_task) {
  709. DSAVarData DVarTemp;
  710. for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
  711. I != EE; ++I) {
  712. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  713. // Referenced
  714. // in a Construct, implicitly determined, p.6]
  715. // In a task construct, if no default clause is present, a variable
  716. // whose data-sharing attribute is not determined by the rules above is
  717. // firstprivate.
  718. DVarTemp = getDSA(I, D);
  719. if (DVarTemp.CKind != OMPC_shared) {
  720. DVar.RefExpr = nullptr;
  721. DVar.DKind = OMPD_task;
  722. DVar.CKind = OMPC_firstprivate;
  723. return DVar;
  724. }
  725. if (isParallelOrTaskRegion(I->Directive))
  726. break;
  727. }
  728. DVar.DKind = OMPD_task;
  729. DVar.CKind =
  730. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  731. return DVar;
  732. }
  733. }
  734. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  735. // in a Construct, implicitly determined, p.3]
  736. // For constructs other than task, if no default clause is present, these
  737. // variables inherit their data-sharing attributes from the enclosing
  738. // context.
  739. return getDSA(std::next(Iter), D);
  740. }
  741. DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
  742. assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
  743. D = D->getCanonicalDecl();
  744. auto It = Stack.back().AlignedMap.find(D);
  745. if (It == Stack.back().AlignedMap.end()) {
  746. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  747. Stack.back().AlignedMap[D] = NewDE;
  748. return nullptr;
  749. } else {
  750. assert(It->second && "Unexpected nullptr expr in the aligned map");
  751. return It->second;
  752. }
  753. return nullptr;
  754. }
  755. void DSAStackTy::addLoopControlVariable(VarDecl *D) {
  756. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  757. D = D->getCanonicalDecl();
  758. Stack.back().LCVSet.insert(D);
  759. }
  760. bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
  761. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  762. D = D->getCanonicalDecl();
  763. return Stack.back().LCVSet.count(D) > 0;
  764. }
  765. void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
  766. D = D->getCanonicalDecl();
  767. if (A == OMPC_threadprivate) {
  768. Stack[0].SharingMap[D].Attributes = A;
  769. Stack[0].SharingMap[D].RefExpr = E;
  770. } else {
  771. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  772. Stack.back().SharingMap[D].Attributes = A;
  773. Stack.back().SharingMap[D].RefExpr = E;
  774. }
  775. }
  776. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  777. D = D->getCanonicalDecl();
  778. if (Stack.size() > 2) {
  779. reverse_iterator I = Iter, E = std::prev(Stack.rend());
  780. Scope *TopScope = nullptr;
  781. while (I != E && !isParallelOrTaskRegion(I->Directive)) {
  782. ++I;
  783. }
  784. if (I == E)
  785. return false;
  786. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  787. Scope *CurScope = getCurScope();
  788. while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
  789. CurScope = CurScope->getParent();
  790. }
  791. return CurScope != TopScope;
  792. }
  793. return false;
  794. }
  795. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  796. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  797. StringRef Name) {
  798. DeclContext *DC = SemaRef.CurContext;
  799. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  800. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  801. VarDecl *Decl =
  802. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  803. Decl->setImplicit();
  804. return Decl;
  805. }
  806. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  807. SourceLocation Loc,
  808. bool RefersToCapture = false) {
  809. D->setReferenced();
  810. D->markUsed(S.Context);
  811. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  812. SourceLocation(), D, RefersToCapture, Loc, Ty,
  813. VK_LValue);
  814. }
  815. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
  816. D = D->getCanonicalDecl();
  817. DSAVarData DVar;
  818. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  819. // in a Construct, C/C++, predetermined, p.1]
  820. // Variables appearing in threadprivate directives are threadprivate.
  821. if ((D->getTLSKind() != VarDecl::TLS_None &&
  822. !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
  823. SemaRef.getLangOpts().OpenMPUseTLS &&
  824. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  825. (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
  826. !D->isLocalVarDecl())) {
  827. addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
  828. D->getLocation()),
  829. OMPC_threadprivate);
  830. }
  831. if (Stack[0].SharingMap.count(D)) {
  832. DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
  833. DVar.CKind = OMPC_threadprivate;
  834. return DVar;
  835. }
  836. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  837. // in a Construct, C/C++, predetermined, p.1]
  838. // Variables with automatic storage duration that are declared in a scope
  839. // inside the construct are private.
  840. OpenMPDirectiveKind Kind =
  841. FromParent ? getParentDirective() : getCurrentDirective();
  842. auto StartI = std::next(Stack.rbegin());
  843. auto EndI = std::prev(Stack.rend());
  844. if (FromParent && StartI != EndI) {
  845. StartI = std::next(StartI);
  846. }
  847. if (!isParallelOrTaskRegion(Kind)) {
  848. if (isOpenMPLocal(D, StartI) &&
  849. ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
  850. D->getStorageClass() == SC_None)) ||
  851. isa<ParmVarDecl>(D))) {
  852. DVar.CKind = OMPC_private;
  853. return DVar;
  854. }
  855. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  856. // in a Construct, C/C++, predetermined, p.4]
  857. // Static data members are shared.
  858. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  859. // in a Construct, C/C++, predetermined, p.7]
  860. // Variables with static storage duration that are declared in a scope
  861. // inside the construct are shared.
  862. if (D->isStaticDataMember() || D->isStaticLocal()) {
  863. DSAVarData DVarTemp =
  864. hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
  865. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  866. return DVar;
  867. DVar.CKind = OMPC_shared;
  868. return DVar;
  869. }
  870. }
  871. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  872. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  873. Type = SemaRef.getASTContext().getBaseElementType(Type);
  874. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  875. // in a Construct, C/C++, predetermined, p.6]
  876. // Variables with const qualified type having no mutable member are
  877. // shared.
  878. CXXRecordDecl *RD =
  879. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  880. if (IsConstant &&
  881. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
  882. // Variables with const-qualified type having no mutable member may be
  883. // listed in a firstprivate clause, even if they are static data members.
  884. DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
  885. MatchesAlways(), FromParent);
  886. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  887. return DVar;
  888. DVar.CKind = OMPC_shared;
  889. return DVar;
  890. }
  891. // Explicitly specified attributes and local variables with predetermined
  892. // attributes.
  893. auto I = std::prev(StartI);
  894. if (I->SharingMap.count(D)) {
  895. DVar.RefExpr = I->SharingMap[D].RefExpr;
  896. DVar.CKind = I->SharingMap[D].Attributes;
  897. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  898. }
  899. return DVar;
  900. }
  901. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
  902. D = D->getCanonicalDecl();
  903. auto StartI = Stack.rbegin();
  904. auto EndI = std::prev(Stack.rend());
  905. if (FromParent && StartI != EndI) {
  906. StartI = std::next(StartI);
  907. }
  908. return getDSA(StartI, D);
  909. }
  910. template <class ClausesPredicate, class DirectivesPredicate>
  911. DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
  912. DirectivesPredicate DPred,
  913. bool FromParent) {
  914. D = D->getCanonicalDecl();
  915. auto StartI = std::next(Stack.rbegin());
  916. auto EndI = std::prev(Stack.rend());
  917. if (FromParent && StartI != EndI) {
  918. StartI = std::next(StartI);
  919. }
  920. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  921. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  922. continue;
  923. DSAVarData DVar = getDSA(I, D);
  924. if (CPred(DVar.CKind))
  925. return DVar;
  926. }
  927. return DSAVarData();
  928. }
  929. template <class ClausesPredicate, class DirectivesPredicate>
  930. DSAStackTy::DSAVarData
  931. DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  932. DirectivesPredicate DPred, bool FromParent) {
  933. D = D->getCanonicalDecl();
  934. auto StartI = std::next(Stack.rbegin());
  935. auto EndI = std::prev(Stack.rend());
  936. if (FromParent && StartI != EndI) {
  937. StartI = std::next(StartI);
  938. }
  939. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  940. if (!DPred(I->Directive))
  941. break;
  942. DSAVarData DVar = getDSA(I, D);
  943. if (CPred(DVar.CKind))
  944. return DVar;
  945. return DSAVarData();
  946. }
  947. return DSAVarData();
  948. }
  949. bool DSAStackTy::hasExplicitDSA(
  950. VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  951. unsigned Level) {
  952. if (CPred(ClauseKindMode))
  953. return true;
  954. if (isClauseParsingMode())
  955. ++Level;
  956. D = D->getCanonicalDecl();
  957. auto StartI = Stack.rbegin();
  958. auto EndI = std::prev(Stack.rend());
  959. if (std::distance(StartI, EndI) <= (int)Level)
  960. return false;
  961. std::advance(StartI, Level);
  962. return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
  963. CPred(StartI->SharingMap[D].Attributes);
  964. }
  965. template <class NamedDirectivesPredicate>
  966. bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
  967. auto StartI = std::next(Stack.rbegin());
  968. auto EndI = std::prev(Stack.rend());
  969. if (FromParent && StartI != EndI) {
  970. StartI = std::next(StartI);
  971. }
  972. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  973. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  974. return true;
  975. }
  976. return false;
  977. }
  978. void Sema::InitDataSharingAttributesStack() {
  979. VarDataSharingAttributesStack = new DSAStackTy(*this);
  980. }
  981. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  982. bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
  983. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  984. VD = VD->getCanonicalDecl();
  985. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  986. (!DSAStack->isClauseParsingMode() ||
  987. DSAStack->getParentDirective() != OMPD_unknown)) {
  988. if (DSAStack->isLoopControlVariable(VD) ||
  989. (VD->hasLocalStorage() &&
  990. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  991. DSAStack->isForceVarCapturing())
  992. return true;
  993. auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
  994. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  995. return true;
  996. DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
  997. DSAStack->isClauseParsingMode());
  998. return DVarPrivate.CKind != OMPC_unknown;
  999. }
  1000. return false;
  1001. }
  1002. bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
  1003. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1004. return DSAStack->hasExplicitDSA(
  1005. VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
  1006. }
  1007. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1008. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1009. const DeclarationNameInfo &DirName,
  1010. Scope *CurScope, SourceLocation Loc) {
  1011. DSAStack->push(DKind, DirName, CurScope, Loc);
  1012. PushExpressionEvaluationContext(PotentiallyEvaluated);
  1013. }
  1014. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1015. DSAStack->setClauseParsingMode(K);
  1016. }
  1017. void Sema::EndOpenMPClause() {
  1018. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1019. }
  1020. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1021. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1022. // A variable of class type (or array thereof) that appears in a lastprivate
  1023. // clause requires an accessible, unambiguous default constructor for the
  1024. // class type, unless the list item is also specified in a firstprivate
  1025. // clause.
  1026. if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1027. for (auto *C : D->clauses()) {
  1028. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1029. SmallVector<Expr *, 8> PrivateCopies;
  1030. for (auto *DE : Clause->varlists()) {
  1031. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1032. PrivateCopies.push_back(nullptr);
  1033. continue;
  1034. }
  1035. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
  1036. QualType Type = VD->getType();
  1037. auto DVar = DSAStack->getTopDSA(VD, false);
  1038. if (DVar.CKind == OMPC_lastprivate) {
  1039. // Generate helper private variable and initialize it with the
  1040. // default value. The address of the original variable is replaced
  1041. // by the address of the new private variable in CodeGen. This new
  1042. // variable is not added to IdResolver, so the code in the OpenMP
  1043. // region uses original variable for proper diagnostics.
  1044. auto *VDPrivate =
  1045. buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1046. VD->getName());
  1047. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  1048. if (VDPrivate->isInvalidDecl())
  1049. continue;
  1050. PrivateCopies.push_back(buildDeclRefExpr(
  1051. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1052. } else {
  1053. // The variable is also a firstprivate, so initialization sequence
  1054. // for private copy is generated already.
  1055. PrivateCopies.push_back(nullptr);
  1056. }
  1057. }
  1058. // Set initializers to private copies if no errors were found.
  1059. if (PrivateCopies.size() == Clause->varlist_size()) {
  1060. Clause->setPrivateCopies(PrivateCopies);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. DSAStack->pop();
  1066. DiscardCleanupsInEvaluationContext();
  1067. PopExpressionEvaluationContext();
  1068. }
  1069. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1070. Expr *NumIterations, Sema &SemaRef,
  1071. Scope *S);
  1072. namespace {
  1073. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1074. private:
  1075. Sema &SemaRef;
  1076. public:
  1077. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1078. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1079. NamedDecl *ND = Candidate.getCorrectionDecl();
  1080. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1081. return VD->hasGlobalStorage() &&
  1082. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1083. SemaRef.getCurScope());
  1084. }
  1085. return false;
  1086. }
  1087. };
  1088. } // namespace
  1089. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1090. CXXScopeSpec &ScopeSpec,
  1091. const DeclarationNameInfo &Id) {
  1092. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1093. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1094. if (Lookup.isAmbiguous())
  1095. return ExprError();
  1096. VarDecl *VD;
  1097. if (!Lookup.isSingleResult()) {
  1098. if (TypoCorrection Corrected = CorrectTypo(
  1099. Id, LookupOrdinaryName, CurScope, nullptr,
  1100. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1101. diagnoseTypo(Corrected,
  1102. PDiag(Lookup.empty()
  1103. ? diag::err_undeclared_var_use_suggest
  1104. : diag::err_omp_expected_var_arg_suggest)
  1105. << Id.getName());
  1106. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1107. } else {
  1108. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1109. : diag::err_omp_expected_var_arg)
  1110. << Id.getName();
  1111. return ExprError();
  1112. }
  1113. } else {
  1114. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1115. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1116. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1117. return ExprError();
  1118. }
  1119. }
  1120. Lookup.suppressDiagnostics();
  1121. // OpenMP [2.9.2, Syntax, C/C++]
  1122. // Variables must be file-scope, namespace-scope, or static block-scope.
  1123. if (!VD->hasGlobalStorage()) {
  1124. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1125. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1126. bool IsDecl =
  1127. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1128. Diag(VD->getLocation(),
  1129. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1130. << VD;
  1131. return ExprError();
  1132. }
  1133. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1134. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1135. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1136. // A threadprivate directive for file-scope variables must appear outside
  1137. // any definition or declaration.
  1138. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1139. !getCurLexicalContext()->isTranslationUnit()) {
  1140. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1141. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1142. bool IsDecl =
  1143. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1144. Diag(VD->getLocation(),
  1145. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1146. << VD;
  1147. return ExprError();
  1148. }
  1149. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1150. // A threadprivate directive for static class member variables must appear
  1151. // in the class definition, in the same scope in which the member
  1152. // variables are declared.
  1153. if (CanonicalVD->isStaticDataMember() &&
  1154. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1155. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1156. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1157. bool IsDecl =
  1158. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1159. Diag(VD->getLocation(),
  1160. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1161. << VD;
  1162. return ExprError();
  1163. }
  1164. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1165. // A threadprivate directive for namespace-scope variables must appear
  1166. // outside any definition or declaration other than the namespace
  1167. // definition itself.
  1168. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1169. (!getCurLexicalContext()->isFileContext() ||
  1170. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1171. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1172. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1173. bool IsDecl =
  1174. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1175. Diag(VD->getLocation(),
  1176. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1177. << VD;
  1178. return ExprError();
  1179. }
  1180. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1181. // A threadprivate directive for static block-scope variables must appear
  1182. // in the scope of the variable and not in a nested scope.
  1183. if (CanonicalVD->isStaticLocal() && CurScope &&
  1184. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1185. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1186. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1187. bool IsDecl =
  1188. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1189. Diag(VD->getLocation(),
  1190. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1191. << VD;
  1192. return ExprError();
  1193. }
  1194. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1195. // A threadprivate directive must lexically precede all references to any
  1196. // of the variables in its list.
  1197. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1198. Diag(Id.getLoc(), diag::err_omp_var_used)
  1199. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1200. return ExprError();
  1201. }
  1202. QualType ExprType = VD->getType().getNonReferenceType();
  1203. ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
  1204. return DE;
  1205. }
  1206. Sema::DeclGroupPtrTy
  1207. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1208. ArrayRef<Expr *> VarList) {
  1209. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1210. CurContext->addDecl(D);
  1211. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1212. }
  1213. return DeclGroupPtrTy();
  1214. }
  1215. namespace {
  1216. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1217. Sema &SemaRef;
  1218. public:
  1219. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1220. if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
  1221. if (VD->hasLocalStorage()) {
  1222. SemaRef.Diag(E->getLocStart(),
  1223. diag::err_omp_local_var_in_threadprivate_init)
  1224. << E->getSourceRange();
  1225. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1226. << VD << VD->getSourceRange();
  1227. return true;
  1228. }
  1229. }
  1230. return false;
  1231. }
  1232. bool VisitStmt(const Stmt *S) {
  1233. for (auto Child : S->children()) {
  1234. if (Child && Visit(Child))
  1235. return true;
  1236. }
  1237. return false;
  1238. }
  1239. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1240. };
  1241. } // namespace
  1242. OMPThreadPrivateDecl *
  1243. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1244. SmallVector<Expr *, 8> Vars;
  1245. for (auto &RefExpr : VarList) {
  1246. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1247. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1248. SourceLocation ILoc = DE->getExprLoc();
  1249. QualType QType = VD->getType();
  1250. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1251. // It will be analyzed later.
  1252. Vars.push_back(DE);
  1253. continue;
  1254. }
  1255. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1256. // A threadprivate variable must not have an incomplete type.
  1257. if (RequireCompleteType(ILoc, VD->getType(),
  1258. diag::err_omp_threadprivate_incomplete_type)) {
  1259. continue;
  1260. }
  1261. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1262. // A threadprivate variable must not have a reference type.
  1263. if (VD->getType()->isReferenceType()) {
  1264. Diag(ILoc, diag::err_omp_ref_type_arg)
  1265. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1266. bool IsDecl =
  1267. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1268. Diag(VD->getLocation(),
  1269. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1270. << VD;
  1271. continue;
  1272. }
  1273. // Check if this is a TLS variable. If TLS is not being supported, produce
  1274. // the corresponding diagnostic.
  1275. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1276. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1277. getLangOpts().OpenMPUseTLS &&
  1278. getASTContext().getTargetInfo().isTLSSupported())) ||
  1279. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1280. !VD->isLocalVarDecl())) {
  1281. Diag(ILoc, diag::err_omp_var_thread_local)
  1282. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1283. bool IsDecl =
  1284. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1285. Diag(VD->getLocation(),
  1286. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1287. << VD;
  1288. continue;
  1289. }
  1290. // Check if initial value of threadprivate variable reference variable with
  1291. // local storage (it is not supported by runtime).
  1292. if (auto Init = VD->getAnyInitializer()) {
  1293. LocalVarRefChecker Checker(*this);
  1294. if (Checker.Visit(Init))
  1295. continue;
  1296. }
  1297. Vars.push_back(RefExpr);
  1298. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1299. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1300. Context, SourceRange(Loc, Loc)));
  1301. if (auto *ML = Context.getASTMutationListener())
  1302. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1303. }
  1304. OMPThreadPrivateDecl *D = nullptr;
  1305. if (!Vars.empty()) {
  1306. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1307. Vars);
  1308. D->setAccess(AS_public);
  1309. }
  1310. return D;
  1311. }
  1312. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1313. const VarDecl *VD, DSAStackTy::DSAVarData DVar,
  1314. bool IsLoopIterVar = false) {
  1315. if (DVar.RefExpr) {
  1316. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1317. << getOpenMPClauseName(DVar.CKind);
  1318. return;
  1319. }
  1320. enum {
  1321. PDSA_StaticMemberShared,
  1322. PDSA_StaticLocalVarShared,
  1323. PDSA_LoopIterVarPrivate,
  1324. PDSA_LoopIterVarLinear,
  1325. PDSA_LoopIterVarLastprivate,
  1326. PDSA_ConstVarShared,
  1327. PDSA_GlobalVarShared,
  1328. PDSA_TaskVarFirstprivate,
  1329. PDSA_LocalVarPrivate,
  1330. PDSA_Implicit
  1331. } Reason = PDSA_Implicit;
  1332. bool ReportHint = false;
  1333. auto ReportLoc = VD->getLocation();
  1334. if (IsLoopIterVar) {
  1335. if (DVar.CKind == OMPC_private)
  1336. Reason = PDSA_LoopIterVarPrivate;
  1337. else if (DVar.CKind == OMPC_lastprivate)
  1338. Reason = PDSA_LoopIterVarLastprivate;
  1339. else
  1340. Reason = PDSA_LoopIterVarLinear;
  1341. } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
  1342. Reason = PDSA_TaskVarFirstprivate;
  1343. ReportLoc = DVar.ImplicitDSALoc;
  1344. } else if (VD->isStaticLocal())
  1345. Reason = PDSA_StaticLocalVarShared;
  1346. else if (VD->isStaticDataMember())
  1347. Reason = PDSA_StaticMemberShared;
  1348. else if (VD->isFileVarDecl())
  1349. Reason = PDSA_GlobalVarShared;
  1350. else if (VD->getType().isConstant(SemaRef.getASTContext()))
  1351. Reason = PDSA_ConstVarShared;
  1352. else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1353. ReportHint = true;
  1354. Reason = PDSA_LocalVarPrivate;
  1355. }
  1356. if (Reason != PDSA_Implicit) {
  1357. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1358. << Reason << ReportHint
  1359. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1360. } else if (DVar.ImplicitDSALoc.isValid()) {
  1361. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1362. << getOpenMPClauseName(DVar.CKind);
  1363. }
  1364. }
  1365. namespace {
  1366. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1367. DSAStackTy *Stack;
  1368. Sema &SemaRef;
  1369. bool ErrorFound;
  1370. CapturedStmt *CS;
  1371. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1372. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  1373. public:
  1374. void VisitDeclRefExpr(DeclRefExpr *E) {
  1375. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1376. // Skip internally declared variables.
  1377. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
  1378. return;
  1379. auto DVar = Stack->getTopDSA(VD, false);
  1380. // Check if the variable has explicit DSA set and stop analysis if it so.
  1381. if (DVar.RefExpr) return;
  1382. auto ELoc = E->getExprLoc();
  1383. auto DKind = Stack->getCurrentDirective();
  1384. // The default(none) clause requires that each variable that is referenced
  1385. // in the construct, and does not have a predetermined data-sharing
  1386. // attribute, must have its data-sharing attribute explicitly determined
  1387. // by being listed in a data-sharing attribute clause.
  1388. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1389. isParallelOrTaskRegion(DKind) &&
  1390. VarsWithInheritedDSA.count(VD) == 0) {
  1391. VarsWithInheritedDSA[VD] = E;
  1392. return;
  1393. }
  1394. // OpenMP [2.9.3.6, Restrictions, p.2]
  1395. // A list item that appears in a reduction clause of the innermost
  1396. // enclosing worksharing or parallel construct may not be accessed in an
  1397. // explicit task.
  1398. DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  1399. [](OpenMPDirectiveKind K) -> bool {
  1400. return isOpenMPParallelDirective(K) ||
  1401. isOpenMPWorksharingDirective(K) ||
  1402. isOpenMPTeamsDirective(K);
  1403. },
  1404. false);
  1405. if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
  1406. ErrorFound = true;
  1407. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1408. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1409. return;
  1410. }
  1411. // Define implicit data-sharing attributes for task.
  1412. DVar = Stack->getImplicitDSA(VD, false);
  1413. if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
  1414. ImplicitFirstprivate.push_back(E);
  1415. }
  1416. }
  1417. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1418. for (auto *C : S->clauses()) {
  1419. // Skip analysis of arguments of implicitly defined firstprivate clause
  1420. // for task directives.
  1421. if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
  1422. for (auto *CC : C->children()) {
  1423. if (CC)
  1424. Visit(CC);
  1425. }
  1426. }
  1427. }
  1428. void VisitStmt(Stmt *S) {
  1429. for (auto *C : S->children()) {
  1430. if (C && !isa<OMPExecutableDirective>(C))
  1431. Visit(C);
  1432. }
  1433. }
  1434. bool isErrorFound() { return ErrorFound; }
  1435. ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
  1436. llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
  1437. return VarsWithInheritedDSA;
  1438. }
  1439. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1440. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1441. };
  1442. } // namespace
  1443. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1444. switch (DKind) {
  1445. case OMPD_parallel: {
  1446. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1447. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1448. Sema::CapturedParamNameType Params[] = {
  1449. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1450. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1451. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1452. };
  1453. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1454. Params);
  1455. break;
  1456. }
  1457. case OMPD_simd: {
  1458. Sema::CapturedParamNameType Params[] = {
  1459. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1460. };
  1461. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1462. Params);
  1463. break;
  1464. }
  1465. case OMPD_for: {
  1466. Sema::CapturedParamNameType Params[] = {
  1467. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1468. };
  1469. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1470. Params);
  1471. break;
  1472. }
  1473. case OMPD_for_simd: {
  1474. Sema::CapturedParamNameType Params[] = {
  1475. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1476. };
  1477. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1478. Params);
  1479. break;
  1480. }
  1481. case OMPD_sections: {
  1482. Sema::CapturedParamNameType Params[] = {
  1483. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1484. };
  1485. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1486. Params);
  1487. break;
  1488. }
  1489. case OMPD_section: {
  1490. Sema::CapturedParamNameType Params[] = {
  1491. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1492. };
  1493. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1494. Params);
  1495. break;
  1496. }
  1497. case OMPD_single: {
  1498. Sema::CapturedParamNameType Params[] = {
  1499. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1500. };
  1501. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1502. Params);
  1503. break;
  1504. }
  1505. case OMPD_master: {
  1506. Sema::CapturedParamNameType Params[] = {
  1507. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1508. };
  1509. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1510. Params);
  1511. break;
  1512. }
  1513. case OMPD_critical: {
  1514. Sema::CapturedParamNameType Params[] = {
  1515. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1516. };
  1517. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1518. Params);
  1519. break;
  1520. }
  1521. case OMPD_parallel_for: {
  1522. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1523. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1524. Sema::CapturedParamNameType Params[] = {
  1525. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1526. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1527. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1528. };
  1529. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1530. Params);
  1531. break;
  1532. }
  1533. case OMPD_parallel_for_simd: {
  1534. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1535. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1536. Sema::CapturedParamNameType Params[] = {
  1537. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1538. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1539. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1540. };
  1541. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1542. Params);
  1543. break;
  1544. }
  1545. case OMPD_parallel_sections: {
  1546. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1547. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1548. Sema::CapturedParamNameType Params[] = {
  1549. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1550. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1551. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1552. };
  1553. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1554. Params);
  1555. break;
  1556. }
  1557. case OMPD_task: {
  1558. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1559. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1560. FunctionProtoType::ExtProtoInfo EPI;
  1561. EPI.Variadic = true;
  1562. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1563. Sema::CapturedParamNameType Params[] = {
  1564. std::make_pair(".global_tid.", KmpInt32Ty),
  1565. std::make_pair(".part_id.", KmpInt32Ty),
  1566. std::make_pair(".privates.",
  1567. Context.VoidPtrTy.withConst().withRestrict()),
  1568. std::make_pair(
  1569. ".copy_fn.",
  1570. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  1571. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1572. };
  1573. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1574. Params);
  1575. // Mark this captured region as inlined, because we don't use outlined
  1576. // function directly.
  1577. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1578. AlwaysInlineAttr::CreateImplicit(
  1579. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1580. break;
  1581. }
  1582. case OMPD_ordered: {
  1583. Sema::CapturedParamNameType Params[] = {
  1584. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1585. };
  1586. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1587. Params);
  1588. break;
  1589. }
  1590. case OMPD_atomic: {
  1591. Sema::CapturedParamNameType Params[] = {
  1592. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1593. };
  1594. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1595. Params);
  1596. break;
  1597. }
  1598. case OMPD_target: {
  1599. Sema::CapturedParamNameType Params[] = {
  1600. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1601. };
  1602. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1603. Params);
  1604. break;
  1605. }
  1606. case OMPD_teams: {
  1607. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1608. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1609. Sema::CapturedParamNameType Params[] = {
  1610. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1611. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1612. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1613. };
  1614. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1615. Params);
  1616. break;
  1617. }
  1618. case OMPD_taskgroup: {
  1619. Sema::CapturedParamNameType Params[] = {
  1620. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1621. };
  1622. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1623. Params);
  1624. break;
  1625. }
  1626. case OMPD_threadprivate:
  1627. case OMPD_taskyield:
  1628. case OMPD_barrier:
  1629. case OMPD_taskwait:
  1630. case OMPD_cancellation_point:
  1631. case OMPD_cancel:
  1632. case OMPD_flush:
  1633. llvm_unreachable("OpenMP Directive is not allowed");
  1634. case OMPD_unknown:
  1635. llvm_unreachable("Unknown OpenMP directive");
  1636. }
  1637. }
  1638. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  1639. ArrayRef<OMPClause *> Clauses) {
  1640. if (!S.isUsable()) {
  1641. ActOnCapturedRegionError();
  1642. return StmtError();
  1643. }
  1644. // This is required for proper codegen.
  1645. for (auto *Clause : Clauses) {
  1646. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  1647. Clause->getClauseKind() == OMPC_copyprivate ||
  1648. (getLangOpts().OpenMPUseTLS &&
  1649. getASTContext().getTargetInfo().isTLSSupported() &&
  1650. Clause->getClauseKind() == OMPC_copyin)) {
  1651. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  1652. // Mark all variables in private list clauses as used in inner region.
  1653. for (auto *VarRef : Clause->children()) {
  1654. if (auto *E = cast_or_null<Expr>(VarRef)) {
  1655. MarkDeclarationsReferencedInExpr(E);
  1656. }
  1657. }
  1658. DSAStack->setForceVarCapturing(/*V=*/false);
  1659. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  1660. Clause->getClauseKind() == OMPC_schedule) {
  1661. // Mark all variables in private list clauses as used in inner region.
  1662. // Required for proper codegen of combined directives.
  1663. // TODO: add processing for other clauses.
  1664. if (auto *E = cast_or_null<Expr>(
  1665. cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
  1666. MarkDeclarationsReferencedInExpr(E);
  1667. }
  1668. }
  1669. }
  1670. return ActOnCapturedRegionEnd(S.get());
  1671. }
  1672. static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  1673. OpenMPDirectiveKind CurrentRegion,
  1674. const DeclarationNameInfo &CurrentName,
  1675. OpenMPDirectiveKind CancelRegion,
  1676. SourceLocation StartLoc) {
  1677. // Allowed nesting of constructs
  1678. // +------------------+-----------------+------------------------------------+
  1679. // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
  1680. // +------------------+-----------------+------------------------------------+
  1681. // | parallel | parallel | * |
  1682. // | parallel | for | * |
  1683. // | parallel | for simd | * |
  1684. // | parallel | master | * |
  1685. // | parallel | critical | * |
  1686. // | parallel | simd | * |
  1687. // | parallel | sections | * |
  1688. // | parallel | section | + |
  1689. // | parallel | single | * |
  1690. // | parallel | parallel for | * |
  1691. // | parallel |parallel for simd| * |
  1692. // | parallel |parallel sections| * |
  1693. // | parallel | task | * |
  1694. // | parallel | taskyield | * |
  1695. // | parallel | barrier | * |
  1696. // | parallel | taskwait | * |
  1697. // | parallel | taskgroup | * |
  1698. // | parallel | flush | * |
  1699. // | parallel | ordered | + |
  1700. // | parallel | atomic | * |
  1701. // | parallel | target | * |
  1702. // | parallel | teams | + |
  1703. // | parallel | cancellation | |
  1704. // | | point | ! |
  1705. // | parallel | cancel | ! |
  1706. // +------------------+-----------------+------------------------------------+
  1707. // | for | parallel | * |
  1708. // | for | for | + |
  1709. // | for | for simd | + |
  1710. // | for | master | + |
  1711. // | for | critical | * |
  1712. // | for | simd | * |
  1713. // | for | sections | + |
  1714. // | for | section | + |
  1715. // | for | single | + |
  1716. // | for | parallel for | * |
  1717. // | for |parallel for simd| * |
  1718. // | for |parallel sections| * |
  1719. // | for | task | * |
  1720. // | for | taskyield | * |
  1721. // | for | barrier | + |
  1722. // | for | taskwait | * |
  1723. // | for | taskgroup | * |
  1724. // | for | flush | * |
  1725. // | for | ordered | * (if construct is ordered) |
  1726. // | for | atomic | * |
  1727. // | for | target | * |
  1728. // | for | teams | + |
  1729. // | for | cancellation | |
  1730. // | | point | ! |
  1731. // | for | cancel | ! |
  1732. // +------------------+-----------------+------------------------------------+
  1733. // | master | parallel | * |
  1734. // | master | for | + |
  1735. // | master | for simd | + |
  1736. // | master | master | * |
  1737. // | master | critical | * |
  1738. // | master | simd | * |
  1739. // | master | sections | + |
  1740. // | master | section | + |
  1741. // | master | single | + |
  1742. // | master | parallel for | * |
  1743. // | master |parallel for simd| * |
  1744. // | master |parallel sections| * |
  1745. // | master | task | * |
  1746. // | master | taskyield | * |
  1747. // | master | barrier | + |
  1748. // | master | taskwait | * |
  1749. // | master | taskgroup | * |
  1750. // | master | flush | * |
  1751. // | master | ordered | + |
  1752. // | master | atomic | * |
  1753. // | master | target | * |
  1754. // | master | teams | + |
  1755. // | master | cancellation | |
  1756. // | | point | |
  1757. // | master | cancel | |
  1758. // +------------------+-----------------+------------------------------------+
  1759. // | critical | parallel | * |
  1760. // | critical | for | + |
  1761. // | critical | for simd | + |
  1762. // | critical | master | * |
  1763. // | critical | critical | * (should have different names) |
  1764. // | critical | simd | * |
  1765. // | critical | sections | + |
  1766. // | critical | section | + |
  1767. // | critical | single | + |
  1768. // | critical | parallel for | * |
  1769. // | critical |parallel for simd| * |
  1770. // | critical |parallel sections| * |
  1771. // | critical | task | * |
  1772. // | critical | taskyield | * |
  1773. // | critical | barrier | + |
  1774. // | critical | taskwait | * |
  1775. // | critical | taskgroup | * |
  1776. // | critical | ordered | + |
  1777. // | critical | atomic | * |
  1778. // | critical | target | * |
  1779. // | critical | teams | + |
  1780. // | critical | cancellation | |
  1781. // | | point | |
  1782. // | critical | cancel | |
  1783. // +------------------+-----------------+------------------------------------+
  1784. // | simd | parallel | |
  1785. // | simd | for | |
  1786. // | simd | for simd | |
  1787. // | simd | master | |
  1788. // | simd | critical | |
  1789. // | simd | simd | |
  1790. // | simd | sections | |
  1791. // | simd | section | |
  1792. // | simd | single | |
  1793. // | simd | parallel for | |
  1794. // | simd |parallel for simd| |
  1795. // | simd |parallel sections| |
  1796. // | simd | task | |
  1797. // | simd | taskyield | |
  1798. // | simd | barrier | |
  1799. // | simd | taskwait | |
  1800. // | simd | taskgroup | |
  1801. // | simd | flush | |
  1802. // | simd | ordered | |
  1803. // | simd | atomic | |
  1804. // | simd | target | |
  1805. // | simd | teams | |
  1806. // | simd | cancellation | |
  1807. // | | point | |
  1808. // | simd | cancel | |
  1809. // +------------------+-----------------+------------------------------------+
  1810. // | for simd | parallel | |
  1811. // | for simd | for | |
  1812. // | for simd | for simd | |
  1813. // | for simd | master | |
  1814. // | for simd | critical | |
  1815. // | for simd | simd | |
  1816. // | for simd | sections | |
  1817. // | for simd | section | |
  1818. // | for simd | single | |
  1819. // | for simd | parallel for | |
  1820. // | for simd |parallel for simd| |
  1821. // | for simd |parallel sections| |
  1822. // | for simd | task | |
  1823. // | for simd | taskyield | |
  1824. // | for simd | barrier | |
  1825. // | for simd | taskwait | |
  1826. // | for simd | taskgroup | |
  1827. // | for simd | flush | |
  1828. // | for simd | ordered | |
  1829. // | for simd | atomic | |
  1830. // | for simd | target | |
  1831. // | for simd | teams | |
  1832. // | for simd | cancellation | |
  1833. // | | point | |
  1834. // | for simd | cancel | |
  1835. // +------------------+-----------------+------------------------------------+
  1836. // | parallel for simd| parallel | |
  1837. // | parallel for simd| for | |
  1838. // | parallel for simd| for simd | |
  1839. // | parallel for simd| master | |
  1840. // | parallel for simd| critical | |
  1841. // | parallel for simd| simd | |
  1842. // | parallel for simd| sections | |
  1843. // | parallel for simd| section | |
  1844. // | parallel for simd| single | |
  1845. // | parallel for simd| parallel for | |
  1846. // | parallel for simd|parallel for simd| |
  1847. // | parallel for simd|parallel sections| |
  1848. // | parallel for simd| task | |
  1849. // | parallel for simd| taskyield | |
  1850. // | parallel for simd| barrier | |
  1851. // | parallel for simd| taskwait | |
  1852. // | parallel for simd| taskgroup | |
  1853. // | parallel for simd| flush | |
  1854. // | parallel for simd| ordered | |
  1855. // | parallel for simd| atomic | |
  1856. // | parallel for simd| target | |
  1857. // | parallel for simd| teams | |
  1858. // | parallel for simd| cancellation | |
  1859. // | | point | |
  1860. // | parallel for simd| cancel | |
  1861. // +------------------+-----------------+------------------------------------+
  1862. // | sections | parallel | * |
  1863. // | sections | for | + |
  1864. // | sections | for simd | + |
  1865. // | sections | master | + |
  1866. // | sections | critical | * |
  1867. // | sections | simd | * |
  1868. // | sections | sections | + |
  1869. // | sections | section | * |
  1870. // | sections | single | + |
  1871. // | sections | parallel for | * |
  1872. // | sections |parallel for simd| * |
  1873. // | sections |parallel sections| * |
  1874. // | sections | task | * |
  1875. // | sections | taskyield | * |
  1876. // | sections | barrier | + |
  1877. // | sections | taskwait | * |
  1878. // | sections | taskgroup | * |
  1879. // | sections | flush | * |
  1880. // | sections | ordered | + |
  1881. // | sections | atomic | * |
  1882. // | sections | target | * |
  1883. // | sections | teams | + |
  1884. // | sections | cancellation | |
  1885. // | | point | ! |
  1886. // | sections | cancel | ! |
  1887. // +------------------+-----------------+------------------------------------+
  1888. // | section | parallel | * |
  1889. // | section | for | + |
  1890. // | section | for simd | + |
  1891. // | section | master | + |
  1892. // | section | critical | * |
  1893. // | section | simd | * |
  1894. // | section | sections | + |
  1895. // | section | section | + |
  1896. // | section | single | + |
  1897. // | section | parallel for | * |
  1898. // | section |parallel for simd| * |
  1899. // | section |parallel sections| * |
  1900. // | section | task | * |
  1901. // | section | taskyield | * |
  1902. // | section | barrier | + |
  1903. // | section | taskwait | * |
  1904. // | section | taskgroup | * |
  1905. // | section | flush | * |
  1906. // | section | ordered | + |
  1907. // | section | atomic | * |
  1908. // | section | target | * |
  1909. // | section | teams | + |
  1910. // | section | cancellation | |
  1911. // | | point | ! |
  1912. // | section | cancel | ! |
  1913. // +------------------+-----------------+------------------------------------+
  1914. // | single | parallel | * |
  1915. // | single | for | + |
  1916. // | single | for simd | + |
  1917. // | single | master | + |
  1918. // | single | critical | * |
  1919. // | single | simd | * |
  1920. // | single | sections | + |
  1921. // | single | section | + |
  1922. // | single | single | + |
  1923. // | single | parallel for | * |
  1924. // | single |parallel for simd| * |
  1925. // | single |parallel sections| * |
  1926. // | single | task | * |
  1927. // | single | taskyield | * |
  1928. // | single | barrier | + |
  1929. // | single | taskwait | * |
  1930. // | single | taskgroup | * |
  1931. // | single | flush | * |
  1932. // | single | ordered | + |
  1933. // | single | atomic | * |
  1934. // | single | target | * |
  1935. // | single | teams | + |
  1936. // | single | cancellation | |
  1937. // | | point | |
  1938. // | single | cancel | |
  1939. // +------------------+-----------------+------------------------------------+
  1940. // | parallel for | parallel | * |
  1941. // | parallel for | for | + |
  1942. // | parallel for | for simd | + |
  1943. // | parallel for | master | + |
  1944. // | parallel for | critical | * |
  1945. // | parallel for | simd | * |
  1946. // | parallel for | sections | + |
  1947. // | parallel for | section | + |
  1948. // | parallel for | single | + |
  1949. // | parallel for | parallel for | * |
  1950. // | parallel for |parallel for simd| * |
  1951. // | parallel for |parallel sections| * |
  1952. // | parallel for | task | * |
  1953. // | parallel for | taskyield | * |
  1954. // | parallel for | barrier | + |
  1955. // | parallel for | taskwait | * |
  1956. // | parallel for | taskgroup | * |
  1957. // | parallel for | flush | * |
  1958. // | parallel for | ordered | * (if construct is ordered) |
  1959. // | parallel for | atomic | * |
  1960. // | parallel for | target | * |
  1961. // | parallel for | teams | + |
  1962. // | parallel for | cancellation | |
  1963. // | | point | ! |
  1964. // | parallel for | cancel | ! |
  1965. // +------------------+-----------------+------------------------------------+
  1966. // | parallel sections| parallel | * |
  1967. // | parallel sections| for | + |
  1968. // | parallel sections| for simd | + |
  1969. // | parallel sections| master | + |
  1970. // | parallel sections| critical | + |
  1971. // | parallel sections| simd | * |
  1972. // | parallel sections| sections | + |
  1973. // | parallel sections| section | * |
  1974. // | parallel sections| single | + |
  1975. // | parallel sections| parallel for | * |
  1976. // | parallel sections|parallel for simd| * |
  1977. // | parallel sections|parallel sections| * |
  1978. // | parallel sections| task | * |
  1979. // | parallel sections| taskyield | * |
  1980. // | parallel sections| barrier | + |
  1981. // | parallel sections| taskwait | * |
  1982. // | parallel sections| taskgroup | * |
  1983. // | parallel sections| flush | * |
  1984. // | parallel sections| ordered | + |
  1985. // | parallel sections| atomic | * |
  1986. // | parallel sections| target | * |
  1987. // | parallel sections| teams | + |
  1988. // | parallel sections| cancellation | |
  1989. // | | point | ! |
  1990. // | parallel sections| cancel | ! |
  1991. // +------------------+-----------------+------------------------------------+
  1992. // | task | parallel | * |
  1993. // | task | for | + |
  1994. // | task | for simd | + |
  1995. // | task | master | + |
  1996. // | task | critical | * |
  1997. // | task | simd | * |
  1998. // | task | sections | + |
  1999. // | task | section | + |
  2000. // | task | single | + |
  2001. // | task | parallel for | * |
  2002. // | task |parallel for simd| * |
  2003. // | task |parallel sections| * |
  2004. // | task | task | * |
  2005. // | task | taskyield | * |
  2006. // | task | barrier | + |
  2007. // | task | taskwait | * |
  2008. // | task | taskgroup | * |
  2009. // | task | flush | * |
  2010. // | task | ordered | + |
  2011. // | task | atomic | * |
  2012. // | task | target | * |
  2013. // | task | teams | + |
  2014. // | task | cancellation | |
  2015. // | | point | ! |
  2016. // | task | cancel | ! |
  2017. // +------------------+-----------------+------------------------------------+
  2018. // | ordered | parallel | * |
  2019. // | ordered | for | + |
  2020. // | ordered | for simd | + |
  2021. // | ordered | master | * |
  2022. // | ordered | critical | * |
  2023. // | ordered | simd | * |
  2024. // | ordered | sections | + |
  2025. // | ordered | section | + |
  2026. // | ordered | single | + |
  2027. // | ordered | parallel for | * |
  2028. // | ordered |parallel for simd| * |
  2029. // | ordered |parallel sections| * |
  2030. // | ordered | task | * |
  2031. // | ordered | taskyield | * |
  2032. // | ordered | barrier | + |
  2033. // | ordered | taskwait | * |
  2034. // | ordered | taskgroup | * |
  2035. // | ordered | flush | * |
  2036. // | ordered | ordered | + |
  2037. // | ordered | atomic | * |
  2038. // | ordered | target | * |
  2039. // | ordered | teams | + |
  2040. // | ordered | cancellation | |
  2041. // | | point | |
  2042. // | ordered | cancel | |
  2043. // +------------------+-----------------+------------------------------------+
  2044. // | atomic | parallel | |
  2045. // | atomic | for | |
  2046. // | atomic | for simd | |
  2047. // | atomic | master | |
  2048. // | atomic | critical | |
  2049. // | atomic | simd | |
  2050. // | atomic | sections | |
  2051. // | atomic | section | |
  2052. // | atomic | single | |
  2053. // | atomic | parallel for | |
  2054. // | atomic |parallel for simd| |
  2055. // | atomic |parallel sections| |
  2056. // | atomic | task | |
  2057. // | atomic | taskyield | |
  2058. // | atomic | barrier | |
  2059. // | atomic | taskwait | |
  2060. // | atomic | taskgroup | |
  2061. // | atomic | flush | |
  2062. // | atomic | ordered | |
  2063. // | atomic | atomic | |
  2064. // | atomic | target | |
  2065. // | atomic | teams | |
  2066. // | atomic | cancellation | |
  2067. // | | point | |
  2068. // | atomic | cancel | |
  2069. // +------------------+-----------------+------------------------------------+
  2070. // | target | parallel | * |
  2071. // | target | for | * |
  2072. // | target | for simd | * |
  2073. // | target | master | * |
  2074. // | target | critical | * |
  2075. // | target | simd | * |
  2076. // | target | sections | * |
  2077. // | target | section | * |
  2078. // | target | single | * |
  2079. // | target | parallel for | * |
  2080. // | target |parallel for simd| * |
  2081. // | target |parallel sections| * |
  2082. // | target | task | * |
  2083. // | target | taskyield | * |
  2084. // | target | barrier | * |
  2085. // | target | taskwait | * |
  2086. // | target | taskgroup | * |
  2087. // | target | flush | * |
  2088. // | target | ordered | * |
  2089. // | target | atomic | * |
  2090. // | target | target | * |
  2091. // | target | teams | * |
  2092. // | target | cancellation | |
  2093. // | | point | |
  2094. // | target | cancel | |
  2095. // +------------------+-----------------+------------------------------------+
  2096. // | teams | parallel | * |
  2097. // | teams | for | + |
  2098. // | teams | for simd | + |
  2099. // | teams | master | + |
  2100. // | teams | critical | + |
  2101. // | teams | simd | + |
  2102. // | teams | sections | + |
  2103. // | teams | section | + |
  2104. // | teams | single | + |
  2105. // | teams | parallel for | * |
  2106. // | teams |parallel for simd| * |
  2107. // | teams |parallel sections| * |
  2108. // | teams | task | + |
  2109. // | teams | taskyield | + |
  2110. // | teams | barrier | + |
  2111. // | teams | taskwait | + |
  2112. // | teams | taskgroup | + |
  2113. // | teams | flush | + |
  2114. // | teams | ordered | + |
  2115. // | teams | atomic | + |
  2116. // | teams | target | + |
  2117. // | teams | teams | + |
  2118. // | teams | cancellation | |
  2119. // | | point | |
  2120. // | teams | cancel | |
  2121. // +------------------+-----------------+------------------------------------+
  2122. if (Stack->getCurScope()) {
  2123. auto ParentRegion = Stack->getParentDirective();
  2124. bool NestingProhibited = false;
  2125. bool CloseNesting = true;
  2126. enum {
  2127. NoRecommend,
  2128. ShouldBeInParallelRegion,
  2129. ShouldBeInOrderedRegion,
  2130. ShouldBeInTargetRegion
  2131. } Recommend = NoRecommend;
  2132. if (isOpenMPSimdDirective(ParentRegion)) {
  2133. // OpenMP [2.16, Nesting of Regions]
  2134. // OpenMP constructs may not be nested inside a simd region.
  2135. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  2136. return true;
  2137. }
  2138. if (ParentRegion == OMPD_atomic) {
  2139. // OpenMP [2.16, Nesting of Regions]
  2140. // OpenMP constructs may not be nested inside an atomic region.
  2141. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2142. return true;
  2143. }
  2144. if (CurrentRegion == OMPD_section) {
  2145. // OpenMP [2.7.2, sections Construct, Restrictions]
  2146. // Orphaned section directives are prohibited. That is, the section
  2147. // directives must appear within the sections construct and must not be
  2148. // encountered elsewhere in the sections region.
  2149. if (ParentRegion != OMPD_sections &&
  2150. ParentRegion != OMPD_parallel_sections) {
  2151. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2152. << (ParentRegion != OMPD_unknown)
  2153. << getOpenMPDirectiveName(ParentRegion);
  2154. return true;
  2155. }
  2156. return false;
  2157. }
  2158. // Allow some constructs to be orphaned (they could be used in functions,
  2159. // called from OpenMP regions with the required preconditions).
  2160. if (ParentRegion == OMPD_unknown)
  2161. return false;
  2162. if (CurrentRegion == OMPD_cancellation_point ||
  2163. CurrentRegion == OMPD_cancel) {
  2164. // OpenMP [2.16, Nesting of Regions]
  2165. // A cancellation point construct for which construct-type-clause is
  2166. // taskgroup must be nested inside a task construct. A cancellation
  2167. // point construct for which construct-type-clause is not taskgroup must
  2168. // be closely nested inside an OpenMP construct that matches the type
  2169. // specified in construct-type-clause.
  2170. // A cancel construct for which construct-type-clause is taskgroup must be
  2171. // nested inside a task construct. A cancel construct for which
  2172. // construct-type-clause is not taskgroup must be closely nested inside an
  2173. // OpenMP construct that matches the type specified in
  2174. // construct-type-clause.
  2175. NestingProhibited =
  2176. !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
  2177. (CancelRegion == OMPD_for && ParentRegion == OMPD_for) ||
  2178. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2179. (CancelRegion == OMPD_sections &&
  2180. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections)));
  2181. } else if (CurrentRegion == OMPD_master) {
  2182. // OpenMP [2.16, Nesting of Regions]
  2183. // A master region may not be closely nested inside a worksharing,
  2184. // atomic, or explicit task region.
  2185. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2186. ParentRegion == OMPD_task;
  2187. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2188. // OpenMP [2.16, Nesting of Regions]
  2189. // A critical region may not be nested (closely or otherwise) inside a
  2190. // critical region with the same name. Note that this restriction is not
  2191. // sufficient to prevent deadlock.
  2192. SourceLocation PreviousCriticalLoc;
  2193. bool DeadLock =
  2194. Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
  2195. OpenMPDirectiveKind K,
  2196. const DeclarationNameInfo &DNI,
  2197. SourceLocation Loc)
  2198. ->bool {
  2199. if (K == OMPD_critical &&
  2200. DNI.getName() == CurrentName.getName()) {
  2201. PreviousCriticalLoc = Loc;
  2202. return true;
  2203. } else
  2204. return false;
  2205. },
  2206. false /* skip top directive */);
  2207. if (DeadLock) {
  2208. SemaRef.Diag(StartLoc,
  2209. diag::err_omp_prohibited_region_critical_same_name)
  2210. << CurrentName.getName();
  2211. if (PreviousCriticalLoc.isValid())
  2212. SemaRef.Diag(PreviousCriticalLoc,
  2213. diag::note_omp_previous_critical_region);
  2214. return true;
  2215. }
  2216. } else if (CurrentRegion == OMPD_barrier) {
  2217. // OpenMP [2.16, Nesting of Regions]
  2218. // A barrier region may not be closely nested inside a worksharing,
  2219. // explicit task, critical, ordered, atomic, or master region.
  2220. NestingProhibited =
  2221. isOpenMPWorksharingDirective(ParentRegion) ||
  2222. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2223. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  2224. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2225. !isOpenMPParallelDirective(CurrentRegion)) {
  2226. // OpenMP [2.16, Nesting of Regions]
  2227. // A worksharing region may not be closely nested inside a worksharing,
  2228. // explicit task, critical, ordered, atomic, or master region.
  2229. NestingProhibited =
  2230. isOpenMPWorksharingDirective(ParentRegion) ||
  2231. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2232. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  2233. Recommend = ShouldBeInParallelRegion;
  2234. } else if (CurrentRegion == OMPD_ordered) {
  2235. // OpenMP [2.16, Nesting of Regions]
  2236. // An ordered region may not be closely nested inside a critical,
  2237. // atomic, or explicit task region.
  2238. // An ordered region must be closely nested inside a loop region (or
  2239. // parallel loop region) with an ordered clause.
  2240. NestingProhibited = ParentRegion == OMPD_critical ||
  2241. ParentRegion == OMPD_task ||
  2242. !Stack->isParentOrderedRegion();
  2243. Recommend = ShouldBeInOrderedRegion;
  2244. } else if (isOpenMPTeamsDirective(CurrentRegion)) {
  2245. // OpenMP [2.16, Nesting of Regions]
  2246. // If specified, a teams construct must be contained within a target
  2247. // construct.
  2248. NestingProhibited = ParentRegion != OMPD_target;
  2249. Recommend = ShouldBeInTargetRegion;
  2250. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  2251. }
  2252. if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
  2253. // OpenMP [2.16, Nesting of Regions]
  2254. // distribute, parallel, parallel sections, parallel workshare, and the
  2255. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2256. // constructs that can be closely nested in the teams region.
  2257. // TODO: add distribute directive.
  2258. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
  2259. Recommend = ShouldBeInParallelRegion;
  2260. }
  2261. if (NestingProhibited) {
  2262. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2263. << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
  2264. << getOpenMPDirectiveName(CurrentRegion);
  2265. return true;
  2266. }
  2267. }
  2268. return false;
  2269. }
  2270. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2271. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2272. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2273. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2274. StmtResult Res = StmtError();
  2275. if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2276. StartLoc))
  2277. return StmtError();
  2278. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2279. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  2280. bool ErrorFound = false;
  2281. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2282. if (AStmt) {
  2283. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2284. // Check default data sharing attributes for referenced variables.
  2285. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2286. DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
  2287. if (DSAChecker.isErrorFound())
  2288. return StmtError();
  2289. // Generate list of implicitly defined firstprivate variables.
  2290. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2291. if (!DSAChecker.getImplicitFirstprivate().empty()) {
  2292. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2293. DSAChecker.getImplicitFirstprivate(), SourceLocation(),
  2294. SourceLocation(), SourceLocation())) {
  2295. ClausesWithImplicit.push_back(Implicit);
  2296. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2297. DSAChecker.getImplicitFirstprivate().size();
  2298. } else
  2299. ErrorFound = true;
  2300. }
  2301. }
  2302. switch (Kind) {
  2303. case OMPD_parallel:
  2304. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2305. EndLoc);
  2306. break;
  2307. case OMPD_simd:
  2308. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2309. VarsWithInheritedDSA);
  2310. break;
  2311. case OMPD_for:
  2312. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2313. VarsWithInheritedDSA);
  2314. break;
  2315. case OMPD_for_simd:
  2316. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2317. EndLoc, VarsWithInheritedDSA);
  2318. break;
  2319. case OMPD_sections:
  2320. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2321. EndLoc);
  2322. break;
  2323. case OMPD_section:
  2324. assert(ClausesWithImplicit.empty() &&
  2325. "No clauses are allowed for 'omp section' directive");
  2326. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2327. break;
  2328. case OMPD_single:
  2329. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2330. EndLoc);
  2331. break;
  2332. case OMPD_master:
  2333. assert(ClausesWithImplicit.empty() &&
  2334. "No clauses are allowed for 'omp master' directive");
  2335. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2336. break;
  2337. case OMPD_critical:
  2338. assert(ClausesWithImplicit.empty() &&
  2339. "No clauses are allowed for 'omp critical' directive");
  2340. Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
  2341. break;
  2342. case OMPD_parallel_for:
  2343. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2344. EndLoc, VarsWithInheritedDSA);
  2345. break;
  2346. case OMPD_parallel_for_simd:
  2347. Res = ActOnOpenMPParallelForSimdDirective(
  2348. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2349. break;
  2350. case OMPD_parallel_sections:
  2351. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2352. StartLoc, EndLoc);
  2353. break;
  2354. case OMPD_task:
  2355. Res =
  2356. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2357. break;
  2358. case OMPD_taskyield:
  2359. assert(ClausesWithImplicit.empty() &&
  2360. "No clauses are allowed for 'omp taskyield' directive");
  2361. assert(AStmt == nullptr &&
  2362. "No associated statement allowed for 'omp taskyield' directive");
  2363. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2364. break;
  2365. case OMPD_barrier:
  2366. assert(ClausesWithImplicit.empty() &&
  2367. "No clauses are allowed for 'omp barrier' directive");
  2368. assert(AStmt == nullptr &&
  2369. "No associated statement allowed for 'omp barrier' directive");
  2370. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2371. break;
  2372. case OMPD_taskwait:
  2373. assert(ClausesWithImplicit.empty() &&
  2374. "No clauses are allowed for 'omp taskwait' directive");
  2375. assert(AStmt == nullptr &&
  2376. "No associated statement allowed for 'omp taskwait' directive");
  2377. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2378. break;
  2379. case OMPD_taskgroup:
  2380. assert(ClausesWithImplicit.empty() &&
  2381. "No clauses are allowed for 'omp taskgroup' directive");
  2382. Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
  2383. break;
  2384. case OMPD_flush:
  2385. assert(AStmt == nullptr &&
  2386. "No associated statement allowed for 'omp flush' directive");
  2387. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2388. break;
  2389. case OMPD_ordered:
  2390. assert(ClausesWithImplicit.empty() &&
  2391. "No clauses are allowed for 'omp ordered' directive");
  2392. Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
  2393. break;
  2394. case OMPD_atomic:
  2395. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2396. EndLoc);
  2397. break;
  2398. case OMPD_teams:
  2399. Res =
  2400. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2401. break;
  2402. case OMPD_target:
  2403. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2404. EndLoc);
  2405. break;
  2406. case OMPD_cancellation_point:
  2407. assert(ClausesWithImplicit.empty() &&
  2408. "No clauses are allowed for 'omp cancellation point' directive");
  2409. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2410. "cancellation point' directive");
  2411. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2412. break;
  2413. case OMPD_cancel:
  2414. assert(ClausesWithImplicit.empty() &&
  2415. "No clauses are allowed for 'omp cancel' directive");
  2416. assert(AStmt == nullptr &&
  2417. "No associated statement allowed for 'omp cancel' directive");
  2418. Res = ActOnOpenMPCancelDirective(StartLoc, EndLoc, CancelRegion);
  2419. break;
  2420. case OMPD_threadprivate:
  2421. llvm_unreachable("OpenMP Directive is not allowed");
  2422. case OMPD_unknown:
  2423. llvm_unreachable("Unknown OpenMP directive");
  2424. }
  2425. for (auto P : VarsWithInheritedDSA) {
  2426. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2427. << P.first << P.second->getSourceRange();
  2428. }
  2429. if (!VarsWithInheritedDSA.empty())
  2430. return StmtError();
  2431. if (ErrorFound)
  2432. return StmtError();
  2433. return Res;
  2434. }
  2435. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  2436. Stmt *AStmt,
  2437. SourceLocation StartLoc,
  2438. SourceLocation EndLoc) {
  2439. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2440. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2441. // 1.2.2 OpenMP Language Terminology
  2442. // Structured block - An executable statement with a single entry at the
  2443. // top and a single exit at the bottom.
  2444. // The point of exit cannot be a branch out of the structured block.
  2445. // longjmp() and throw() must not violate the entry/exit criteria.
  2446. CS->getCapturedDecl()->setNothrow();
  2447. getCurFunction()->setHasBranchProtectedScope();
  2448. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  2449. AStmt);
  2450. }
  2451. namespace {
  2452. /// \brief Helper class for checking canonical form of the OpenMP loops and
  2453. /// extracting iteration space of each loop in the loop nest, that will be used
  2454. /// for IR generation.
  2455. class OpenMPIterationSpaceChecker {
  2456. /// \brief Reference to Sema.
  2457. Sema &SemaRef;
  2458. /// \brief A location for diagnostics (when there is no some better location).
  2459. SourceLocation DefaultLoc;
  2460. /// \brief A location for diagnostics (when increment is not compatible).
  2461. SourceLocation ConditionLoc;
  2462. /// \brief A source location for referring to loop init later.
  2463. SourceRange InitSrcRange;
  2464. /// \brief A source location for referring to condition later.
  2465. SourceRange ConditionSrcRange;
  2466. /// \brief A source location for referring to increment later.
  2467. SourceRange IncrementSrcRange;
  2468. /// \brief Loop variable.
  2469. VarDecl *Var;
  2470. /// \brief Reference to loop variable.
  2471. DeclRefExpr *VarRef;
  2472. /// \brief Lower bound (initializer for the var).
  2473. Expr *LB;
  2474. /// \brief Upper bound.
  2475. Expr *UB;
  2476. /// \brief Loop step (increment).
  2477. Expr *Step;
  2478. /// \brief This flag is true when condition is one of:
  2479. /// Var < UB
  2480. /// Var <= UB
  2481. /// UB > Var
  2482. /// UB >= Var
  2483. bool TestIsLessOp;
  2484. /// \brief This flag is true when condition is strict ( < or > ).
  2485. bool TestIsStrictOp;
  2486. /// \brief This flag is true when step is subtracted on each iteration.
  2487. bool SubtractStep;
  2488. public:
  2489. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  2490. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
  2491. InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
  2492. IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
  2493. LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
  2494. TestIsStrictOp(false), SubtractStep(false) {}
  2495. /// \brief Check init-expr for canonical loop form and save loop counter
  2496. /// variable - #Var and its initialization value - #LB.
  2497. bool CheckInit(Stmt *S, bool EmitDiags = true);
  2498. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  2499. /// for less/greater and for strict/non-strict comparison.
  2500. bool CheckCond(Expr *S);
  2501. /// \brief Check incr-expr for canonical loop form and return true if it
  2502. /// does not conform, otherwise save loop step (#Step).
  2503. bool CheckInc(Expr *S);
  2504. /// \brief Return the loop counter variable.
  2505. VarDecl *GetLoopVar() const { return Var; }
  2506. /// \brief Return the reference expression to loop counter variable.
  2507. DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
  2508. /// \brief Source range of the loop init.
  2509. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  2510. /// \brief Source range of the loop condition.
  2511. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  2512. /// \brief Source range of the loop increment.
  2513. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  2514. /// \brief True if the step should be subtracted.
  2515. bool ShouldSubtractStep() const { return SubtractStep; }
  2516. /// \brief Build the expression to calculate the number of iterations.
  2517. Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
  2518. /// \brief Build the precondition expression for the loops.
  2519. Expr *BuildPreCond(Scope *S, Expr *Cond) const;
  2520. /// \brief Build reference expression to the counter be used for codegen.
  2521. Expr *BuildCounterVar() const;
  2522. /// \brief Build initization of the counter be used for codegen.
  2523. Expr *BuildCounterInit() const;
  2524. /// \brief Build step of the counter be used for codegen.
  2525. Expr *BuildCounterStep() const;
  2526. /// \brief Return true if any expression is dependent.
  2527. bool Dependent() const;
  2528. private:
  2529. /// \brief Check the right-hand side of an assignment in the increment
  2530. /// expression.
  2531. bool CheckIncRHS(Expr *RHS);
  2532. /// \brief Helper to set loop counter variable and its initializer.
  2533. bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
  2534. /// \brief Helper to set upper bound.
  2535. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
  2536. const SourceLocation &SL);
  2537. /// \brief Helper to set loop increment.
  2538. bool SetStep(Expr *NewStep, bool Subtract);
  2539. };
  2540. bool OpenMPIterationSpaceChecker::Dependent() const {
  2541. if (!Var) {
  2542. assert(!LB && !UB && !Step);
  2543. return false;
  2544. }
  2545. return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
  2546. (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
  2547. }
  2548. template <typename T>
  2549. static T *getExprAsWritten(T *E) {
  2550. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  2551. E = ExprTemp->getSubExpr();
  2552. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  2553. E = MTE->GetTemporaryExpr();
  2554. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  2555. E = Binder->getSubExpr();
  2556. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  2557. E = ICE->getSubExprAsWritten();
  2558. return E->IgnoreParens();
  2559. }
  2560. bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
  2561. DeclRefExpr *NewVarRefExpr,
  2562. Expr *NewLB) {
  2563. // State consistency checking to ensure correct usage.
  2564. assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
  2565. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  2566. if (!NewVar || !NewLB)
  2567. return true;
  2568. Var = NewVar;
  2569. VarRef = NewVarRefExpr;
  2570. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  2571. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2572. if ((Ctor->isCopyOrMoveConstructor() ||
  2573. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2574. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2575. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  2576. LB = NewLB;
  2577. return false;
  2578. }
  2579. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  2580. const SourceRange &SR,
  2581. const SourceLocation &SL) {
  2582. // State consistency checking to ensure correct usage.
  2583. assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
  2584. !TestIsLessOp && !TestIsStrictOp);
  2585. if (!NewUB)
  2586. return true;
  2587. UB = NewUB;
  2588. TestIsLessOp = LessOp;
  2589. TestIsStrictOp = StrictOp;
  2590. ConditionSrcRange = SR;
  2591. ConditionLoc = SL;
  2592. return false;
  2593. }
  2594. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  2595. // State consistency checking to ensure correct usage.
  2596. assert(Var != nullptr && LB != nullptr && Step == nullptr);
  2597. if (!NewStep)
  2598. return true;
  2599. if (!NewStep->isValueDependent()) {
  2600. // Check that the step is integer expression.
  2601. SourceLocation StepLoc = NewStep->getLocStart();
  2602. ExprResult Val =
  2603. SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
  2604. if (Val.isInvalid())
  2605. return true;
  2606. NewStep = Val.get();
  2607. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  2608. // If test-expr is of form var relational-op b and relational-op is < or
  2609. // <= then incr-expr must cause var to increase on each iteration of the
  2610. // loop. If test-expr is of form var relational-op b and relational-op is
  2611. // > or >= then incr-expr must cause var to decrease on each iteration of
  2612. // the loop.
  2613. // If test-expr is of form b relational-op var and relational-op is < or
  2614. // <= then incr-expr must cause var to decrease on each iteration of the
  2615. // loop. If test-expr is of form b relational-op var and relational-op is
  2616. // > or >= then incr-expr must cause var to increase on each iteration of
  2617. // the loop.
  2618. llvm::APSInt Result;
  2619. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  2620. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  2621. bool IsConstNeg =
  2622. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  2623. bool IsConstPos =
  2624. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  2625. bool IsConstZero = IsConstant && !Result.getBoolValue();
  2626. if (UB && (IsConstZero ||
  2627. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  2628. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  2629. SemaRef.Diag(NewStep->getExprLoc(),
  2630. diag::err_omp_loop_incr_not_compatible)
  2631. << Var << TestIsLessOp << NewStep->getSourceRange();
  2632. SemaRef.Diag(ConditionLoc,
  2633. diag::note_omp_loop_cond_requres_compatible_incr)
  2634. << TestIsLessOp << ConditionSrcRange;
  2635. return true;
  2636. }
  2637. if (TestIsLessOp == Subtract) {
  2638. NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
  2639. NewStep).get();
  2640. Subtract = !Subtract;
  2641. }
  2642. }
  2643. Step = NewStep;
  2644. SubtractStep = Subtract;
  2645. return false;
  2646. }
  2647. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  2648. // Check init-expr for canonical loop form and save loop counter
  2649. // variable - #Var and its initialization value - #LB.
  2650. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  2651. // var = lb
  2652. // integer-type var = lb
  2653. // random-access-iterator-type var = lb
  2654. // pointer-type var = lb
  2655. //
  2656. if (!S) {
  2657. if (EmitDiags) {
  2658. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  2659. }
  2660. return true;
  2661. }
  2662. InitSrcRange = S->getSourceRange();
  2663. if (Expr *E = dyn_cast<Expr>(S))
  2664. S = E->IgnoreParens();
  2665. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2666. if (BO->getOpcode() == BO_Assign)
  2667. if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
  2668. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  2669. BO->getRHS());
  2670. } else if (auto DS = dyn_cast<DeclStmt>(S)) {
  2671. if (DS->isSingleDecl()) {
  2672. if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  2673. if (Var->hasInit()) {
  2674. // Accept non-canonical init form here but emit ext. warning.
  2675. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  2676. SemaRef.Diag(S->getLocStart(),
  2677. diag::ext_omp_loop_not_canonical_init)
  2678. << S->getSourceRange();
  2679. return SetVarAndLB(Var, nullptr, Var->getInit());
  2680. }
  2681. }
  2682. }
  2683. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
  2684. if (CE->getOperator() == OO_Equal)
  2685. if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
  2686. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  2687. CE->getArg(1));
  2688. if (EmitDiags) {
  2689. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  2690. << S->getSourceRange();
  2691. }
  2692. return true;
  2693. }
  2694. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  2695. /// variable (which may be the loop variable) if possible.
  2696. static const VarDecl *GetInitVarDecl(const Expr *E) {
  2697. if (!E)
  2698. return nullptr;
  2699. E = getExprAsWritten(E);
  2700. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  2701. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2702. if ((Ctor->isCopyOrMoveConstructor() ||
  2703. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2704. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2705. E = CE->getArg(0)->IgnoreParenImpCasts();
  2706. auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
  2707. if (!DRE)
  2708. return nullptr;
  2709. return dyn_cast<VarDecl>(DRE->getDecl());
  2710. }
  2711. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  2712. // Check test-expr for canonical form, save upper-bound UB, flags for
  2713. // less/greater and for strict/non-strict comparison.
  2714. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2715. // var relational-op b
  2716. // b relational-op var
  2717. //
  2718. if (!S) {
  2719. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
  2720. return true;
  2721. }
  2722. S = getExprAsWritten(S);
  2723. SourceLocation CondLoc = S->getLocStart();
  2724. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2725. if (BO->isRelationalOp()) {
  2726. if (GetInitVarDecl(BO->getLHS()) == Var)
  2727. return SetUB(BO->getRHS(),
  2728. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  2729. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2730. BO->getSourceRange(), BO->getOperatorLoc());
  2731. if (GetInitVarDecl(BO->getRHS()) == Var)
  2732. return SetUB(BO->getLHS(),
  2733. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  2734. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2735. BO->getSourceRange(), BO->getOperatorLoc());
  2736. }
  2737. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2738. if (CE->getNumArgs() == 2) {
  2739. auto Op = CE->getOperator();
  2740. switch (Op) {
  2741. case OO_Greater:
  2742. case OO_GreaterEqual:
  2743. case OO_Less:
  2744. case OO_LessEqual:
  2745. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2746. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  2747. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2748. CE->getOperatorLoc());
  2749. if (GetInitVarDecl(CE->getArg(1)) == Var)
  2750. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  2751. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2752. CE->getOperatorLoc());
  2753. break;
  2754. default:
  2755. break;
  2756. }
  2757. }
  2758. }
  2759. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  2760. << S->getSourceRange() << Var;
  2761. return true;
  2762. }
  2763. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  2764. // RHS of canonical loop form increment can be:
  2765. // var + incr
  2766. // incr + var
  2767. // var - incr
  2768. //
  2769. RHS = RHS->IgnoreParenImpCasts();
  2770. if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
  2771. if (BO->isAdditiveOp()) {
  2772. bool IsAdd = BO->getOpcode() == BO_Add;
  2773. if (GetInitVarDecl(BO->getLHS()) == Var)
  2774. return SetStep(BO->getRHS(), !IsAdd);
  2775. if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
  2776. return SetStep(BO->getLHS(), false);
  2777. }
  2778. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  2779. bool IsAdd = CE->getOperator() == OO_Plus;
  2780. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  2781. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2782. return SetStep(CE->getArg(1), !IsAdd);
  2783. if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
  2784. return SetStep(CE->getArg(0), false);
  2785. }
  2786. }
  2787. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2788. << RHS->getSourceRange() << Var;
  2789. return true;
  2790. }
  2791. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  2792. // Check incr-expr for canonical loop form and return true if it
  2793. // does not conform.
  2794. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2795. // ++var
  2796. // var++
  2797. // --var
  2798. // var--
  2799. // var += incr
  2800. // var -= incr
  2801. // var = var + incr
  2802. // var = incr + var
  2803. // var = var - incr
  2804. //
  2805. if (!S) {
  2806. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
  2807. return true;
  2808. }
  2809. IncrementSrcRange = S->getSourceRange();
  2810. S = S->IgnoreParens();
  2811. if (auto UO = dyn_cast<UnaryOperator>(S)) {
  2812. if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
  2813. return SetStep(
  2814. SemaRef.ActOnIntegerConstant(UO->getLocStart(),
  2815. (UO->isDecrementOp() ? -1 : 1)).get(),
  2816. false);
  2817. } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2818. switch (BO->getOpcode()) {
  2819. case BO_AddAssign:
  2820. case BO_SubAssign:
  2821. if (GetInitVarDecl(BO->getLHS()) == Var)
  2822. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  2823. break;
  2824. case BO_Assign:
  2825. if (GetInitVarDecl(BO->getLHS()) == Var)
  2826. return CheckIncRHS(BO->getRHS());
  2827. break;
  2828. default:
  2829. break;
  2830. }
  2831. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2832. switch (CE->getOperator()) {
  2833. case OO_PlusPlus:
  2834. case OO_MinusMinus:
  2835. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2836. return SetStep(
  2837. SemaRef.ActOnIntegerConstant(
  2838. CE->getLocStart(),
  2839. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
  2840. false);
  2841. break;
  2842. case OO_PlusEqual:
  2843. case OO_MinusEqual:
  2844. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2845. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  2846. break;
  2847. case OO_Equal:
  2848. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2849. return CheckIncRHS(CE->getArg(1));
  2850. break;
  2851. default:
  2852. break;
  2853. }
  2854. }
  2855. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2856. << S->getSourceRange() << Var;
  2857. return true;
  2858. }
  2859. namespace {
  2860. // Transform variables declared in GNU statement expressions to new ones to
  2861. // avoid crash on codegen.
  2862. class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
  2863. typedef TreeTransform<TransformToNewDefs> BaseTransform;
  2864. public:
  2865. TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
  2866. Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
  2867. if (auto *VD = cast<VarDecl>(D))
  2868. if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
  2869. !isa<ImplicitParamDecl>(D)) {
  2870. auto *NewVD = VarDecl::Create(
  2871. SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
  2872. VD->getLocation(), VD->getIdentifier(), VD->getType(),
  2873. VD->getTypeSourceInfo(), VD->getStorageClass());
  2874. NewVD->setTSCSpec(VD->getTSCSpec());
  2875. NewVD->setInit(VD->getInit());
  2876. NewVD->setInitStyle(VD->getInitStyle());
  2877. NewVD->setExceptionVariable(VD->isExceptionVariable());
  2878. NewVD->setNRVOVariable(VD->isNRVOVariable());
  2879. NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
  2880. NewVD->setConstexpr(VD->isConstexpr());
  2881. NewVD->setInitCapture(VD->isInitCapture());
  2882. NewVD->setPreviousDeclInSameBlockScope(
  2883. VD->isPreviousDeclInSameBlockScope());
  2884. VD->getDeclContext()->addHiddenDecl(NewVD);
  2885. transformedLocalDecl(VD, NewVD);
  2886. return NewVD;
  2887. }
  2888. return BaseTransform::TransformDefinition(Loc, D);
  2889. }
  2890. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  2891. if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
  2892. if (E->getDecl() != NewD) {
  2893. NewD->setReferenced();
  2894. NewD->markUsed(SemaRef.Context);
  2895. return DeclRefExpr::Create(
  2896. SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
  2897. cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
  2898. E->getNameInfo(), E->getType(), E->getValueKind());
  2899. }
  2900. return BaseTransform::TransformDeclRefExpr(E);
  2901. }
  2902. };
  2903. }
  2904. /// \brief Build the expression to calculate the number of iterations.
  2905. Expr *
  2906. OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
  2907. const bool LimitedType) const {
  2908. TransformToNewDefs Transform(SemaRef);
  2909. ExprResult Diff;
  2910. auto VarType = Var->getType().getNonReferenceType();
  2911. if (VarType->isIntegerType() || VarType->isPointerType() ||
  2912. SemaRef.getLangOpts().CPlusPlus) {
  2913. // Upper - Lower
  2914. auto *UBExpr = TestIsLessOp ? UB : LB;
  2915. auto *LBExpr = TestIsLessOp ? LB : UB;
  2916. Expr *Upper = Transform.TransformExpr(UBExpr).get();
  2917. Expr *Lower = Transform.TransformExpr(LBExpr).get();
  2918. if (!Upper || !Lower)
  2919. return nullptr;
  2920. Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
  2921. Sema::AA_Converting,
  2922. /*AllowExplicit=*/true)
  2923. .get();
  2924. Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
  2925. Sema::AA_Converting,
  2926. /*AllowExplicit=*/true)
  2927. .get();
  2928. if (!Upper || !Lower)
  2929. return nullptr;
  2930. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  2931. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  2932. // BuildBinOp already emitted error, this one is to point user to upper
  2933. // and lower bound, and to tell what is passed to 'operator-'.
  2934. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  2935. << Upper->getSourceRange() << Lower->getSourceRange();
  2936. return nullptr;
  2937. }
  2938. }
  2939. if (!Diff.isUsable())
  2940. return nullptr;
  2941. // Upper - Lower [- 1]
  2942. if (TestIsStrictOp)
  2943. Diff = SemaRef.BuildBinOp(
  2944. S, DefaultLoc, BO_Sub, Diff.get(),
  2945. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  2946. if (!Diff.isUsable())
  2947. return nullptr;
  2948. // Upper - Lower [- 1] + Step
  2949. auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  2950. if (NewStep.isInvalid())
  2951. return nullptr;
  2952. NewStep = SemaRef.PerformImplicitConversion(
  2953. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  2954. /*AllowExplicit=*/true);
  2955. if (NewStep.isInvalid())
  2956. return nullptr;
  2957. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  2958. if (!Diff.isUsable())
  2959. return nullptr;
  2960. // Parentheses (for dumping/debugging purposes only).
  2961. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  2962. if (!Diff.isUsable())
  2963. return nullptr;
  2964. // (Upper - Lower [- 1] + Step) / Step
  2965. NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  2966. if (NewStep.isInvalid())
  2967. return nullptr;
  2968. NewStep = SemaRef.PerformImplicitConversion(
  2969. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  2970. /*AllowExplicit=*/true);
  2971. if (NewStep.isInvalid())
  2972. return nullptr;
  2973. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  2974. if (!Diff.isUsable())
  2975. return nullptr;
  2976. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  2977. QualType Type = Diff.get()->getType();
  2978. auto &C = SemaRef.Context;
  2979. bool UseVarType = VarType->hasIntegerRepresentation() &&
  2980. C.getTypeSize(Type) > C.getTypeSize(VarType);
  2981. if (!Type->isIntegerType() || UseVarType) {
  2982. unsigned NewSize =
  2983. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  2984. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  2985. : Type->hasSignedIntegerRepresentation();
  2986. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  2987. Diff = SemaRef.PerformImplicitConversion(
  2988. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  2989. if (!Diff.isUsable())
  2990. return nullptr;
  2991. }
  2992. if (LimitedType) {
  2993. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  2994. if (NewSize != C.getTypeSize(Type)) {
  2995. if (NewSize < C.getTypeSize(Type)) {
  2996. assert(NewSize == 64 && "incorrect loop var size");
  2997. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  2998. << InitSrcRange << ConditionSrcRange;
  2999. }
  3000. QualType NewType = C.getIntTypeForBitwidth(
  3001. NewSize, Type->hasSignedIntegerRepresentation() ||
  3002. C.getTypeSize(Type) < NewSize);
  3003. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3004. Sema::AA_Converting, true);
  3005. if (!Diff.isUsable())
  3006. return nullptr;
  3007. }
  3008. }
  3009. return Diff.get();
  3010. }
  3011. Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
  3012. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3013. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3014. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3015. TransformToNewDefs Transform(SemaRef);
  3016. auto NewLB = Transform.TransformExpr(LB);
  3017. auto NewUB = Transform.TransformExpr(UB);
  3018. if (NewLB.isInvalid() || NewUB.isInvalid())
  3019. return Cond;
  3020. NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
  3021. Sema::AA_Converting,
  3022. /*AllowExplicit=*/true);
  3023. NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
  3024. Sema::AA_Converting,
  3025. /*AllowExplicit=*/true);
  3026. if (NewLB.isInvalid() || NewUB.isInvalid())
  3027. return Cond;
  3028. auto CondExpr = SemaRef.BuildBinOp(
  3029. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3030. : (TestIsStrictOp ? BO_GT : BO_GE),
  3031. NewLB.get(), NewUB.get());
  3032. if (CondExpr.isUsable()) {
  3033. CondExpr = SemaRef.PerformImplicitConversion(
  3034. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3035. /*AllowExplicit=*/true);
  3036. }
  3037. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3038. // Otherwise use original loop conditon and evaluate it in runtime.
  3039. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3040. }
  3041. /// \brief Build reference expression to the counter be used for codegen.
  3042. Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
  3043. return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
  3044. }
  3045. /// \brief Build initization of the counter be used for codegen.
  3046. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3047. /// \brief Build step of the counter be used for codegen.
  3048. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3049. /// \brief Iteration space of a single for loop.
  3050. struct LoopIterationSpace {
  3051. /// \brief Condition of the loop.
  3052. Expr *PreCond;
  3053. /// \brief This expression calculates the number of iterations in the loop.
  3054. /// It is always possible to calculate it before starting the loop.
  3055. Expr *NumIterations;
  3056. /// \brief The loop counter variable.
  3057. Expr *CounterVar;
  3058. /// \brief This is initializer for the initial value of #CounterVar.
  3059. Expr *CounterInit;
  3060. /// \brief This is step for the #CounterVar used to generate its update:
  3061. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3062. Expr *CounterStep;
  3063. /// \brief Should step be subtracted?
  3064. bool Subtract;
  3065. /// \brief Source range of the loop init.
  3066. SourceRange InitSrcRange;
  3067. /// \brief Source range of the loop condition.
  3068. SourceRange CondSrcRange;
  3069. /// \brief Source range of the loop increment.
  3070. SourceRange IncSrcRange;
  3071. };
  3072. } // namespace
  3073. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3074. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3075. assert(Init && "Expected loop in canonical form.");
  3076. unsigned CollapseIteration = DSAStack->getCollapseNumber();
  3077. if (CollapseIteration > 0 &&
  3078. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3079. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3080. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3081. DSAStack->addLoopControlVariable(ISC.GetLoopVar());
  3082. }
  3083. DSAStack->setCollapseNumber(CollapseIteration - 1);
  3084. }
  3085. }
  3086. /// \brief Called on a for stmt to check and extract its iteration space
  3087. /// for further processing (such as collapsing).
  3088. static bool CheckOpenMPIterationSpace(
  3089. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3090. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3091. Expr *NestedLoopCountExpr,
  3092. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  3093. LoopIterationSpace &ResultIterSpace) {
  3094. // OpenMP [2.6, Canonical Loop Form]
  3095. // for (init-expr; test-expr; incr-expr) structured-block
  3096. auto For = dyn_cast_or_null<ForStmt>(S);
  3097. if (!For) {
  3098. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3099. << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
  3100. << NestedLoopCount << (CurrentNestedLoopCount > 0)
  3101. << CurrentNestedLoopCount;
  3102. if (NestedLoopCount > 1)
  3103. SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
  3104. diag::note_omp_collapse_expr)
  3105. << NestedLoopCountExpr->getSourceRange();
  3106. return true;
  3107. }
  3108. assert(For->getBody());
  3109. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3110. // Check init.
  3111. auto Init = For->getInit();
  3112. if (ISC.CheckInit(Init)) {
  3113. return true;
  3114. }
  3115. bool HasErrors = false;
  3116. // Check loop variable's type.
  3117. auto Var = ISC.GetLoopVar();
  3118. // OpenMP [2.6, Canonical Loop Form]
  3119. // Var is one of the following:
  3120. // A variable of signed or unsigned integer type.
  3121. // For C++, a variable of a random access iterator type.
  3122. // For C, a variable of a pointer type.
  3123. auto VarType = Var->getType();
  3124. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3125. !VarType->isPointerType() &&
  3126. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3127. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3128. << SemaRef.getLangOpts().CPlusPlus;
  3129. HasErrors = true;
  3130. }
  3131. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
  3132. // Construct
  3133. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3134. // parallel for construct is (are) private.
  3135. // The loop iteration variable in the associated for-loop of a simd construct
  3136. // with just one associated for-loop is linear with a constant-linear-step
  3137. // that is the increment of the associated for-loop.
  3138. // Exclude loop var from the list of variables with implicitly defined data
  3139. // sharing attributes.
  3140. VarsWithImplicitDSA.erase(Var);
  3141. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
  3142. // a Construct, C/C++].
  3143. // The loop iteration variable in the associated for-loop of a simd construct
  3144. // with just one associated for-loop may be listed in a linear clause with a
  3145. // constant-linear-step that is the increment of the associated for-loop.
  3146. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3147. // parallel for construct may be listed in a private or lastprivate clause.
  3148. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
  3149. auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
  3150. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3151. // declared in the loop and it is predetermined as a private.
  3152. auto PredeterminedCKind =
  3153. isOpenMPSimdDirective(DKind)
  3154. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3155. : OMPC_private;
  3156. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3157. DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
  3158. (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
  3159. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
  3160. DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
  3161. ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
  3162. DVar.RefExpr != nullptr)) {
  3163. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3164. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3165. << getOpenMPClauseName(PredeterminedCKind);
  3166. if (DVar.RefExpr == nullptr)
  3167. DVar.CKind = PredeterminedCKind;
  3168. ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
  3169. HasErrors = true;
  3170. } else if (LoopVarRefExpr != nullptr) {
  3171. // Make the loop iteration variable private (for worksharing constructs),
  3172. // linear (for simd directives with the only one associated loop) or
  3173. // lastprivate (for simd directives with several collapsed loops).
  3174. if (DVar.CKind == OMPC_unknown)
  3175. DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
  3176. /*FromParent=*/false);
  3177. DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
  3178. }
  3179. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3180. // Check test-expr.
  3181. HasErrors |= ISC.CheckCond(For->getCond());
  3182. // Check incr-expr.
  3183. HasErrors |= ISC.CheckInc(For->getInc());
  3184. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3185. return HasErrors;
  3186. // Build the loop's iteration space representation.
  3187. ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
  3188. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3189. DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
  3190. ResultIterSpace.CounterVar = ISC.BuildCounterVar();
  3191. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3192. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  3193. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  3194. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  3195. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  3196. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  3197. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  3198. ResultIterSpace.NumIterations == nullptr ||
  3199. ResultIterSpace.CounterVar == nullptr ||
  3200. ResultIterSpace.CounterInit == nullptr ||
  3201. ResultIterSpace.CounterStep == nullptr);
  3202. return HasErrors;
  3203. }
  3204. /// \brief Build 'VarRef = Start.
  3205. static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
  3206. ExprResult VarRef, ExprResult Start) {
  3207. TransformToNewDefs Transform(SemaRef);
  3208. // Build 'VarRef = Start.
  3209. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3210. if (NewStart.isInvalid())
  3211. return ExprError();
  3212. NewStart = SemaRef.PerformImplicitConversion(
  3213. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3214. Sema::AA_Converting,
  3215. /*AllowExplicit=*/true);
  3216. if (NewStart.isInvalid())
  3217. return ExprError();
  3218. NewStart = SemaRef.PerformImplicitConversion(
  3219. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  3220. /*AllowExplicit=*/true);
  3221. if (!NewStart.isUsable())
  3222. return ExprError();
  3223. auto Init =
  3224. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3225. return Init;
  3226. }
  3227. /// \brief Build 'VarRef = Start + Iter * Step'.
  3228. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
  3229. SourceLocation Loc, ExprResult VarRef,
  3230. ExprResult Start, ExprResult Iter,
  3231. ExprResult Step, bool Subtract) {
  3232. // Add parentheses (for debugging purposes only).
  3233. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  3234. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  3235. !Step.isUsable())
  3236. return ExprError();
  3237. TransformToNewDefs Transform(SemaRef);
  3238. auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
  3239. if (NewStep.isInvalid())
  3240. return ExprError();
  3241. NewStep = SemaRef.PerformImplicitConversion(
  3242. NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
  3243. Sema::AA_Converting,
  3244. /*AllowExplicit=*/true);
  3245. if (NewStep.isInvalid())
  3246. return ExprError();
  3247. ExprResult Update =
  3248. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  3249. if (!Update.isUsable())
  3250. return ExprError();
  3251. // Build 'VarRef = Start + Iter * Step'.
  3252. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3253. if (NewStart.isInvalid())
  3254. return ExprError();
  3255. NewStart = SemaRef.PerformImplicitConversion(
  3256. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3257. Sema::AA_Converting,
  3258. /*AllowExplicit=*/true);
  3259. if (NewStart.isInvalid())
  3260. return ExprError();
  3261. Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
  3262. NewStart.get(), Update.get());
  3263. if (!Update.isUsable())
  3264. return ExprError();
  3265. Update = SemaRef.PerformImplicitConversion(
  3266. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  3267. if (!Update.isUsable())
  3268. return ExprError();
  3269. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  3270. return Update;
  3271. }
  3272. /// \brief Convert integer expression \a E to make it have at least \a Bits
  3273. /// bits.
  3274. static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
  3275. Sema &SemaRef) {
  3276. if (E == nullptr)
  3277. return ExprError();
  3278. auto &C = SemaRef.Context;
  3279. QualType OldType = E->getType();
  3280. unsigned HasBits = C.getTypeSize(OldType);
  3281. if (HasBits >= Bits)
  3282. return ExprResult(E);
  3283. // OK to convert to signed, because new type has more bits than old.
  3284. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  3285. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  3286. true);
  3287. }
  3288. /// \brief Check if the given expression \a E is a constant integer that fits
  3289. /// into \a Bits bits.
  3290. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  3291. if (E == nullptr)
  3292. return false;
  3293. llvm::APSInt Result;
  3294. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  3295. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  3296. return false;
  3297. }
  3298. /// \brief Called on a for stmt to check itself and nested loops (if any).
  3299. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  3300. /// number of collapsed loops otherwise.
  3301. static unsigned
  3302. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
  3303. Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
  3304. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  3305. OMPLoopDirective::HelperExprs &Built) {
  3306. unsigned NestedLoopCount = 1;
  3307. if (NestedLoopCountExpr) {
  3308. // Found 'collapse' clause - calculate collapse number.
  3309. llvm::APSInt Result;
  3310. if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  3311. NestedLoopCount = Result.getLimitedValue();
  3312. }
  3313. // This is helper routine for loop directives (e.g., 'for', 'simd',
  3314. // 'for simd', etc.).
  3315. SmallVector<LoopIterationSpace, 4> IterSpaces;
  3316. IterSpaces.resize(NestedLoopCount);
  3317. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  3318. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  3319. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  3320. NestedLoopCount, NestedLoopCountExpr,
  3321. VarsWithImplicitDSA, IterSpaces[Cnt]))
  3322. return 0;
  3323. // Move on to the next nested for loop, or to the loop body.
  3324. // OpenMP [2.8.1, simd construct, Restrictions]
  3325. // All loops associated with the construct must be perfectly nested; that
  3326. // is, there must be no intervening code nor any OpenMP directive between
  3327. // any two loops.
  3328. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  3329. }
  3330. Built.clear(/* size */ NestedLoopCount);
  3331. if (SemaRef.CurContext->isDependentContext())
  3332. return NestedLoopCount;
  3333. // An example of what is generated for the following code:
  3334. //
  3335. // #pragma omp simd collapse(2)
  3336. // for (i = 0; i < NI; ++i)
  3337. // for (j = J0; j < NJ; j+=2) {
  3338. // <loop body>
  3339. // }
  3340. //
  3341. // We generate the code below.
  3342. // Note: the loop body may be outlined in CodeGen.
  3343. // Note: some counters may be C++ classes, operator- is used to find number of
  3344. // iterations and operator+= to calculate counter value.
  3345. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  3346. // or i64 is currently supported).
  3347. //
  3348. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  3349. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  3350. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  3351. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  3352. // // similar updates for vars in clauses (e.g. 'linear')
  3353. // <loop body (using local i and j)>
  3354. // }
  3355. // i = NI; // assign final values of counters
  3356. // j = NJ;
  3357. //
  3358. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  3359. // the iteration counts of the collapsed for loops.
  3360. // Precondition tests if there is at least one iteration (all conditions are
  3361. // true).
  3362. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  3363. auto N0 = IterSpaces[0].NumIterations;
  3364. ExprResult LastIteration32 = WidenIterationCount(
  3365. 32 /* Bits */, SemaRef.PerformImplicitConversion(
  3366. N0->IgnoreImpCasts(), N0->getType(),
  3367. Sema::AA_Converting, /*AllowExplicit=*/true)
  3368. .get(),
  3369. SemaRef);
  3370. ExprResult LastIteration64 = WidenIterationCount(
  3371. 64 /* Bits */, SemaRef.PerformImplicitConversion(
  3372. N0->IgnoreImpCasts(), N0->getType(),
  3373. Sema::AA_Converting, /*AllowExplicit=*/true)
  3374. .get(),
  3375. SemaRef);
  3376. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  3377. return NestedLoopCount;
  3378. auto &C = SemaRef.Context;
  3379. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  3380. Scope *CurScope = DSA.getCurScope();
  3381. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  3382. if (PreCond.isUsable()) {
  3383. PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
  3384. PreCond.get(), IterSpaces[Cnt].PreCond);
  3385. }
  3386. auto N = IterSpaces[Cnt].NumIterations;
  3387. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  3388. if (LastIteration32.isUsable())
  3389. LastIteration32 = SemaRef.BuildBinOp(
  3390. CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
  3391. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3392. Sema::AA_Converting,
  3393. /*AllowExplicit=*/true)
  3394. .get());
  3395. if (LastIteration64.isUsable())
  3396. LastIteration64 = SemaRef.BuildBinOp(
  3397. CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
  3398. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3399. Sema::AA_Converting,
  3400. /*AllowExplicit=*/true)
  3401. .get());
  3402. }
  3403. // Choose either the 32-bit or 64-bit version.
  3404. ExprResult LastIteration = LastIteration64;
  3405. if (LastIteration32.isUsable() &&
  3406. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  3407. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  3408. FitsInto(
  3409. 32 /* Bits */,
  3410. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  3411. LastIteration64.get(), SemaRef)))
  3412. LastIteration = LastIteration32;
  3413. if (!LastIteration.isUsable())
  3414. return 0;
  3415. // Save the number of iterations.
  3416. ExprResult NumIterations = LastIteration;
  3417. {
  3418. LastIteration = SemaRef.BuildBinOp(
  3419. CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
  3420. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3421. if (!LastIteration.isUsable())
  3422. return 0;
  3423. }
  3424. // Calculate the last iteration number beforehand instead of doing this on
  3425. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  3426. llvm::APSInt Result;
  3427. bool IsConstant =
  3428. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  3429. ExprResult CalcLastIteration;
  3430. if (!IsConstant) {
  3431. SourceLocation SaveLoc;
  3432. VarDecl *SaveVar =
  3433. buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
  3434. ".omp.last.iteration");
  3435. ExprResult SaveRef = buildDeclRefExpr(
  3436. SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
  3437. CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
  3438. SaveRef.get(), LastIteration.get());
  3439. LastIteration = SaveRef;
  3440. // Prepare SaveRef + 1.
  3441. NumIterations = SemaRef.BuildBinOp(
  3442. CurScope, SaveLoc, BO_Add, SaveRef.get(),
  3443. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3444. if (!NumIterations.isUsable())
  3445. return 0;
  3446. }
  3447. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  3448. QualType VType = LastIteration.get()->getType();
  3449. // Build variables passed into runtime, nesessary for worksharing directives.
  3450. ExprResult LB, UB, IL, ST, EUB;
  3451. if (isOpenMPWorksharingDirective(DKind)) {
  3452. // Lower bound variable, initialized with zero.
  3453. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  3454. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  3455. SemaRef.AddInitializerToDecl(
  3456. LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3457. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3458. // Upper bound variable, initialized with last iteration number.
  3459. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  3460. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  3461. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  3462. /*DirectInit*/ false,
  3463. /*TypeMayContainAuto*/ false);
  3464. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  3465. // This will be used to implement clause 'lastprivate'.
  3466. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  3467. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  3468. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  3469. SemaRef.AddInitializerToDecl(
  3470. ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3471. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3472. // Stride variable returned by runtime (we initialize it to 1 by default).
  3473. VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
  3474. ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
  3475. SemaRef.AddInitializerToDecl(
  3476. STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  3477. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3478. // Build expression: UB = min(UB, LastIteration)
  3479. // It is nesessary for CodeGen of directives with static scheduling.
  3480. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  3481. UB.get(), LastIteration.get());
  3482. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  3483. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  3484. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  3485. CondOp.get());
  3486. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  3487. }
  3488. // Build the iteration variable and its initialization before loop.
  3489. ExprResult IV;
  3490. ExprResult Init;
  3491. {
  3492. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
  3493. IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
  3494. Expr *RHS = isOpenMPWorksharingDirective(DKind)
  3495. ? LB.get()
  3496. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  3497. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  3498. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  3499. }
  3500. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  3501. SourceLocation CondLoc;
  3502. ExprResult Cond =
  3503. isOpenMPWorksharingDirective(DKind)
  3504. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  3505. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  3506. NumIterations.get());
  3507. // Loop increment (IV = IV + 1)
  3508. SourceLocation IncLoc;
  3509. ExprResult Inc =
  3510. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  3511. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  3512. if (!Inc.isUsable())
  3513. return 0;
  3514. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  3515. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  3516. if (!Inc.isUsable())
  3517. return 0;
  3518. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  3519. // Used for directives with static scheduling.
  3520. ExprResult NextLB, NextUB;
  3521. if (isOpenMPWorksharingDirective(DKind)) {
  3522. // LB + ST
  3523. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  3524. if (!NextLB.isUsable())
  3525. return 0;
  3526. // LB = LB + ST
  3527. NextLB =
  3528. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  3529. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  3530. if (!NextLB.isUsable())
  3531. return 0;
  3532. // UB + ST
  3533. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  3534. if (!NextUB.isUsable())
  3535. return 0;
  3536. // UB = UB + ST
  3537. NextUB =
  3538. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  3539. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  3540. if (!NextUB.isUsable())
  3541. return 0;
  3542. }
  3543. // Build updates and final values of the loop counters.
  3544. bool HasErrors = false;
  3545. Built.Counters.resize(NestedLoopCount);
  3546. Built.Inits.resize(NestedLoopCount);
  3547. Built.Updates.resize(NestedLoopCount);
  3548. Built.Finals.resize(NestedLoopCount);
  3549. {
  3550. ExprResult Div;
  3551. // Go from inner nested loop to outer.
  3552. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  3553. LoopIterationSpace &IS = IterSpaces[Cnt];
  3554. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  3555. // Build: Iter = (IV / Div) % IS.NumIters
  3556. // where Div is product of previous iterations' IS.NumIters.
  3557. ExprResult Iter;
  3558. if (Div.isUsable()) {
  3559. Iter =
  3560. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  3561. } else {
  3562. Iter = IV;
  3563. assert((Cnt == (int)NestedLoopCount - 1) &&
  3564. "unusable div expected on first iteration only");
  3565. }
  3566. if (Cnt != 0 && Iter.isUsable())
  3567. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  3568. IS.NumIterations);
  3569. if (!Iter.isUsable()) {
  3570. HasErrors = true;
  3571. break;
  3572. }
  3573. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  3574. auto *CounterVar = buildDeclRefExpr(
  3575. SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
  3576. IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  3577. /*RefersToCapture=*/true);
  3578. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  3579. IS.CounterInit);
  3580. if (!Init.isUsable()) {
  3581. HasErrors = true;
  3582. break;
  3583. }
  3584. ExprResult Update =
  3585. BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  3586. IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
  3587. if (!Update.isUsable()) {
  3588. HasErrors = true;
  3589. break;
  3590. }
  3591. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  3592. ExprResult Final = BuildCounterUpdate(
  3593. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  3594. IS.NumIterations, IS.CounterStep, IS.Subtract);
  3595. if (!Final.isUsable()) {
  3596. HasErrors = true;
  3597. break;
  3598. }
  3599. // Build Div for the next iteration: Div <- Div * IS.NumIters
  3600. if (Cnt != 0) {
  3601. if (Div.isUnset())
  3602. Div = IS.NumIterations;
  3603. else
  3604. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  3605. IS.NumIterations);
  3606. // Add parentheses (for debugging purposes only).
  3607. if (Div.isUsable())
  3608. Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
  3609. if (!Div.isUsable()) {
  3610. HasErrors = true;
  3611. break;
  3612. }
  3613. }
  3614. if (!Update.isUsable() || !Final.isUsable()) {
  3615. HasErrors = true;
  3616. break;
  3617. }
  3618. // Save results
  3619. Built.Counters[Cnt] = IS.CounterVar;
  3620. Built.Inits[Cnt] = Init.get();
  3621. Built.Updates[Cnt] = Update.get();
  3622. Built.Finals[Cnt] = Final.get();
  3623. }
  3624. }
  3625. if (HasErrors)
  3626. return 0;
  3627. // Save results
  3628. Built.IterationVarRef = IV.get();
  3629. Built.LastIteration = LastIteration.get();
  3630. Built.NumIterations = NumIterations.get();
  3631. Built.CalcLastIteration =
  3632. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  3633. Built.PreCond = PreCond.get();
  3634. Built.Cond = Cond.get();
  3635. Built.Init = Init.get();
  3636. Built.Inc = Inc.get();
  3637. Built.LB = LB.get();
  3638. Built.UB = UB.get();
  3639. Built.IL = IL.get();
  3640. Built.ST = ST.get();
  3641. Built.EUB = EUB.get();
  3642. Built.NLB = NextLB.get();
  3643. Built.NUB = NextUB.get();
  3644. return NestedLoopCount;
  3645. }
  3646. static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  3647. auto &&CollapseFilter = [](const OMPClause *C) -> bool {
  3648. return C->getClauseKind() == OMPC_collapse;
  3649. };
  3650. OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
  3651. Clauses, std::move(CollapseFilter));
  3652. if (I)
  3653. return cast<OMPCollapseClause>(*I)->getNumForLoops();
  3654. return nullptr;
  3655. }
  3656. StmtResult Sema::ActOnOpenMPSimdDirective(
  3657. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3658. SourceLocation EndLoc,
  3659. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3660. OMPLoopDirective::HelperExprs B;
  3661. // In presence of clause 'collapse', it will define the nested loops number.
  3662. unsigned NestedLoopCount =
  3663. CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
  3664. *DSAStack, VarsWithImplicitDSA, B);
  3665. if (NestedLoopCount == 0)
  3666. return StmtError();
  3667. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3668. "omp simd loop exprs were not built");
  3669. if (!CurContext->isDependentContext()) {
  3670. // Finalize the clauses that need pre-built expressions for CodeGen.
  3671. for (auto C : Clauses) {
  3672. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3673. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3674. B.NumIterations, *this, CurScope))
  3675. return StmtError();
  3676. }
  3677. }
  3678. getCurFunction()->setHasBranchProtectedScope();
  3679. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3680. Clauses, AStmt, B);
  3681. }
  3682. StmtResult Sema::ActOnOpenMPForDirective(
  3683. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3684. SourceLocation EndLoc,
  3685. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3686. OMPLoopDirective::HelperExprs B;
  3687. // In presence of clause 'collapse', it will define the nested loops number.
  3688. unsigned NestedLoopCount =
  3689. CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
  3690. *DSAStack, VarsWithImplicitDSA, B);
  3691. if (NestedLoopCount == 0)
  3692. return StmtError();
  3693. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3694. "omp for loop exprs were not built");
  3695. getCurFunction()->setHasBranchProtectedScope();
  3696. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3697. Clauses, AStmt, B);
  3698. }
  3699. StmtResult Sema::ActOnOpenMPForSimdDirective(
  3700. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3701. SourceLocation EndLoc,
  3702. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3703. OMPLoopDirective::HelperExprs B;
  3704. // In presence of clause 'collapse', it will define the nested loops number.
  3705. unsigned NestedLoopCount =
  3706. CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
  3707. *this, *DSAStack, VarsWithImplicitDSA, B);
  3708. if (NestedLoopCount == 0)
  3709. return StmtError();
  3710. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3711. "omp for simd loop exprs were not built");
  3712. if (!CurContext->isDependentContext()) {
  3713. // Finalize the clauses that need pre-built expressions for CodeGen.
  3714. for (auto C : Clauses) {
  3715. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3716. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3717. B.NumIterations, *this, CurScope))
  3718. return StmtError();
  3719. }
  3720. }
  3721. getCurFunction()->setHasBranchProtectedScope();
  3722. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  3723. Clauses, AStmt, B);
  3724. }
  3725. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  3726. Stmt *AStmt,
  3727. SourceLocation StartLoc,
  3728. SourceLocation EndLoc) {
  3729. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3730. auto BaseStmt = AStmt;
  3731. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  3732. BaseStmt = CS->getCapturedStmt();
  3733. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  3734. auto S = C->children();
  3735. if (!S)
  3736. return StmtError();
  3737. // All associated statements must be '#pragma omp section' except for
  3738. // the first one.
  3739. for (Stmt *SectionStmt : ++S) {
  3740. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  3741. if (SectionStmt)
  3742. Diag(SectionStmt->getLocStart(),
  3743. diag::err_omp_sections_substmt_not_section);
  3744. return StmtError();
  3745. }
  3746. }
  3747. } else {
  3748. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  3749. return StmtError();
  3750. }
  3751. getCurFunction()->setHasBranchProtectedScope();
  3752. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  3753. AStmt);
  3754. }
  3755. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  3756. SourceLocation StartLoc,
  3757. SourceLocation EndLoc) {
  3758. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3759. getCurFunction()->setHasBranchProtectedScope();
  3760. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3761. }
  3762. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  3763. Stmt *AStmt,
  3764. SourceLocation StartLoc,
  3765. SourceLocation EndLoc) {
  3766. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3767. getCurFunction()->setHasBranchProtectedScope();
  3768. // OpenMP [2.7.3, single Construct, Restrictions]
  3769. // The copyprivate clause must not be used with the nowait clause.
  3770. OMPClause *Nowait = nullptr;
  3771. OMPClause *Copyprivate = nullptr;
  3772. for (auto *Clause : Clauses) {
  3773. if (Clause->getClauseKind() == OMPC_nowait)
  3774. Nowait = Clause;
  3775. else if (Clause->getClauseKind() == OMPC_copyprivate)
  3776. Copyprivate = Clause;
  3777. if (Copyprivate && Nowait) {
  3778. Diag(Copyprivate->getLocStart(),
  3779. diag::err_omp_single_copyprivate_with_nowait);
  3780. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  3781. return StmtError();
  3782. }
  3783. }
  3784. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3785. }
  3786. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  3787. SourceLocation StartLoc,
  3788. SourceLocation EndLoc) {
  3789. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3790. getCurFunction()->setHasBranchProtectedScope();
  3791. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3792. }
  3793. StmtResult
  3794. Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
  3795. Stmt *AStmt, SourceLocation StartLoc,
  3796. SourceLocation EndLoc) {
  3797. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3798. getCurFunction()->setHasBranchProtectedScope();
  3799. return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  3800. AStmt);
  3801. }
  3802. StmtResult Sema::ActOnOpenMPParallelForDirective(
  3803. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3804. SourceLocation EndLoc,
  3805. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3806. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3807. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3808. // 1.2.2 OpenMP Language Terminology
  3809. // Structured block - An executable statement with a single entry at the
  3810. // top and a single exit at the bottom.
  3811. // The point of exit cannot be a branch out of the structured block.
  3812. // longjmp() and throw() must not violate the entry/exit criteria.
  3813. CS->getCapturedDecl()->setNothrow();
  3814. OMPLoopDirective::HelperExprs B;
  3815. // In presence of clause 'collapse', it will define the nested loops number.
  3816. unsigned NestedLoopCount =
  3817. CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
  3818. *this, *DSAStack, VarsWithImplicitDSA, B);
  3819. if (NestedLoopCount == 0)
  3820. return StmtError();
  3821. assert((CurContext->isDependentContext() || B.builtAll()) &&
  3822. "omp parallel for loop exprs were not built");
  3823. getCurFunction()->setHasBranchProtectedScope();
  3824. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  3825. NestedLoopCount, Clauses, AStmt, B);
  3826. }
  3827. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  3828. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  3829. SourceLocation EndLoc,
  3830. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  3831. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3832. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3833. // 1.2.2 OpenMP Language Terminology
  3834. // Structured block - An executable statement with a single entry at the
  3835. // top and a single exit at the bottom.
  3836. // The point of exit cannot be a branch out of the structured block.
  3837. // longjmp() and throw() must not violate the entry/exit criteria.
  3838. CS->getCapturedDecl()->setNothrow();
  3839. OMPLoopDirective::HelperExprs B;
  3840. // In presence of clause 'collapse', it will define the nested loops number.
  3841. unsigned NestedLoopCount =
  3842. CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
  3843. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  3844. if (NestedLoopCount == 0)
  3845. return StmtError();
  3846. if (!CurContext->isDependentContext()) {
  3847. // Finalize the clauses that need pre-built expressions for CodeGen.
  3848. for (auto C : Clauses) {
  3849. if (auto LC = dyn_cast<OMPLinearClause>(C))
  3850. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  3851. B.NumIterations, *this, CurScope))
  3852. return StmtError();
  3853. }
  3854. }
  3855. getCurFunction()->setHasBranchProtectedScope();
  3856. return OMPParallelForSimdDirective::Create(
  3857. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  3858. }
  3859. StmtResult
  3860. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  3861. Stmt *AStmt, SourceLocation StartLoc,
  3862. SourceLocation EndLoc) {
  3863. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3864. auto BaseStmt = AStmt;
  3865. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  3866. BaseStmt = CS->getCapturedStmt();
  3867. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  3868. auto S = C->children();
  3869. if (!S)
  3870. return StmtError();
  3871. // All associated statements must be '#pragma omp section' except for
  3872. // the first one.
  3873. for (Stmt *SectionStmt : ++S) {
  3874. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  3875. if (SectionStmt)
  3876. Diag(SectionStmt->getLocStart(),
  3877. diag::err_omp_parallel_sections_substmt_not_section);
  3878. return StmtError();
  3879. }
  3880. }
  3881. } else {
  3882. Diag(AStmt->getLocStart(),
  3883. diag::err_omp_parallel_sections_not_compound_stmt);
  3884. return StmtError();
  3885. }
  3886. getCurFunction()->setHasBranchProtectedScope();
  3887. return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
  3888. Clauses, AStmt);
  3889. }
  3890. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  3891. Stmt *AStmt, SourceLocation StartLoc,
  3892. SourceLocation EndLoc) {
  3893. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3894. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3895. // 1.2.2 OpenMP Language Terminology
  3896. // Structured block - An executable statement with a single entry at the
  3897. // top and a single exit at the bottom.
  3898. // The point of exit cannot be a branch out of the structured block.
  3899. // longjmp() and throw() must not violate the entry/exit criteria.
  3900. CS->getCapturedDecl()->setNothrow();
  3901. getCurFunction()->setHasBranchProtectedScope();
  3902. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3903. }
  3904. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  3905. SourceLocation EndLoc) {
  3906. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  3907. }
  3908. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  3909. SourceLocation EndLoc) {
  3910. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  3911. }
  3912. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  3913. SourceLocation EndLoc) {
  3914. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  3915. }
  3916. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  3917. SourceLocation StartLoc,
  3918. SourceLocation EndLoc) {
  3919. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3920. getCurFunction()->setHasBranchProtectedScope();
  3921. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3922. }
  3923. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  3924. SourceLocation StartLoc,
  3925. SourceLocation EndLoc) {
  3926. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  3927. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  3928. }
  3929. StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
  3930. SourceLocation StartLoc,
  3931. SourceLocation EndLoc) {
  3932. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3933. getCurFunction()->setHasBranchProtectedScope();
  3934. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
  3935. }
  3936. namespace {
  3937. /// \brief Helper class for checking expression in 'omp atomic [update]'
  3938. /// construct.
  3939. class OpenMPAtomicUpdateChecker {
  3940. /// \brief Error results for atomic update expressions.
  3941. enum ExprAnalysisErrorCode {
  3942. /// \brief A statement is not an expression statement.
  3943. NotAnExpression,
  3944. /// \brief Expression is not builtin binary or unary operation.
  3945. NotABinaryOrUnaryExpression,
  3946. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  3947. NotAnUnaryIncDecExpression,
  3948. /// \brief An expression is not of scalar type.
  3949. NotAScalarType,
  3950. /// \brief A binary operation is not an assignment operation.
  3951. NotAnAssignmentOp,
  3952. /// \brief RHS part of the binary operation is not a binary expression.
  3953. NotABinaryExpression,
  3954. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  3955. /// expression.
  3956. NotABinaryOperator,
  3957. /// \brief RHS binary operation does not have reference to the updated LHS
  3958. /// part.
  3959. NotAnUpdateExpression,
  3960. /// \brief No errors is found.
  3961. NoError
  3962. };
  3963. /// \brief Reference to Sema.
  3964. Sema &SemaRef;
  3965. /// \brief A location for note diagnostics (when error is found).
  3966. SourceLocation NoteLoc;
  3967. /// \brief 'x' lvalue part of the source atomic expression.
  3968. Expr *X;
  3969. /// \brief 'expr' rvalue part of the source atomic expression.
  3970. Expr *E;
  3971. /// \brief Helper expression of the form
  3972. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  3973. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  3974. Expr *UpdateExpr;
  3975. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  3976. /// important for non-associative operations.
  3977. bool IsXLHSInRHSPart;
  3978. BinaryOperatorKind Op;
  3979. SourceLocation OpLoc;
  3980. /// \brief true if the source expression is a postfix unary operation, false
  3981. /// if it is a prefix unary operation.
  3982. bool IsPostfixUpdate;
  3983. public:
  3984. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  3985. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  3986. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  3987. /// \brief Check specified statement that it is suitable for 'atomic update'
  3988. /// constructs and extract 'x', 'expr' and Operation from the original
  3989. /// expression. If DiagId and NoteId == 0, then only check is performed
  3990. /// without error notification.
  3991. /// \param DiagId Diagnostic which should be emitted if error is found.
  3992. /// \param NoteId Diagnostic note for the main error message.
  3993. /// \return true if statement is not an update expression, false otherwise.
  3994. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  3995. /// \brief Return the 'x' lvalue part of the source atomic expression.
  3996. Expr *getX() const { return X; }
  3997. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  3998. Expr *getExpr() const { return E; }
  3999. /// \brief Return the update expression used in calculation of the updated
  4000. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4001. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4002. Expr *getUpdateExpr() const { return UpdateExpr; }
  4003. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  4004. /// false otherwise.
  4005. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  4006. /// \brief true if the source expression is a postfix unary operation, false
  4007. /// if it is a prefix unary operation.
  4008. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  4009. private:
  4010. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  4011. unsigned NoteId = 0);
  4012. };
  4013. } // namespace
  4014. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  4015. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  4016. ExprAnalysisErrorCode ErrorFound = NoError;
  4017. SourceLocation ErrorLoc, NoteLoc;
  4018. SourceRange ErrorRange, NoteRange;
  4019. // Allowed constructs are:
  4020. // x = x binop expr;
  4021. // x = expr binop x;
  4022. if (AtomicBinOp->getOpcode() == BO_Assign) {
  4023. X = AtomicBinOp->getLHS();
  4024. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  4025. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  4026. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  4027. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  4028. AtomicInnerBinOp->isBitwiseOp()) {
  4029. Op = AtomicInnerBinOp->getOpcode();
  4030. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  4031. auto *LHS = AtomicInnerBinOp->getLHS();
  4032. auto *RHS = AtomicInnerBinOp->getRHS();
  4033. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  4034. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  4035. /*Canonical=*/true);
  4036. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  4037. /*Canonical=*/true);
  4038. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  4039. /*Canonical=*/true);
  4040. if (XId == LHSId) {
  4041. E = RHS;
  4042. IsXLHSInRHSPart = true;
  4043. } else if (XId == RHSId) {
  4044. E = LHS;
  4045. IsXLHSInRHSPart = false;
  4046. } else {
  4047. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4048. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4049. NoteLoc = X->getExprLoc();
  4050. NoteRange = X->getSourceRange();
  4051. ErrorFound = NotAnUpdateExpression;
  4052. }
  4053. } else {
  4054. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4055. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4056. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  4057. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4058. ErrorFound = NotABinaryOperator;
  4059. }
  4060. } else {
  4061. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  4062. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  4063. ErrorFound = NotABinaryExpression;
  4064. }
  4065. } else {
  4066. ErrorLoc = AtomicBinOp->getExprLoc();
  4067. ErrorRange = AtomicBinOp->getSourceRange();
  4068. NoteLoc = AtomicBinOp->getOperatorLoc();
  4069. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4070. ErrorFound = NotAnAssignmentOp;
  4071. }
  4072. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4073. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4074. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4075. return true;
  4076. } else if (SemaRef.CurContext->isDependentContext())
  4077. E = X = UpdateExpr = nullptr;
  4078. return ErrorFound != NoError;
  4079. }
  4080. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  4081. unsigned NoteId) {
  4082. ExprAnalysisErrorCode ErrorFound = NoError;
  4083. SourceLocation ErrorLoc, NoteLoc;
  4084. SourceRange ErrorRange, NoteRange;
  4085. // Allowed constructs are:
  4086. // x++;
  4087. // x--;
  4088. // ++x;
  4089. // --x;
  4090. // x binop= expr;
  4091. // x = x binop expr;
  4092. // x = expr binop x;
  4093. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  4094. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  4095. if (AtomicBody->getType()->isScalarType() ||
  4096. AtomicBody->isInstantiationDependent()) {
  4097. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  4098. AtomicBody->IgnoreParenImpCasts())) {
  4099. // Check for Compound Assignment Operation
  4100. Op = BinaryOperator::getOpForCompoundAssignment(
  4101. AtomicCompAssignOp->getOpcode());
  4102. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  4103. E = AtomicCompAssignOp->getRHS();
  4104. X = AtomicCompAssignOp->getLHS();
  4105. IsXLHSInRHSPart = true;
  4106. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  4107. AtomicBody->IgnoreParenImpCasts())) {
  4108. // Check for Binary Operation
  4109. if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  4110. return true;
  4111. } else if (auto *AtomicUnaryOp =
  4112. dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
  4113. // Check for Unary Operation
  4114. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  4115. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  4116. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  4117. OpLoc = AtomicUnaryOp->getOperatorLoc();
  4118. X = AtomicUnaryOp->getSubExpr();
  4119. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  4120. IsXLHSInRHSPart = true;
  4121. } else {
  4122. ErrorFound = NotAnUnaryIncDecExpression;
  4123. ErrorLoc = AtomicUnaryOp->getExprLoc();
  4124. ErrorRange = AtomicUnaryOp->getSourceRange();
  4125. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  4126. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4127. }
  4128. } else {
  4129. ErrorFound = NotABinaryOrUnaryExpression;
  4130. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  4131. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  4132. }
  4133. } else {
  4134. ErrorFound = NotAScalarType;
  4135. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  4136. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4137. }
  4138. } else {
  4139. ErrorFound = NotAnExpression;
  4140. NoteLoc = ErrorLoc = S->getLocStart();
  4141. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4142. }
  4143. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4144. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4145. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4146. return true;
  4147. } else if (SemaRef.CurContext->isDependentContext())
  4148. E = X = UpdateExpr = nullptr;
  4149. if (ErrorFound == NoError && E && X) {
  4150. // Build an update expression of form 'OpaqueValueExpr(x) binop
  4151. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  4152. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  4153. auto *OVEX = new (SemaRef.getASTContext())
  4154. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  4155. auto *OVEExpr = new (SemaRef.getASTContext())
  4156. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  4157. auto Update =
  4158. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  4159. IsXLHSInRHSPart ? OVEExpr : OVEX);
  4160. if (Update.isInvalid())
  4161. return true;
  4162. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  4163. Sema::AA_Casting);
  4164. if (Update.isInvalid())
  4165. return true;
  4166. UpdateExpr = Update.get();
  4167. }
  4168. return ErrorFound != NoError;
  4169. }
  4170. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  4171. Stmt *AStmt,
  4172. SourceLocation StartLoc,
  4173. SourceLocation EndLoc) {
  4174. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4175. auto CS = cast<CapturedStmt>(AStmt);
  4176. // 1.2.2 OpenMP Language Terminology
  4177. // Structured block - An executable statement with a single entry at the
  4178. // top and a single exit at the bottom.
  4179. // The point of exit cannot be a branch out of the structured block.
  4180. // longjmp() and throw() must not violate the entry/exit criteria.
  4181. OpenMPClauseKind AtomicKind = OMPC_unknown;
  4182. SourceLocation AtomicKindLoc;
  4183. for (auto *C : Clauses) {
  4184. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  4185. C->getClauseKind() == OMPC_update ||
  4186. C->getClauseKind() == OMPC_capture) {
  4187. if (AtomicKind != OMPC_unknown) {
  4188. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  4189. << SourceRange(C->getLocStart(), C->getLocEnd());
  4190. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  4191. << getOpenMPClauseName(AtomicKind);
  4192. } else {
  4193. AtomicKind = C->getClauseKind();
  4194. AtomicKindLoc = C->getLocStart();
  4195. }
  4196. }
  4197. }
  4198. auto Body = CS->getCapturedStmt();
  4199. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  4200. Body = EWC->getSubExpr();
  4201. Expr *X = nullptr;
  4202. Expr *V = nullptr;
  4203. Expr *E = nullptr;
  4204. Expr *UE = nullptr;
  4205. bool IsXLHSInRHSPart = false;
  4206. bool IsPostfixUpdate = false;
  4207. // OpenMP [2.12.6, atomic Construct]
  4208. // In the next expressions:
  4209. // * x and v (as applicable) are both l-value expressions with scalar type.
  4210. // * During the execution of an atomic region, multiple syntactic
  4211. // occurrences of x must designate the same storage location.
  4212. // * Neither of v and expr (as applicable) may access the storage location
  4213. // designated by x.
  4214. // * Neither of x and expr (as applicable) may access the storage location
  4215. // designated by v.
  4216. // * expr is an expression with scalar type.
  4217. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  4218. // * binop, binop=, ++, and -- are not overloaded operators.
  4219. // * The expression x binop expr must be numerically equivalent to x binop
  4220. // (expr). This requirement is satisfied if the operators in expr have
  4221. // precedence greater than binop, or by using parentheses around expr or
  4222. // subexpressions of expr.
  4223. // * The expression expr binop x must be numerically equivalent to (expr)
  4224. // binop x. This requirement is satisfied if the operators in expr have
  4225. // precedence equal to or greater than binop, or by using parentheses around
  4226. // expr or subexpressions of expr.
  4227. // * For forms that allow multiple occurrences of x, the number of times
  4228. // that x is evaluated is unspecified.
  4229. if (AtomicKind == OMPC_read) {
  4230. enum {
  4231. NotAnExpression,
  4232. NotAnAssignmentOp,
  4233. NotAScalarType,
  4234. NotAnLValue,
  4235. NoError
  4236. } ErrorFound = NoError;
  4237. SourceLocation ErrorLoc, NoteLoc;
  4238. SourceRange ErrorRange, NoteRange;
  4239. // If clause is read:
  4240. // v = x;
  4241. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  4242. auto AtomicBinOp =
  4243. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4244. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4245. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4246. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  4247. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4248. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  4249. if (!X->isLValue() || !V->isLValue()) {
  4250. auto NotLValueExpr = X->isLValue() ? V : X;
  4251. ErrorFound = NotAnLValue;
  4252. ErrorLoc = AtomicBinOp->getExprLoc();
  4253. ErrorRange = AtomicBinOp->getSourceRange();
  4254. NoteLoc = NotLValueExpr->getExprLoc();
  4255. NoteRange = NotLValueExpr->getSourceRange();
  4256. }
  4257. } else if (!X->isInstantiationDependent() ||
  4258. !V->isInstantiationDependent()) {
  4259. auto NotScalarExpr =
  4260. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4261. ? V
  4262. : X;
  4263. ErrorFound = NotAScalarType;
  4264. ErrorLoc = AtomicBinOp->getExprLoc();
  4265. ErrorRange = AtomicBinOp->getSourceRange();
  4266. NoteLoc = NotScalarExpr->getExprLoc();
  4267. NoteRange = NotScalarExpr->getSourceRange();
  4268. }
  4269. } else {
  4270. ErrorFound = NotAnAssignmentOp;
  4271. ErrorLoc = AtomicBody->getExprLoc();
  4272. ErrorRange = AtomicBody->getSourceRange();
  4273. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4274. : AtomicBody->getExprLoc();
  4275. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4276. : AtomicBody->getSourceRange();
  4277. }
  4278. } else {
  4279. ErrorFound = NotAnExpression;
  4280. NoteLoc = ErrorLoc = Body->getLocStart();
  4281. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4282. }
  4283. if (ErrorFound != NoError) {
  4284. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  4285. << ErrorRange;
  4286. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4287. << NoteRange;
  4288. return StmtError();
  4289. } else if (CurContext->isDependentContext())
  4290. V = X = nullptr;
  4291. } else if (AtomicKind == OMPC_write) {
  4292. enum {
  4293. NotAnExpression,
  4294. NotAnAssignmentOp,
  4295. NotAScalarType,
  4296. NotAnLValue,
  4297. NoError
  4298. } ErrorFound = NoError;
  4299. SourceLocation ErrorLoc, NoteLoc;
  4300. SourceRange ErrorRange, NoteRange;
  4301. // If clause is write:
  4302. // x = expr;
  4303. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  4304. auto AtomicBinOp =
  4305. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4306. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4307. X = AtomicBinOp->getLHS();
  4308. E = AtomicBinOp->getRHS();
  4309. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4310. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  4311. if (!X->isLValue()) {
  4312. ErrorFound = NotAnLValue;
  4313. ErrorLoc = AtomicBinOp->getExprLoc();
  4314. ErrorRange = AtomicBinOp->getSourceRange();
  4315. NoteLoc = X->getExprLoc();
  4316. NoteRange = X->getSourceRange();
  4317. }
  4318. } else if (!X->isInstantiationDependent() ||
  4319. !E->isInstantiationDependent()) {
  4320. auto NotScalarExpr =
  4321. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4322. ? E
  4323. : X;
  4324. ErrorFound = NotAScalarType;
  4325. ErrorLoc = AtomicBinOp->getExprLoc();
  4326. ErrorRange = AtomicBinOp->getSourceRange();
  4327. NoteLoc = NotScalarExpr->getExprLoc();
  4328. NoteRange = NotScalarExpr->getSourceRange();
  4329. }
  4330. } else {
  4331. ErrorFound = NotAnAssignmentOp;
  4332. ErrorLoc = AtomicBody->getExprLoc();
  4333. ErrorRange = AtomicBody->getSourceRange();
  4334. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4335. : AtomicBody->getExprLoc();
  4336. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4337. : AtomicBody->getSourceRange();
  4338. }
  4339. } else {
  4340. ErrorFound = NotAnExpression;
  4341. NoteLoc = ErrorLoc = Body->getLocStart();
  4342. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4343. }
  4344. if (ErrorFound != NoError) {
  4345. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  4346. << ErrorRange;
  4347. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  4348. << NoteRange;
  4349. return StmtError();
  4350. } else if (CurContext->isDependentContext())
  4351. E = X = nullptr;
  4352. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  4353. // If clause is update:
  4354. // x++;
  4355. // x--;
  4356. // ++x;
  4357. // --x;
  4358. // x binop= expr;
  4359. // x = x binop expr;
  4360. // x = expr binop x;
  4361. OpenMPAtomicUpdateChecker Checker(*this);
  4362. if (Checker.checkStatement(
  4363. Body, (AtomicKind == OMPC_update)
  4364. ? diag::err_omp_atomic_update_not_expression_statement
  4365. : diag::err_omp_atomic_not_expression_statement,
  4366. diag::note_omp_atomic_update))
  4367. return StmtError();
  4368. if (!CurContext->isDependentContext()) {
  4369. E = Checker.getExpr();
  4370. X = Checker.getX();
  4371. UE = Checker.getUpdateExpr();
  4372. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4373. }
  4374. } else if (AtomicKind == OMPC_capture) {
  4375. enum {
  4376. NotAnAssignmentOp,
  4377. NotACompoundStatement,
  4378. NotTwoSubstatements,
  4379. NotASpecificExpression,
  4380. NoError
  4381. } ErrorFound = NoError;
  4382. SourceLocation ErrorLoc, NoteLoc;
  4383. SourceRange ErrorRange, NoteRange;
  4384. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  4385. // If clause is a capture:
  4386. // v = x++;
  4387. // v = x--;
  4388. // v = ++x;
  4389. // v = --x;
  4390. // v = x binop= expr;
  4391. // v = x = x binop expr;
  4392. // v = x = expr binop x;
  4393. auto *AtomicBinOp =
  4394. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4395. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4396. V = AtomicBinOp->getLHS();
  4397. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4398. OpenMPAtomicUpdateChecker Checker(*this);
  4399. if (Checker.checkStatement(
  4400. Body, diag::err_omp_atomic_capture_not_expression_statement,
  4401. diag::note_omp_atomic_update))
  4402. return StmtError();
  4403. E = Checker.getExpr();
  4404. X = Checker.getX();
  4405. UE = Checker.getUpdateExpr();
  4406. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4407. IsPostfixUpdate = Checker.isPostfixUpdate();
  4408. } else {
  4409. ErrorLoc = AtomicBody->getExprLoc();
  4410. ErrorRange = AtomicBody->getSourceRange();
  4411. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4412. : AtomicBody->getExprLoc();
  4413. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4414. : AtomicBody->getSourceRange();
  4415. ErrorFound = NotAnAssignmentOp;
  4416. }
  4417. if (ErrorFound != NoError) {
  4418. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  4419. << ErrorRange;
  4420. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  4421. return StmtError();
  4422. } else if (CurContext->isDependentContext()) {
  4423. UE = V = E = X = nullptr;
  4424. }
  4425. } else {
  4426. // If clause is a capture:
  4427. // { v = x; x = expr; }
  4428. // { v = x; x++; }
  4429. // { v = x; x--; }
  4430. // { v = x; ++x; }
  4431. // { v = x; --x; }
  4432. // { v = x; x binop= expr; }
  4433. // { v = x; x = x binop expr; }
  4434. // { v = x; x = expr binop x; }
  4435. // { x++; v = x; }
  4436. // { x--; v = x; }
  4437. // { ++x; v = x; }
  4438. // { --x; v = x; }
  4439. // { x binop= expr; v = x; }
  4440. // { x = x binop expr; v = x; }
  4441. // { x = expr binop x; v = x; }
  4442. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  4443. // Check that this is { expr1; expr2; }
  4444. if (CS->size() == 2) {
  4445. auto *First = CS->body_front();
  4446. auto *Second = CS->body_back();
  4447. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  4448. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  4449. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  4450. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  4451. // Need to find what subexpression is 'v' and what is 'x'.
  4452. OpenMPAtomicUpdateChecker Checker(*this);
  4453. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  4454. BinaryOperator *BinOp = nullptr;
  4455. if (IsUpdateExprFound) {
  4456. BinOp = dyn_cast<BinaryOperator>(First);
  4457. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  4458. }
  4459. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  4460. // { v = x; x++; }
  4461. // { v = x; x--; }
  4462. // { v = x; ++x; }
  4463. // { v = x; --x; }
  4464. // { v = x; x binop= expr; }
  4465. // { v = x; x = x binop expr; }
  4466. // { v = x; x = expr binop x; }
  4467. // Check that the first expression has form v = x.
  4468. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  4469. llvm::FoldingSetNodeID XId, PossibleXId;
  4470. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  4471. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  4472. IsUpdateExprFound = XId == PossibleXId;
  4473. if (IsUpdateExprFound) {
  4474. V = BinOp->getLHS();
  4475. X = Checker.getX();
  4476. E = Checker.getExpr();
  4477. UE = Checker.getUpdateExpr();
  4478. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4479. IsPostfixUpdate = true;
  4480. }
  4481. }
  4482. if (!IsUpdateExprFound) {
  4483. IsUpdateExprFound = !Checker.checkStatement(First);
  4484. BinOp = nullptr;
  4485. if (IsUpdateExprFound) {
  4486. BinOp = dyn_cast<BinaryOperator>(Second);
  4487. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  4488. }
  4489. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  4490. // { x++; v = x; }
  4491. // { x--; v = x; }
  4492. // { ++x; v = x; }
  4493. // { --x; v = x; }
  4494. // { x binop= expr; v = x; }
  4495. // { x = x binop expr; v = x; }
  4496. // { x = expr binop x; v = x; }
  4497. // Check that the second expression has form v = x.
  4498. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  4499. llvm::FoldingSetNodeID XId, PossibleXId;
  4500. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  4501. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  4502. IsUpdateExprFound = XId == PossibleXId;
  4503. if (IsUpdateExprFound) {
  4504. V = BinOp->getLHS();
  4505. X = Checker.getX();
  4506. E = Checker.getExpr();
  4507. UE = Checker.getUpdateExpr();
  4508. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  4509. IsPostfixUpdate = false;
  4510. }
  4511. }
  4512. }
  4513. if (!IsUpdateExprFound) {
  4514. // { v = x; x = expr; }
  4515. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  4516. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  4517. ErrorFound = NotAnAssignmentOp;
  4518. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  4519. : First->getLocStart();
  4520. NoteRange = ErrorRange = FirstBinOp
  4521. ? FirstBinOp->getSourceRange()
  4522. : SourceRange(ErrorLoc, ErrorLoc);
  4523. } else {
  4524. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  4525. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  4526. ErrorFound = NotAnAssignmentOp;
  4527. NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
  4528. : Second->getLocStart();
  4529. NoteRange = ErrorRange = SecondBinOp
  4530. ? SecondBinOp->getSourceRange()
  4531. : SourceRange(ErrorLoc, ErrorLoc);
  4532. } else {
  4533. auto *PossibleXRHSInFirst =
  4534. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  4535. auto *PossibleXLHSInSecond =
  4536. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  4537. llvm::FoldingSetNodeID X1Id, X2Id;
  4538. PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
  4539. PossibleXLHSInSecond->Profile(X2Id, Context,
  4540. /*Canonical=*/true);
  4541. IsUpdateExprFound = X1Id == X2Id;
  4542. if (IsUpdateExprFound) {
  4543. V = FirstBinOp->getLHS();
  4544. X = SecondBinOp->getLHS();
  4545. E = SecondBinOp->getRHS();
  4546. UE = nullptr;
  4547. IsXLHSInRHSPart = false;
  4548. IsPostfixUpdate = true;
  4549. } else {
  4550. ErrorFound = NotASpecificExpression;
  4551. ErrorLoc = FirstBinOp->getExprLoc();
  4552. ErrorRange = FirstBinOp->getSourceRange();
  4553. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  4554. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  4555. }
  4556. }
  4557. }
  4558. }
  4559. } else {
  4560. NoteLoc = ErrorLoc = Body->getLocStart();
  4561. NoteRange = ErrorRange =
  4562. SourceRange(Body->getLocStart(), Body->getLocStart());
  4563. ErrorFound = NotTwoSubstatements;
  4564. }
  4565. } else {
  4566. NoteLoc = ErrorLoc = Body->getLocStart();
  4567. NoteRange = ErrorRange =
  4568. SourceRange(Body->getLocStart(), Body->getLocStart());
  4569. ErrorFound = NotACompoundStatement;
  4570. }
  4571. if (ErrorFound != NoError) {
  4572. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  4573. << ErrorRange;
  4574. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  4575. return StmtError();
  4576. } else if (CurContext->isDependentContext()) {
  4577. UE = V = E = X = nullptr;
  4578. }
  4579. }
  4580. }
  4581. getCurFunction()->setHasBranchProtectedScope();
  4582. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4583. X, V, E, UE, IsXLHSInRHSPart,
  4584. IsPostfixUpdate);
  4585. }
  4586. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  4587. Stmt *AStmt,
  4588. SourceLocation StartLoc,
  4589. SourceLocation EndLoc) {
  4590. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4591. // OpenMP [2.16, Nesting of Regions]
  4592. // If specified, a teams construct must be contained within a target
  4593. // construct. That target construct must contain no statements or directives
  4594. // outside of the teams construct.
  4595. if (DSAStack->hasInnerTeamsRegion()) {
  4596. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  4597. bool OMPTeamsFound = true;
  4598. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  4599. auto I = CS->body_begin();
  4600. while (I != CS->body_end()) {
  4601. auto OED = dyn_cast<OMPExecutableDirective>(*I);
  4602. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  4603. OMPTeamsFound = false;
  4604. break;
  4605. }
  4606. ++I;
  4607. }
  4608. assert(I != CS->body_end() && "Not found statement");
  4609. S = *I;
  4610. }
  4611. if (!OMPTeamsFound) {
  4612. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  4613. Diag(DSAStack->getInnerTeamsRegionLoc(),
  4614. diag::note_omp_nested_teams_construct_here);
  4615. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  4616. << isa<OMPExecutableDirective>(S);
  4617. return StmtError();
  4618. }
  4619. }
  4620. getCurFunction()->setHasBranchProtectedScope();
  4621. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4622. }
  4623. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  4624. Stmt *AStmt, SourceLocation StartLoc,
  4625. SourceLocation EndLoc) {
  4626. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4627. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4628. // 1.2.2 OpenMP Language Terminology
  4629. // Structured block - An executable statement with a single entry at the
  4630. // top and a single exit at the bottom.
  4631. // The point of exit cannot be a branch out of the structured block.
  4632. // longjmp() and throw() must not violate the entry/exit criteria.
  4633. CS->getCapturedDecl()->setNothrow();
  4634. getCurFunction()->setHasBranchProtectedScope();
  4635. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4636. }
  4637. StmtResult
  4638. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  4639. SourceLocation EndLoc,
  4640. OpenMPDirectiveKind CancelRegion) {
  4641. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  4642. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  4643. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4644. << getOpenMPDirectiveName(CancelRegion);
  4645. return StmtError();
  4646. }
  4647. if (DSAStack->isParentNowaitRegion()) {
  4648. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  4649. return StmtError();
  4650. }
  4651. if (DSAStack->isParentOrderedRegion()) {
  4652. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  4653. return StmtError();
  4654. }
  4655. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  4656. CancelRegion);
  4657. }
  4658. StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
  4659. SourceLocation EndLoc,
  4660. OpenMPDirectiveKind CancelRegion) {
  4661. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  4662. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  4663. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4664. << getOpenMPDirectiveName(CancelRegion);
  4665. return StmtError();
  4666. }
  4667. if (DSAStack->isParentNowaitRegion()) {
  4668. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  4669. return StmtError();
  4670. }
  4671. if (DSAStack->isParentOrderedRegion()) {
  4672. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  4673. return StmtError();
  4674. }
  4675. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, CancelRegion);
  4676. }
  4677. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  4678. SourceLocation StartLoc,
  4679. SourceLocation LParenLoc,
  4680. SourceLocation EndLoc) {
  4681. OMPClause *Res = nullptr;
  4682. switch (Kind) {
  4683. case OMPC_if:
  4684. Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
  4685. break;
  4686. case OMPC_final:
  4687. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  4688. break;
  4689. case OMPC_num_threads:
  4690. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  4691. break;
  4692. case OMPC_safelen:
  4693. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  4694. break;
  4695. case OMPC_collapse:
  4696. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  4697. break;
  4698. case OMPC_default:
  4699. case OMPC_proc_bind:
  4700. case OMPC_schedule:
  4701. case OMPC_private:
  4702. case OMPC_firstprivate:
  4703. case OMPC_lastprivate:
  4704. case OMPC_shared:
  4705. case OMPC_reduction:
  4706. case OMPC_linear:
  4707. case OMPC_aligned:
  4708. case OMPC_copyin:
  4709. case OMPC_copyprivate:
  4710. case OMPC_ordered:
  4711. case OMPC_nowait:
  4712. case OMPC_untied:
  4713. case OMPC_mergeable:
  4714. case OMPC_threadprivate:
  4715. case OMPC_flush:
  4716. case OMPC_read:
  4717. case OMPC_write:
  4718. case OMPC_update:
  4719. case OMPC_capture:
  4720. case OMPC_seq_cst:
  4721. case OMPC_depend:
  4722. case OMPC_unknown:
  4723. llvm_unreachable("Clause is not allowed.");
  4724. }
  4725. return Res;
  4726. }
  4727. OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
  4728. SourceLocation LParenLoc,
  4729. SourceLocation EndLoc) {
  4730. Expr *ValExpr = Condition;
  4731. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  4732. !Condition->isInstantiationDependent() &&
  4733. !Condition->containsUnexpandedParameterPack()) {
  4734. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  4735. Condition->getExprLoc(), Condition);
  4736. if (Val.isInvalid())
  4737. return nullptr;
  4738. ValExpr = Val.get();
  4739. }
  4740. return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4741. }
  4742. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  4743. SourceLocation StartLoc,
  4744. SourceLocation LParenLoc,
  4745. SourceLocation EndLoc) {
  4746. Expr *ValExpr = Condition;
  4747. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  4748. !Condition->isInstantiationDependent() &&
  4749. !Condition->containsUnexpandedParameterPack()) {
  4750. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  4751. Condition->getExprLoc(), Condition);
  4752. if (Val.isInvalid())
  4753. return nullptr;
  4754. ValExpr = Val.get();
  4755. }
  4756. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4757. }
  4758. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  4759. Expr *Op) {
  4760. if (!Op)
  4761. return ExprError();
  4762. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  4763. public:
  4764. IntConvertDiagnoser()
  4765. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  4766. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  4767. QualType T) override {
  4768. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  4769. }
  4770. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  4771. QualType T) override {
  4772. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  4773. }
  4774. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  4775. QualType T,
  4776. QualType ConvTy) override {
  4777. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  4778. }
  4779. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  4780. QualType ConvTy) override {
  4781. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  4782. << ConvTy->isEnumeralType() << ConvTy;
  4783. }
  4784. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  4785. QualType T) override {
  4786. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  4787. }
  4788. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  4789. QualType ConvTy) override {
  4790. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  4791. << ConvTy->isEnumeralType() << ConvTy;
  4792. }
  4793. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  4794. QualType) override {
  4795. llvm_unreachable("conversion functions are permitted");
  4796. }
  4797. } ConvertDiagnoser;
  4798. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  4799. }
  4800. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  4801. SourceLocation StartLoc,
  4802. SourceLocation LParenLoc,
  4803. SourceLocation EndLoc) {
  4804. Expr *ValExpr = NumThreads;
  4805. if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
  4806. !NumThreads->containsUnexpandedParameterPack()) {
  4807. SourceLocation NumThreadsLoc = NumThreads->getLocStart();
  4808. ExprResult Val =
  4809. PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
  4810. if (Val.isInvalid())
  4811. return nullptr;
  4812. ValExpr = Val.get();
  4813. // OpenMP [2.5, Restrictions]
  4814. // The num_threads expression must evaluate to a positive integer value.
  4815. llvm::APSInt Result;
  4816. if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
  4817. !Result.isStrictlyPositive()) {
  4818. Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
  4819. << "num_threads" << NumThreads->getSourceRange();
  4820. return nullptr;
  4821. }
  4822. }
  4823. return new (Context)
  4824. OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  4825. }
  4826. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  4827. OpenMPClauseKind CKind) {
  4828. if (!E)
  4829. return ExprError();
  4830. if (E->isValueDependent() || E->isTypeDependent() ||
  4831. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4832. return E;
  4833. llvm::APSInt Result;
  4834. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  4835. if (ICE.isInvalid())
  4836. return ExprError();
  4837. if (!Result.isStrictlyPositive()) {
  4838. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  4839. << getOpenMPClauseName(CKind) << E->getSourceRange();
  4840. return ExprError();
  4841. }
  4842. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  4843. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  4844. << E->getSourceRange();
  4845. return ExprError();
  4846. }
  4847. if (CKind == OMPC_collapse) {
  4848. DSAStack->setCollapseNumber(Result.getExtValue());
  4849. }
  4850. return ICE;
  4851. }
  4852. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  4853. SourceLocation LParenLoc,
  4854. SourceLocation EndLoc) {
  4855. // OpenMP [2.8.1, simd construct, Description]
  4856. // The parameter of the safelen clause must be a constant
  4857. // positive integer expression.
  4858. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  4859. if (Safelen.isInvalid())
  4860. return nullptr;
  4861. return new (Context)
  4862. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  4863. }
  4864. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  4865. SourceLocation StartLoc,
  4866. SourceLocation LParenLoc,
  4867. SourceLocation EndLoc) {
  4868. // OpenMP [2.7.1, loop construct, Description]
  4869. // OpenMP [2.8.1, simd construct, Description]
  4870. // OpenMP [2.9.6, distribute construct, Description]
  4871. // The parameter of the collapse clause must be a constant
  4872. // positive integer expression.
  4873. ExprResult NumForLoopsResult =
  4874. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  4875. if (NumForLoopsResult.isInvalid())
  4876. return nullptr;
  4877. return new (Context)
  4878. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  4879. }
  4880. OMPClause *Sema::ActOnOpenMPSimpleClause(
  4881. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  4882. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  4883. OMPClause *Res = nullptr;
  4884. switch (Kind) {
  4885. case OMPC_default:
  4886. Res =
  4887. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  4888. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  4889. break;
  4890. case OMPC_proc_bind:
  4891. Res = ActOnOpenMPProcBindClause(
  4892. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  4893. LParenLoc, EndLoc);
  4894. break;
  4895. case OMPC_if:
  4896. case OMPC_final:
  4897. case OMPC_num_threads:
  4898. case OMPC_safelen:
  4899. case OMPC_collapse:
  4900. case OMPC_schedule:
  4901. case OMPC_private:
  4902. case OMPC_firstprivate:
  4903. case OMPC_lastprivate:
  4904. case OMPC_shared:
  4905. case OMPC_reduction:
  4906. case OMPC_linear:
  4907. case OMPC_aligned:
  4908. case OMPC_copyin:
  4909. case OMPC_copyprivate:
  4910. case OMPC_ordered:
  4911. case OMPC_nowait:
  4912. case OMPC_untied:
  4913. case OMPC_mergeable:
  4914. case OMPC_threadprivate:
  4915. case OMPC_flush:
  4916. case OMPC_read:
  4917. case OMPC_write:
  4918. case OMPC_update:
  4919. case OMPC_capture:
  4920. case OMPC_seq_cst:
  4921. case OMPC_depend:
  4922. case OMPC_unknown:
  4923. llvm_unreachable("Clause is not allowed.");
  4924. }
  4925. return Res;
  4926. }
  4927. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  4928. SourceLocation KindKwLoc,
  4929. SourceLocation StartLoc,
  4930. SourceLocation LParenLoc,
  4931. SourceLocation EndLoc) {
  4932. if (Kind == OMPC_DEFAULT_unknown) {
  4933. std::string Values;
  4934. static_assert(OMPC_DEFAULT_unknown > 0,
  4935. "OMPC_DEFAULT_unknown not greater than 0");
  4936. std::string Sep(", ");
  4937. for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
  4938. Values += "'";
  4939. Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
  4940. Values += "'";
  4941. switch (i) {
  4942. case OMPC_DEFAULT_unknown - 2:
  4943. Values += " or ";
  4944. break;
  4945. case OMPC_DEFAULT_unknown - 1:
  4946. break;
  4947. default:
  4948. Values += Sep;
  4949. break;
  4950. }
  4951. }
  4952. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  4953. << Values << getOpenMPClauseName(OMPC_default);
  4954. return nullptr;
  4955. }
  4956. switch (Kind) {
  4957. case OMPC_DEFAULT_none:
  4958. DSAStack->setDefaultDSANone(KindKwLoc);
  4959. break;
  4960. case OMPC_DEFAULT_shared:
  4961. DSAStack->setDefaultDSAShared(KindKwLoc);
  4962. break;
  4963. case OMPC_DEFAULT_unknown:
  4964. llvm_unreachable("Clause kind is not allowed.");
  4965. break;
  4966. }
  4967. return new (Context)
  4968. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  4969. }
  4970. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  4971. SourceLocation KindKwLoc,
  4972. SourceLocation StartLoc,
  4973. SourceLocation LParenLoc,
  4974. SourceLocation EndLoc) {
  4975. if (Kind == OMPC_PROC_BIND_unknown) {
  4976. std::string Values;
  4977. std::string Sep(", ");
  4978. for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
  4979. Values += "'";
  4980. Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
  4981. Values += "'";
  4982. switch (i) {
  4983. case OMPC_PROC_BIND_unknown - 2:
  4984. Values += " or ";
  4985. break;
  4986. case OMPC_PROC_BIND_unknown - 1:
  4987. break;
  4988. default:
  4989. Values += Sep;
  4990. break;
  4991. }
  4992. }
  4993. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  4994. << Values << getOpenMPClauseName(OMPC_proc_bind);
  4995. return nullptr;
  4996. }
  4997. return new (Context)
  4998. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  4999. }
  5000. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  5001. OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
  5002. SourceLocation StartLoc, SourceLocation LParenLoc,
  5003. SourceLocation ArgumentLoc, SourceLocation CommaLoc,
  5004. SourceLocation EndLoc) {
  5005. OMPClause *Res = nullptr;
  5006. switch (Kind) {
  5007. case OMPC_schedule:
  5008. Res = ActOnOpenMPScheduleClause(
  5009. static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
  5010. LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
  5011. break;
  5012. case OMPC_if:
  5013. case OMPC_final:
  5014. case OMPC_num_threads:
  5015. case OMPC_safelen:
  5016. case OMPC_collapse:
  5017. case OMPC_default:
  5018. case OMPC_proc_bind:
  5019. case OMPC_private:
  5020. case OMPC_firstprivate:
  5021. case OMPC_lastprivate:
  5022. case OMPC_shared:
  5023. case OMPC_reduction:
  5024. case OMPC_linear:
  5025. case OMPC_aligned:
  5026. case OMPC_copyin:
  5027. case OMPC_copyprivate:
  5028. case OMPC_ordered:
  5029. case OMPC_nowait:
  5030. case OMPC_untied:
  5031. case OMPC_mergeable:
  5032. case OMPC_threadprivate:
  5033. case OMPC_flush:
  5034. case OMPC_read:
  5035. case OMPC_write:
  5036. case OMPC_update:
  5037. case OMPC_capture:
  5038. case OMPC_seq_cst:
  5039. case OMPC_depend:
  5040. case OMPC_unknown:
  5041. llvm_unreachable("Clause is not allowed.");
  5042. }
  5043. return Res;
  5044. }
  5045. OMPClause *Sema::ActOnOpenMPScheduleClause(
  5046. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  5047. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  5048. SourceLocation EndLoc) {
  5049. if (Kind == OMPC_SCHEDULE_unknown) {
  5050. std::string Values;
  5051. std::string Sep(", ");
  5052. for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
  5053. Values += "'";
  5054. Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
  5055. Values += "'";
  5056. switch (i) {
  5057. case OMPC_SCHEDULE_unknown - 2:
  5058. Values += " or ";
  5059. break;
  5060. case OMPC_SCHEDULE_unknown - 1:
  5061. break;
  5062. default:
  5063. Values += Sep;
  5064. break;
  5065. }
  5066. }
  5067. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  5068. << Values << getOpenMPClauseName(OMPC_schedule);
  5069. return nullptr;
  5070. }
  5071. Expr *ValExpr = ChunkSize;
  5072. Expr *HelperValExpr = nullptr;
  5073. if (ChunkSize) {
  5074. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  5075. !ChunkSize->isInstantiationDependent() &&
  5076. !ChunkSize->containsUnexpandedParameterPack()) {
  5077. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  5078. ExprResult Val =
  5079. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  5080. if (Val.isInvalid())
  5081. return nullptr;
  5082. ValExpr = Val.get();
  5083. // OpenMP [2.7.1, Restrictions]
  5084. // chunk_size must be a loop invariant integer expression with a positive
  5085. // value.
  5086. llvm::APSInt Result;
  5087. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  5088. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  5089. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  5090. << "schedule" << ChunkSize->getSourceRange();
  5091. return nullptr;
  5092. }
  5093. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  5094. auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
  5095. ChunkSize->getType(), ".chunk.");
  5096. auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
  5097. ChunkSize->getExprLoc(),
  5098. /*RefersToCapture=*/true);
  5099. HelperValExpr = ImpVarRef;
  5100. }
  5101. }
  5102. }
  5103. return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
  5104. EndLoc, Kind, ValExpr, HelperValExpr);
  5105. }
  5106. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  5107. SourceLocation StartLoc,
  5108. SourceLocation EndLoc) {
  5109. OMPClause *Res = nullptr;
  5110. switch (Kind) {
  5111. case OMPC_ordered:
  5112. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  5113. break;
  5114. case OMPC_nowait:
  5115. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  5116. break;
  5117. case OMPC_untied:
  5118. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  5119. break;
  5120. case OMPC_mergeable:
  5121. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  5122. break;
  5123. case OMPC_read:
  5124. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  5125. break;
  5126. case OMPC_write:
  5127. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  5128. break;
  5129. case OMPC_update:
  5130. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  5131. break;
  5132. case OMPC_capture:
  5133. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  5134. break;
  5135. case OMPC_seq_cst:
  5136. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  5137. break;
  5138. case OMPC_if:
  5139. case OMPC_final:
  5140. case OMPC_num_threads:
  5141. case OMPC_safelen:
  5142. case OMPC_collapse:
  5143. case OMPC_schedule:
  5144. case OMPC_private:
  5145. case OMPC_firstprivate:
  5146. case OMPC_lastprivate:
  5147. case OMPC_shared:
  5148. case OMPC_reduction:
  5149. case OMPC_linear:
  5150. case OMPC_aligned:
  5151. case OMPC_copyin:
  5152. case OMPC_copyprivate:
  5153. case OMPC_default:
  5154. case OMPC_proc_bind:
  5155. case OMPC_threadprivate:
  5156. case OMPC_flush:
  5157. case OMPC_depend:
  5158. case OMPC_unknown:
  5159. llvm_unreachable("Clause is not allowed.");
  5160. }
  5161. return Res;
  5162. }
  5163. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  5164. SourceLocation EndLoc) {
  5165. DSAStack->setOrderedRegion();
  5166. return new (Context) OMPOrderedClause(StartLoc, EndLoc);
  5167. }
  5168. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  5169. SourceLocation EndLoc) {
  5170. DSAStack->setNowaitRegion();
  5171. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  5172. }
  5173. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  5174. SourceLocation EndLoc) {
  5175. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  5176. }
  5177. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  5178. SourceLocation EndLoc) {
  5179. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  5180. }
  5181. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  5182. SourceLocation EndLoc) {
  5183. return new (Context) OMPReadClause(StartLoc, EndLoc);
  5184. }
  5185. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  5186. SourceLocation EndLoc) {
  5187. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  5188. }
  5189. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  5190. SourceLocation EndLoc) {
  5191. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  5192. }
  5193. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  5194. SourceLocation EndLoc) {
  5195. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  5196. }
  5197. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  5198. SourceLocation EndLoc) {
  5199. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  5200. }
  5201. OMPClause *Sema::ActOnOpenMPVarListClause(
  5202. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  5203. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  5204. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  5205. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  5206. SourceLocation DepLoc) {
  5207. OMPClause *Res = nullptr;
  5208. switch (Kind) {
  5209. case OMPC_private:
  5210. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5211. break;
  5212. case OMPC_firstprivate:
  5213. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5214. break;
  5215. case OMPC_lastprivate:
  5216. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5217. break;
  5218. case OMPC_shared:
  5219. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  5220. break;
  5221. case OMPC_reduction:
  5222. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  5223. EndLoc, ReductionIdScopeSpec, ReductionId);
  5224. break;
  5225. case OMPC_linear:
  5226. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  5227. ColonLoc, EndLoc);
  5228. break;
  5229. case OMPC_aligned:
  5230. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  5231. ColonLoc, EndLoc);
  5232. break;
  5233. case OMPC_copyin:
  5234. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  5235. break;
  5236. case OMPC_copyprivate:
  5237. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  5238. break;
  5239. case OMPC_flush:
  5240. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  5241. break;
  5242. case OMPC_depend:
  5243. Res = ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList, StartLoc,
  5244. LParenLoc, EndLoc);
  5245. break;
  5246. case OMPC_if:
  5247. case OMPC_final:
  5248. case OMPC_num_threads:
  5249. case OMPC_safelen:
  5250. case OMPC_collapse:
  5251. case OMPC_default:
  5252. case OMPC_proc_bind:
  5253. case OMPC_schedule:
  5254. case OMPC_ordered:
  5255. case OMPC_nowait:
  5256. case OMPC_untied:
  5257. case OMPC_mergeable:
  5258. case OMPC_threadprivate:
  5259. case OMPC_read:
  5260. case OMPC_write:
  5261. case OMPC_update:
  5262. case OMPC_capture:
  5263. case OMPC_seq_cst:
  5264. case OMPC_unknown:
  5265. llvm_unreachable("Clause is not allowed.");
  5266. }
  5267. return Res;
  5268. }
  5269. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  5270. SourceLocation StartLoc,
  5271. SourceLocation LParenLoc,
  5272. SourceLocation EndLoc) {
  5273. SmallVector<Expr *, 8> Vars;
  5274. SmallVector<Expr *, 8> PrivateCopies;
  5275. for (auto &RefExpr : VarList) {
  5276. assert(RefExpr && "NULL expr in OpenMP private clause.");
  5277. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5278. // It will be analyzed later.
  5279. Vars.push_back(RefExpr);
  5280. PrivateCopies.push_back(nullptr);
  5281. continue;
  5282. }
  5283. SourceLocation ELoc = RefExpr->getExprLoc();
  5284. // OpenMP [2.1, C/C++]
  5285. // A list item is a variable name.
  5286. // OpenMP [2.9.3.3, Restrictions, p.1]
  5287. // A variable that is part of another variable (as an array or
  5288. // structure element) cannot appear in a private clause.
  5289. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5290. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5291. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5292. continue;
  5293. }
  5294. Decl *D = DE->getDecl();
  5295. VarDecl *VD = cast<VarDecl>(D);
  5296. QualType Type = VD->getType();
  5297. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5298. // It will be analyzed later.
  5299. Vars.push_back(DE);
  5300. PrivateCopies.push_back(nullptr);
  5301. continue;
  5302. }
  5303. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5304. // A variable that appears in a private clause must not have an incomplete
  5305. // type or a reference type.
  5306. if (RequireCompleteType(ELoc, Type,
  5307. diag::err_omp_private_incomplete_type)) {
  5308. continue;
  5309. }
  5310. if (Type->isReferenceType()) {
  5311. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5312. << getOpenMPClauseName(OMPC_private) << Type;
  5313. bool IsDecl =
  5314. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5315. Diag(VD->getLocation(),
  5316. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5317. << VD;
  5318. continue;
  5319. }
  5320. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5321. // in a Construct]
  5322. // Variables with the predetermined data-sharing attributes may not be
  5323. // listed in data-sharing attributes clauses, except for the cases
  5324. // listed below. For these exceptions only, listing a predetermined
  5325. // variable in a data-sharing attribute clause is allowed and overrides
  5326. // the variable's predetermined data-sharing attributes.
  5327. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5328. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  5329. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  5330. << getOpenMPClauseName(OMPC_private);
  5331. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5332. continue;
  5333. }
  5334. // Variably modified types are not supported for tasks.
  5335. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  5336. DSAStack->getCurrentDirective() == OMPD_task) {
  5337. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  5338. << getOpenMPClauseName(OMPC_private) << Type
  5339. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  5340. bool IsDecl =
  5341. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5342. Diag(VD->getLocation(),
  5343. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5344. << VD;
  5345. continue;
  5346. }
  5347. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  5348. // A variable of class type (or array thereof) that appears in a private
  5349. // clause requires an accessible, unambiguous default constructor for the
  5350. // class type.
  5351. // Generate helper private variable and initialize it with the default
  5352. // value. The address of the original variable is replaced by the address of
  5353. // the new private variable in CodeGen. This new variable is not added to
  5354. // IdResolver, so the code in the OpenMP region uses original variable for
  5355. // proper diagnostics.
  5356. Type = Type.getUnqualifiedType();
  5357. auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
  5358. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  5359. if (VDPrivate->isInvalidDecl())
  5360. continue;
  5361. auto VDPrivateRefExpr = buildDeclRefExpr(
  5362. *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  5363. DSAStack->addDSA(VD, DE, OMPC_private);
  5364. Vars.push_back(DE);
  5365. PrivateCopies.push_back(VDPrivateRefExpr);
  5366. }
  5367. if (Vars.empty())
  5368. return nullptr;
  5369. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  5370. PrivateCopies);
  5371. }
  5372. namespace {
  5373. class DiagsUninitializedSeveretyRAII {
  5374. private:
  5375. DiagnosticsEngine &Diags;
  5376. SourceLocation SavedLoc;
  5377. bool IsIgnored;
  5378. public:
  5379. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  5380. bool IsIgnored)
  5381. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  5382. if (!IsIgnored) {
  5383. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  5384. /*Map*/ diag::Severity::Ignored, Loc);
  5385. }
  5386. }
  5387. ~DiagsUninitializedSeveretyRAII() {
  5388. if (!IsIgnored)
  5389. Diags.popMappings(SavedLoc);
  5390. }
  5391. };
  5392. }
  5393. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  5394. SourceLocation StartLoc,
  5395. SourceLocation LParenLoc,
  5396. SourceLocation EndLoc) {
  5397. SmallVector<Expr *, 8> Vars;
  5398. SmallVector<Expr *, 8> PrivateCopies;
  5399. SmallVector<Expr *, 8> Inits;
  5400. bool IsImplicitClause =
  5401. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  5402. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  5403. for (auto &RefExpr : VarList) {
  5404. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  5405. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5406. // It will be analyzed later.
  5407. Vars.push_back(RefExpr);
  5408. PrivateCopies.push_back(nullptr);
  5409. Inits.push_back(nullptr);
  5410. continue;
  5411. }
  5412. SourceLocation ELoc =
  5413. IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
  5414. // OpenMP [2.1, C/C++]
  5415. // A list item is a variable name.
  5416. // OpenMP [2.9.3.3, Restrictions, p.1]
  5417. // A variable that is part of another variable (as an array or
  5418. // structure element) cannot appear in a private clause.
  5419. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5420. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5421. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5422. continue;
  5423. }
  5424. Decl *D = DE->getDecl();
  5425. VarDecl *VD = cast<VarDecl>(D);
  5426. QualType Type = VD->getType();
  5427. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5428. // It will be analyzed later.
  5429. Vars.push_back(DE);
  5430. PrivateCopies.push_back(nullptr);
  5431. Inits.push_back(nullptr);
  5432. continue;
  5433. }
  5434. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5435. // A variable that appears in a private clause must not have an incomplete
  5436. // type or a reference type.
  5437. if (RequireCompleteType(ELoc, Type,
  5438. diag::err_omp_firstprivate_incomplete_type)) {
  5439. continue;
  5440. }
  5441. if (Type->isReferenceType()) {
  5442. if (IsImplicitClause) {
  5443. Diag(ImplicitClauseLoc,
  5444. diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
  5445. << Type;
  5446. Diag(RefExpr->getExprLoc(), diag::note_used_here);
  5447. } else {
  5448. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5449. << getOpenMPClauseName(OMPC_firstprivate) << Type;
  5450. }
  5451. bool IsDecl =
  5452. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5453. Diag(VD->getLocation(),
  5454. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5455. << VD;
  5456. continue;
  5457. }
  5458. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  5459. // A variable of class type (or array thereof) that appears in a private
  5460. // clause requires an accessible, unambiguous copy constructor for the
  5461. // class type.
  5462. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  5463. // If an implicit firstprivate variable found it was checked already.
  5464. if (!IsImplicitClause) {
  5465. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5466. bool IsConstant = ElemType.isConstant(Context);
  5467. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  5468. // A list item that specifies a given variable may not appear in more
  5469. // than one clause on the same directive, except that a variable may be
  5470. // specified in both firstprivate and lastprivate clauses.
  5471. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  5472. DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
  5473. Diag(ELoc, diag::err_omp_wrong_dsa)
  5474. << getOpenMPClauseName(DVar.CKind)
  5475. << getOpenMPClauseName(OMPC_firstprivate);
  5476. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5477. continue;
  5478. }
  5479. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5480. // in a Construct]
  5481. // Variables with the predetermined data-sharing attributes may not be
  5482. // listed in data-sharing attributes clauses, except for the cases
  5483. // listed below. For these exceptions only, listing a predetermined
  5484. // variable in a data-sharing attribute clause is allowed and overrides
  5485. // the variable's predetermined data-sharing attributes.
  5486. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5487. // in a Construct, C/C++, p.2]
  5488. // Variables with const-qualified type having no mutable member may be
  5489. // listed in a firstprivate clause, even if they are static data members.
  5490. if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
  5491. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  5492. Diag(ELoc, diag::err_omp_wrong_dsa)
  5493. << getOpenMPClauseName(DVar.CKind)
  5494. << getOpenMPClauseName(OMPC_firstprivate);
  5495. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5496. continue;
  5497. }
  5498. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  5499. // OpenMP [2.9.3.4, Restrictions, p.2]
  5500. // A list item that is private within a parallel region must not appear
  5501. // in a firstprivate clause on a worksharing construct if any of the
  5502. // worksharing regions arising from the worksharing construct ever bind
  5503. // to any of the parallel regions arising from the parallel construct.
  5504. if (isOpenMPWorksharingDirective(CurrDir) &&
  5505. !isOpenMPParallelDirective(CurrDir)) {
  5506. DVar = DSAStack->getImplicitDSA(VD, true);
  5507. if (DVar.CKind != OMPC_shared &&
  5508. (isOpenMPParallelDirective(DVar.DKind) ||
  5509. DVar.DKind == OMPD_unknown)) {
  5510. Diag(ELoc, diag::err_omp_required_access)
  5511. << getOpenMPClauseName(OMPC_firstprivate)
  5512. << getOpenMPClauseName(OMPC_shared);
  5513. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5514. continue;
  5515. }
  5516. }
  5517. // OpenMP [2.9.3.4, Restrictions, p.3]
  5518. // A list item that appears in a reduction clause of a parallel construct
  5519. // must not appear in a firstprivate clause on a worksharing or task
  5520. // construct if any of the worksharing or task regions arising from the
  5521. // worksharing or task construct ever bind to any of the parallel regions
  5522. // arising from the parallel construct.
  5523. // OpenMP [2.9.3.4, Restrictions, p.4]
  5524. // A list item that appears in a reduction clause in worksharing
  5525. // construct must not appear in a firstprivate clause in a task construct
  5526. // encountered during execution of any of the worksharing regions arising
  5527. // from the worksharing construct.
  5528. if (CurrDir == OMPD_task) {
  5529. DVar =
  5530. DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  5531. [](OpenMPDirectiveKind K) -> bool {
  5532. return isOpenMPParallelDirective(K) ||
  5533. isOpenMPWorksharingDirective(K);
  5534. },
  5535. false);
  5536. if (DVar.CKind == OMPC_reduction &&
  5537. (isOpenMPParallelDirective(DVar.DKind) ||
  5538. isOpenMPWorksharingDirective(DVar.DKind))) {
  5539. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  5540. << getOpenMPDirectiveName(DVar.DKind);
  5541. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5542. continue;
  5543. }
  5544. }
  5545. }
  5546. // Variably modified types are not supported for tasks.
  5547. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  5548. DSAStack->getCurrentDirective() == OMPD_task) {
  5549. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  5550. << getOpenMPClauseName(OMPC_firstprivate) << Type
  5551. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  5552. bool IsDecl =
  5553. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5554. Diag(VD->getLocation(),
  5555. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5556. << VD;
  5557. continue;
  5558. }
  5559. Type = Type.getUnqualifiedType();
  5560. auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
  5561. // Generate helper private variable and initialize it with the value of the
  5562. // original variable. The address of the original variable is replaced by
  5563. // the address of the new private variable in the CodeGen. This new variable
  5564. // is not added to IdResolver, so the code in the OpenMP region uses
  5565. // original variable for proper diagnostics and variable capturing.
  5566. Expr *VDInitRefExpr = nullptr;
  5567. // For arrays generate initializer for single element and replace it by the
  5568. // original array element in CodeGen.
  5569. if (Type->isArrayType()) {
  5570. auto VDInit =
  5571. buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
  5572. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  5573. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  5574. ElemType = ElemType.getUnqualifiedType();
  5575. auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
  5576. ".firstprivate.temp");
  5577. InitializedEntity Entity =
  5578. InitializedEntity::InitializeVariable(VDInitTemp);
  5579. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  5580. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  5581. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  5582. if (Result.isInvalid())
  5583. VDPrivate->setInvalidDecl();
  5584. else
  5585. VDPrivate->setInit(Result.getAs<Expr>());
  5586. } else {
  5587. auto *VDInit =
  5588. buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
  5589. VDInitRefExpr =
  5590. buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
  5591. AddInitializerToDecl(VDPrivate,
  5592. DefaultLvalueConversion(VDInitRefExpr).get(),
  5593. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  5594. }
  5595. if (VDPrivate->isInvalidDecl()) {
  5596. if (IsImplicitClause) {
  5597. Diag(DE->getExprLoc(),
  5598. diag::note_omp_task_predetermined_firstprivate_here);
  5599. }
  5600. continue;
  5601. }
  5602. CurContext->addDecl(VDPrivate);
  5603. auto VDPrivateRefExpr = buildDeclRefExpr(
  5604. *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  5605. DSAStack->addDSA(VD, DE, OMPC_firstprivate);
  5606. Vars.push_back(DE);
  5607. PrivateCopies.push_back(VDPrivateRefExpr);
  5608. Inits.push_back(VDInitRefExpr);
  5609. }
  5610. if (Vars.empty())
  5611. return nullptr;
  5612. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  5613. Vars, PrivateCopies, Inits);
  5614. }
  5615. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  5616. SourceLocation StartLoc,
  5617. SourceLocation LParenLoc,
  5618. SourceLocation EndLoc) {
  5619. SmallVector<Expr *, 8> Vars;
  5620. SmallVector<Expr *, 8> SrcExprs;
  5621. SmallVector<Expr *, 8> DstExprs;
  5622. SmallVector<Expr *, 8> AssignmentOps;
  5623. for (auto &RefExpr : VarList) {
  5624. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  5625. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5626. // It will be analyzed later.
  5627. Vars.push_back(RefExpr);
  5628. SrcExprs.push_back(nullptr);
  5629. DstExprs.push_back(nullptr);
  5630. AssignmentOps.push_back(nullptr);
  5631. continue;
  5632. }
  5633. SourceLocation ELoc = RefExpr->getExprLoc();
  5634. // OpenMP [2.1, C/C++]
  5635. // A list item is a variable name.
  5636. // OpenMP [2.14.3.5, Restrictions, p.1]
  5637. // A variable that is part of another variable (as an array or structure
  5638. // element) cannot appear in a lastprivate clause.
  5639. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5640. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5641. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5642. continue;
  5643. }
  5644. Decl *D = DE->getDecl();
  5645. VarDecl *VD = cast<VarDecl>(D);
  5646. QualType Type = VD->getType();
  5647. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5648. // It will be analyzed later.
  5649. Vars.push_back(DE);
  5650. SrcExprs.push_back(nullptr);
  5651. DstExprs.push_back(nullptr);
  5652. AssignmentOps.push_back(nullptr);
  5653. continue;
  5654. }
  5655. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  5656. // A variable that appears in a lastprivate clause must not have an
  5657. // incomplete type or a reference type.
  5658. if (RequireCompleteType(ELoc, Type,
  5659. diag::err_omp_lastprivate_incomplete_type)) {
  5660. continue;
  5661. }
  5662. if (Type->isReferenceType()) {
  5663. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  5664. << getOpenMPClauseName(OMPC_lastprivate) << Type;
  5665. bool IsDecl =
  5666. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5667. Diag(VD->getLocation(),
  5668. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5669. << VD;
  5670. continue;
  5671. }
  5672. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  5673. // in a Construct]
  5674. // Variables with the predetermined data-sharing attributes may not be
  5675. // listed in data-sharing attributes clauses, except for the cases
  5676. // listed below.
  5677. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5678. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  5679. DVar.CKind != OMPC_firstprivate &&
  5680. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  5681. Diag(ELoc, diag::err_omp_wrong_dsa)
  5682. << getOpenMPClauseName(DVar.CKind)
  5683. << getOpenMPClauseName(OMPC_lastprivate);
  5684. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5685. continue;
  5686. }
  5687. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  5688. // OpenMP [2.14.3.5, Restrictions, p.2]
  5689. // A list item that is private within a parallel region, or that appears in
  5690. // the reduction clause of a parallel construct, must not appear in a
  5691. // lastprivate clause on a worksharing construct if any of the corresponding
  5692. // worksharing regions ever binds to any of the corresponding parallel
  5693. // regions.
  5694. DSAStackTy::DSAVarData TopDVar = DVar;
  5695. if (isOpenMPWorksharingDirective(CurrDir) &&
  5696. !isOpenMPParallelDirective(CurrDir)) {
  5697. DVar = DSAStack->getImplicitDSA(VD, true);
  5698. if (DVar.CKind != OMPC_shared) {
  5699. Diag(ELoc, diag::err_omp_required_access)
  5700. << getOpenMPClauseName(OMPC_lastprivate)
  5701. << getOpenMPClauseName(OMPC_shared);
  5702. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5703. continue;
  5704. }
  5705. }
  5706. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  5707. // A variable of class type (or array thereof) that appears in a
  5708. // lastprivate clause requires an accessible, unambiguous default
  5709. // constructor for the class type, unless the list item is also specified
  5710. // in a firstprivate clause.
  5711. // A variable of class type (or array thereof) that appears in a
  5712. // lastprivate clause requires an accessible, unambiguous copy assignment
  5713. // operator for the class type.
  5714. Type = Context.getBaseElementType(Type).getNonReferenceType();
  5715. auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
  5716. Type.getUnqualifiedType(), ".lastprivate.src");
  5717. auto *PseudoSrcExpr = buildDeclRefExpr(
  5718. *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
  5719. auto *DstVD =
  5720. buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
  5721. auto *PseudoDstExpr =
  5722. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  5723. // For arrays generate assignment operation for single element and replace
  5724. // it by the original array element in CodeGen.
  5725. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  5726. PseudoDstExpr, PseudoSrcExpr);
  5727. if (AssignmentOp.isInvalid())
  5728. continue;
  5729. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  5730. /*DiscardedValue=*/true);
  5731. if (AssignmentOp.isInvalid())
  5732. continue;
  5733. if (TopDVar.CKind != OMPC_firstprivate)
  5734. DSAStack->addDSA(VD, DE, OMPC_lastprivate);
  5735. Vars.push_back(DE);
  5736. SrcExprs.push_back(PseudoSrcExpr);
  5737. DstExprs.push_back(PseudoDstExpr);
  5738. AssignmentOps.push_back(AssignmentOp.get());
  5739. }
  5740. if (Vars.empty())
  5741. return nullptr;
  5742. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  5743. Vars, SrcExprs, DstExprs, AssignmentOps);
  5744. }
  5745. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  5746. SourceLocation StartLoc,
  5747. SourceLocation LParenLoc,
  5748. SourceLocation EndLoc) {
  5749. SmallVector<Expr *, 8> Vars;
  5750. for (auto &RefExpr : VarList) {
  5751. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  5752. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5753. // It will be analyzed later.
  5754. Vars.push_back(RefExpr);
  5755. continue;
  5756. }
  5757. SourceLocation ELoc = RefExpr->getExprLoc();
  5758. // OpenMP [2.1, C/C++]
  5759. // A list item is a variable name.
  5760. // OpenMP [2.14.3.2, Restrictions, p.1]
  5761. // A variable that is part of another variable (as an array or structure
  5762. // element) cannot appear in a shared unless it is a static data member
  5763. // of a C++ class.
  5764. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  5765. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5766. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  5767. continue;
  5768. }
  5769. Decl *D = DE->getDecl();
  5770. VarDecl *VD = cast<VarDecl>(D);
  5771. QualType Type = VD->getType();
  5772. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  5773. // It will be analyzed later.
  5774. Vars.push_back(DE);
  5775. continue;
  5776. }
  5777. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  5778. // in a Construct]
  5779. // Variables with the predetermined data-sharing attributes may not be
  5780. // listed in data-sharing attributes clauses, except for the cases
  5781. // listed below. For these exceptions only, listing a predetermined
  5782. // variable in a data-sharing attribute clause is allowed and overrides
  5783. // the variable's predetermined data-sharing attributes.
  5784. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  5785. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  5786. DVar.RefExpr) {
  5787. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  5788. << getOpenMPClauseName(OMPC_shared);
  5789. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  5790. continue;
  5791. }
  5792. DSAStack->addDSA(VD, DE, OMPC_shared);
  5793. Vars.push_back(DE);
  5794. }
  5795. if (Vars.empty())
  5796. return nullptr;
  5797. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  5798. }
  5799. namespace {
  5800. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  5801. DSAStackTy *Stack;
  5802. public:
  5803. bool VisitDeclRefExpr(DeclRefExpr *E) {
  5804. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  5805. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  5806. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  5807. return false;
  5808. if (DVar.CKind != OMPC_unknown)
  5809. return true;
  5810. DSAStackTy::DSAVarData DVarPrivate =
  5811. Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
  5812. if (DVarPrivate.CKind != OMPC_unknown)
  5813. return true;
  5814. return false;
  5815. }
  5816. return false;
  5817. }
  5818. bool VisitStmt(Stmt *S) {
  5819. for (auto Child : S->children()) {
  5820. if (Child && Visit(Child))
  5821. return true;
  5822. }
  5823. return false;
  5824. }
  5825. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  5826. };
  5827. } // namespace
  5828. OMPClause *Sema::ActOnOpenMPReductionClause(
  5829. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  5830. SourceLocation ColonLoc, SourceLocation EndLoc,
  5831. CXXScopeSpec &ReductionIdScopeSpec,
  5832. const DeclarationNameInfo &ReductionId) {
  5833. // TODO: Allow scope specification search when 'declare reduction' is
  5834. // supported.
  5835. assert(ReductionIdScopeSpec.isEmpty() &&
  5836. "No support for scoped reduction identifiers yet.");
  5837. auto DN = ReductionId.getName();
  5838. auto OOK = DN.getCXXOverloadedOperator();
  5839. BinaryOperatorKind BOK = BO_Comma;
  5840. // OpenMP [2.14.3.6, reduction clause]
  5841. // C
  5842. // reduction-identifier is either an identifier or one of the following
  5843. // operators: +, -, *, &, |, ^, && and ||
  5844. // C++
  5845. // reduction-identifier is either an id-expression or one of the following
  5846. // operators: +, -, *, &, |, ^, && and ||
  5847. // FIXME: Only 'min' and 'max' identifiers are supported for now.
  5848. switch (OOK) {
  5849. case OO_Plus:
  5850. case OO_Minus:
  5851. BOK = BO_Add;
  5852. break;
  5853. case OO_Star:
  5854. BOK = BO_Mul;
  5855. break;
  5856. case OO_Amp:
  5857. BOK = BO_And;
  5858. break;
  5859. case OO_Pipe:
  5860. BOK = BO_Or;
  5861. break;
  5862. case OO_Caret:
  5863. BOK = BO_Xor;
  5864. break;
  5865. case OO_AmpAmp:
  5866. BOK = BO_LAnd;
  5867. break;
  5868. case OO_PipePipe:
  5869. BOK = BO_LOr;
  5870. break;
  5871. case OO_New:
  5872. case OO_Delete:
  5873. case OO_Array_New:
  5874. case OO_Array_Delete:
  5875. case OO_Slash:
  5876. case OO_Percent:
  5877. case OO_Tilde:
  5878. case OO_Exclaim:
  5879. case OO_Equal:
  5880. case OO_Less:
  5881. case OO_Greater:
  5882. case OO_LessEqual:
  5883. case OO_GreaterEqual:
  5884. case OO_PlusEqual:
  5885. case OO_MinusEqual:
  5886. case OO_StarEqual:
  5887. case OO_SlashEqual:
  5888. case OO_PercentEqual:
  5889. case OO_CaretEqual:
  5890. case OO_AmpEqual:
  5891. case OO_PipeEqual:
  5892. case OO_LessLess:
  5893. case OO_GreaterGreater:
  5894. case OO_LessLessEqual:
  5895. case OO_GreaterGreaterEqual:
  5896. case OO_EqualEqual:
  5897. case OO_ExclaimEqual:
  5898. case OO_PlusPlus:
  5899. case OO_MinusMinus:
  5900. case OO_Comma:
  5901. case OO_ArrowStar:
  5902. case OO_Arrow:
  5903. case OO_Call:
  5904. case OO_Subscript:
  5905. case OO_Conditional:
  5906. case NUM_OVERLOADED_OPERATORS:
  5907. llvm_unreachable("Unexpected reduction identifier");
  5908. case OO_None:
  5909. if (auto II = DN.getAsIdentifierInfo()) {
  5910. if (II->isStr("max"))
  5911. BOK = BO_GT;
  5912. else if (II->isStr("min"))
  5913. BOK = BO_LT;
  5914. }
  5915. break;
  5916. }
  5917. SourceRange ReductionIdRange;
  5918. if (ReductionIdScopeSpec.isValid()) {
  5919. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  5920. }
  5921. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  5922. if (BOK == BO_Comma) {
  5923. // Not allowed reduction identifier is found.
  5924. Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
  5925. << ReductionIdRange;
  5926. return nullptr;
  5927. }
  5928. SmallVector<Expr *, 8> Vars;
  5929. SmallVector<Expr *, 8> LHSs;
  5930. SmallVector<Expr *, 8> RHSs;
  5931. SmallVector<Expr *, 8> ReductionOps;
  5932. for (auto RefExpr : VarList) {
  5933. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  5934. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  5935. // It will be analyzed later.
  5936. Vars.push_back(RefExpr);
  5937. LHSs.push_back(nullptr);
  5938. RHSs.push_back(nullptr);
  5939. ReductionOps.push_back(nullptr);
  5940. continue;
  5941. }
  5942. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  5943. RefExpr->isInstantiationDependent() ||
  5944. RefExpr->containsUnexpandedParameterPack()) {
  5945. // It will be analyzed later.
  5946. Vars.push_back(RefExpr);
  5947. LHSs.push_back(nullptr);
  5948. RHSs.push_back(nullptr);
  5949. ReductionOps.push_back(nullptr);
  5950. continue;
  5951. }
  5952. auto ELoc = RefExpr->getExprLoc();
  5953. auto ERange = RefExpr->getSourceRange();
  5954. // OpenMP [2.1, C/C++]
  5955. // A list item is a variable or array section, subject to the restrictions
  5956. // specified in Section 2.4 on page 42 and in each of the sections
  5957. // describing clauses and directives for which a list appears.
  5958. // OpenMP [2.14.3.3, Restrictions, p.1]
  5959. // A variable that is part of another variable (as an array or
  5960. // structure element) cannot appear in a private clause.
  5961. auto DE = dyn_cast<DeclRefExpr>(RefExpr);
  5962. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  5963. Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
  5964. continue;
  5965. }
  5966. auto D = DE->getDecl();
  5967. auto VD = cast<VarDecl>(D);
  5968. auto Type = VD->getType();
  5969. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  5970. // A variable that appears in a private clause must not have an incomplete
  5971. // type or a reference type.
  5972. if (RequireCompleteType(ELoc, Type,
  5973. diag::err_omp_reduction_incomplete_type))
  5974. continue;
  5975. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  5976. // Arrays may not appear in a reduction clause.
  5977. if (Type.getNonReferenceType()->isArrayType()) {
  5978. Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
  5979. bool IsDecl =
  5980. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5981. Diag(VD->getLocation(),
  5982. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5983. << VD;
  5984. continue;
  5985. }
  5986. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  5987. // A list item that appears in a reduction clause must not be
  5988. // const-qualified.
  5989. if (Type.getNonReferenceType().isConstant(Context)) {
  5990. Diag(ELoc, diag::err_omp_const_variable)
  5991. << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
  5992. bool IsDecl =
  5993. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  5994. Diag(VD->getLocation(),
  5995. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  5996. << VD;
  5997. continue;
  5998. }
  5999. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  6000. // If a list-item is a reference type then it must bind to the same object
  6001. // for all threads of the team.
  6002. VarDecl *VDDef = VD->getDefinition();
  6003. if (Type->isReferenceType() && VDDef) {
  6004. DSARefChecker Check(DSAStack);
  6005. if (Check.Visit(VDDef->getInit())) {
  6006. Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
  6007. Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  6008. continue;
  6009. }
  6010. }
  6011. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  6012. // The type of a list item that appears in a reduction clause must be valid
  6013. // for the reduction-identifier. For a max or min reduction in C, the type
  6014. // of the list item must be an allowed arithmetic data type: char, int,
  6015. // float, double, or _Bool, possibly modified with long, short, signed, or
  6016. // unsigned. For a max or min reduction in C++, the type of the list item
  6017. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  6018. // double, or bool, possibly modified with long, short, signed, or unsigned.
  6019. if ((BOK == BO_GT || BOK == BO_LT) &&
  6020. !(Type->isScalarType() ||
  6021. (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  6022. Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  6023. << getLangOpts().CPlusPlus;
  6024. bool IsDecl =
  6025. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6026. Diag(VD->getLocation(),
  6027. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6028. << VD;
  6029. continue;
  6030. }
  6031. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  6032. !getLangOpts().CPlusPlus && Type->isFloatingType()) {
  6033. Diag(ELoc, diag::err_omp_clause_floating_type_arg);
  6034. bool IsDecl =
  6035. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6036. Diag(VD->getLocation(),
  6037. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6038. << VD;
  6039. continue;
  6040. }
  6041. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  6042. // in a Construct]
  6043. // Variables with the predetermined data-sharing attributes may not be
  6044. // listed in data-sharing attributes clauses, except for the cases
  6045. // listed below. For these exceptions only, listing a predetermined
  6046. // variable in a data-sharing attribute clause is allowed and overrides
  6047. // the variable's predetermined data-sharing attributes.
  6048. // OpenMP [2.14.3.6, Restrictions, p.3]
  6049. // Any number of reduction clauses can be specified on the directive,
  6050. // but a list item can appear only once in the reduction clauses for that
  6051. // directive.
  6052. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6053. if (DVar.CKind == OMPC_reduction) {
  6054. Diag(ELoc, diag::err_omp_once_referenced)
  6055. << getOpenMPClauseName(OMPC_reduction);
  6056. if (DVar.RefExpr) {
  6057. Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  6058. }
  6059. } else if (DVar.CKind != OMPC_unknown) {
  6060. Diag(ELoc, diag::err_omp_wrong_dsa)
  6061. << getOpenMPClauseName(DVar.CKind)
  6062. << getOpenMPClauseName(OMPC_reduction);
  6063. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6064. continue;
  6065. }
  6066. // OpenMP [2.14.3.6, Restrictions, p.1]
  6067. // A list item that appears in a reduction clause of a worksharing
  6068. // construct must be shared in the parallel regions to which any of the
  6069. // worksharing regions arising from the worksharing construct bind.
  6070. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  6071. if (isOpenMPWorksharingDirective(CurrDir) &&
  6072. !isOpenMPParallelDirective(CurrDir)) {
  6073. DVar = DSAStack->getImplicitDSA(VD, true);
  6074. if (DVar.CKind != OMPC_shared) {
  6075. Diag(ELoc, diag::err_omp_required_access)
  6076. << getOpenMPClauseName(OMPC_reduction)
  6077. << getOpenMPClauseName(OMPC_shared);
  6078. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6079. continue;
  6080. }
  6081. }
  6082. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  6083. auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
  6084. auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
  6085. // Add initializer for private variable.
  6086. Expr *Init = nullptr;
  6087. switch (BOK) {
  6088. case BO_Add:
  6089. case BO_Xor:
  6090. case BO_Or:
  6091. case BO_LOr:
  6092. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  6093. if (Type->isScalarType() || Type->isAnyComplexType()) {
  6094. Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  6095. }
  6096. break;
  6097. case BO_Mul:
  6098. case BO_LAnd:
  6099. if (Type->isScalarType() || Type->isAnyComplexType()) {
  6100. // '*' and '&&' reduction ops - initializer is '1'.
  6101. Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  6102. }
  6103. break;
  6104. case BO_And: {
  6105. // '&' reduction op - initializer is '~0'.
  6106. QualType OrigType = Type;
  6107. if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
  6108. Type = ComplexTy->getElementType();
  6109. }
  6110. if (Type->isRealFloatingType()) {
  6111. llvm::APFloat InitValue =
  6112. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  6113. /*isIEEE=*/true);
  6114. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  6115. Type, ELoc);
  6116. } else if (Type->isScalarType()) {
  6117. auto Size = Context.getTypeSize(Type);
  6118. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  6119. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  6120. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  6121. }
  6122. if (Init && OrigType->isAnyComplexType()) {
  6123. // Init = 0xFFFF + 0xFFFFi;
  6124. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  6125. Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  6126. }
  6127. Type = OrigType;
  6128. break;
  6129. }
  6130. case BO_LT:
  6131. case BO_GT: {
  6132. // 'min' reduction op - initializer is 'Largest representable number in
  6133. // the reduction list item type'.
  6134. // 'max' reduction op - initializer is 'Least representable number in
  6135. // the reduction list item type'.
  6136. if (Type->isIntegerType() || Type->isPointerType()) {
  6137. bool IsSigned = Type->hasSignedIntegerRepresentation();
  6138. auto Size = Context.getTypeSize(Type);
  6139. QualType IntTy =
  6140. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  6141. llvm::APInt InitValue =
  6142. (BOK != BO_LT)
  6143. ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  6144. : llvm::APInt::getMinValue(Size)
  6145. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  6146. : llvm::APInt::getMaxValue(Size);
  6147. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  6148. if (Type->isPointerType()) {
  6149. // Cast to pointer type.
  6150. auto CastExpr = BuildCStyleCastExpr(
  6151. SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
  6152. SourceLocation(), Init);
  6153. if (CastExpr.isInvalid())
  6154. continue;
  6155. Init = CastExpr.get();
  6156. }
  6157. } else if (Type->isRealFloatingType()) {
  6158. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  6159. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  6160. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  6161. Type, ELoc);
  6162. }
  6163. break;
  6164. }
  6165. case BO_PtrMemD:
  6166. case BO_PtrMemI:
  6167. case BO_MulAssign:
  6168. case BO_Div:
  6169. case BO_Rem:
  6170. case BO_Sub:
  6171. case BO_Shl:
  6172. case BO_Shr:
  6173. case BO_LE:
  6174. case BO_GE:
  6175. case BO_EQ:
  6176. case BO_NE:
  6177. case BO_AndAssign:
  6178. case BO_XorAssign:
  6179. case BO_OrAssign:
  6180. case BO_Assign:
  6181. case BO_AddAssign:
  6182. case BO_SubAssign:
  6183. case BO_DivAssign:
  6184. case BO_RemAssign:
  6185. case BO_ShlAssign:
  6186. case BO_ShrAssign:
  6187. case BO_Comma:
  6188. llvm_unreachable("Unexpected reduction operation");
  6189. }
  6190. if (Init) {
  6191. AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
  6192. /*TypeMayContainAuto=*/false);
  6193. } else {
  6194. ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
  6195. }
  6196. if (!RHSVD->hasInit()) {
  6197. Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
  6198. << ReductionIdRange;
  6199. bool IsDecl =
  6200. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6201. Diag(VD->getLocation(),
  6202. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6203. << VD;
  6204. continue;
  6205. }
  6206. auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
  6207. auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
  6208. ExprResult ReductionOp =
  6209. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
  6210. LHSDRE, RHSDRE);
  6211. if (ReductionOp.isUsable()) {
  6212. if (BOK != BO_LT && BOK != BO_GT) {
  6213. ReductionOp =
  6214. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  6215. BO_Assign, LHSDRE, ReductionOp.get());
  6216. } else {
  6217. auto *ConditionalOp = new (Context) ConditionalOperator(
  6218. ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
  6219. RHSDRE, Type, VK_LValue, OK_Ordinary);
  6220. ReductionOp =
  6221. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  6222. BO_Assign, LHSDRE, ConditionalOp);
  6223. }
  6224. if (ReductionOp.isUsable()) {
  6225. ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
  6226. }
  6227. }
  6228. if (ReductionOp.isInvalid())
  6229. continue;
  6230. DSAStack->addDSA(VD, DE, OMPC_reduction);
  6231. Vars.push_back(DE);
  6232. LHSs.push_back(LHSDRE);
  6233. RHSs.push_back(RHSDRE);
  6234. ReductionOps.push_back(ReductionOp.get());
  6235. }
  6236. if (Vars.empty())
  6237. return nullptr;
  6238. return OMPReductionClause::Create(
  6239. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
  6240. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
  6241. RHSs, ReductionOps);
  6242. }
  6243. OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
  6244. SourceLocation StartLoc,
  6245. SourceLocation LParenLoc,
  6246. SourceLocation ColonLoc,
  6247. SourceLocation EndLoc) {
  6248. SmallVector<Expr *, 8> Vars;
  6249. SmallVector<Expr *, 8> Inits;
  6250. for (auto &RefExpr : VarList) {
  6251. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  6252. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6253. // It will be analyzed later.
  6254. Vars.push_back(RefExpr);
  6255. Inits.push_back(nullptr);
  6256. continue;
  6257. }
  6258. // OpenMP [2.14.3.7, linear clause]
  6259. // A list item that appears in a linear clause is subject to the private
  6260. // clause semantics described in Section 2.14.3.3 on page 159 except as
  6261. // noted. In addition, the value of the new list item on each iteration
  6262. // of the associated loop(s) corresponds to the value of the original
  6263. // list item before entering the construct plus the logical number of
  6264. // the iteration times linear-step.
  6265. SourceLocation ELoc = RefExpr->getExprLoc();
  6266. // OpenMP [2.1, C/C++]
  6267. // A list item is a variable name.
  6268. // OpenMP [2.14.3.3, Restrictions, p.1]
  6269. // A variable that is part of another variable (as an array or
  6270. // structure element) cannot appear in a private clause.
  6271. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6272. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6273. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6274. continue;
  6275. }
  6276. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  6277. // OpenMP [2.14.3.7, linear clause]
  6278. // A list-item cannot appear in more than one linear clause.
  6279. // A list-item that appears in a linear clause cannot appear in any
  6280. // other data-sharing attribute clause.
  6281. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6282. if (DVar.RefExpr) {
  6283. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  6284. << getOpenMPClauseName(OMPC_linear);
  6285. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6286. continue;
  6287. }
  6288. QualType QType = VD->getType();
  6289. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  6290. // It will be analyzed later.
  6291. Vars.push_back(DE);
  6292. Inits.push_back(nullptr);
  6293. continue;
  6294. }
  6295. // A variable must not have an incomplete type or a reference type.
  6296. if (RequireCompleteType(ELoc, QType,
  6297. diag::err_omp_linear_incomplete_type)) {
  6298. continue;
  6299. }
  6300. if (QType->isReferenceType()) {
  6301. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  6302. << getOpenMPClauseName(OMPC_linear) << QType;
  6303. bool IsDecl =
  6304. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6305. Diag(VD->getLocation(),
  6306. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6307. << VD;
  6308. continue;
  6309. }
  6310. // A list item must not be const-qualified.
  6311. if (QType.isConstant(Context)) {
  6312. Diag(ELoc, diag::err_omp_const_variable)
  6313. << getOpenMPClauseName(OMPC_linear);
  6314. bool IsDecl =
  6315. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6316. Diag(VD->getLocation(),
  6317. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6318. << VD;
  6319. continue;
  6320. }
  6321. // A list item must be of integral or pointer type.
  6322. QType = QType.getUnqualifiedType().getCanonicalType();
  6323. const Type *Ty = QType.getTypePtrOrNull();
  6324. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  6325. !Ty->isPointerType())) {
  6326. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
  6327. bool IsDecl =
  6328. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6329. Diag(VD->getLocation(),
  6330. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6331. << VD;
  6332. continue;
  6333. }
  6334. // Build var to save initial value.
  6335. VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
  6336. AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
  6337. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  6338. auto InitRef = buildDeclRefExpr(
  6339. *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  6340. DSAStack->addDSA(VD, DE, OMPC_linear);
  6341. Vars.push_back(DE);
  6342. Inits.push_back(InitRef);
  6343. }
  6344. if (Vars.empty())
  6345. return nullptr;
  6346. Expr *StepExpr = Step;
  6347. Expr *CalcStepExpr = nullptr;
  6348. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  6349. !Step->isInstantiationDependent() &&
  6350. !Step->containsUnexpandedParameterPack()) {
  6351. SourceLocation StepLoc = Step->getLocStart();
  6352. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  6353. if (Val.isInvalid())
  6354. return nullptr;
  6355. StepExpr = Val.get();
  6356. // Build var to save the step value.
  6357. VarDecl *SaveVar =
  6358. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  6359. ExprResult SaveRef =
  6360. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  6361. ExprResult CalcStep =
  6362. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  6363. // Warn about zero linear step (it would be probably better specified as
  6364. // making corresponding variables 'const').
  6365. llvm::APSInt Result;
  6366. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  6367. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  6368. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  6369. << (Vars.size() > 1);
  6370. if (!IsConstant && CalcStep.isUsable()) {
  6371. // Calculate the step beforehand instead of doing this on each iteration.
  6372. // (This is not used if the number of iterations may be kfold-ed).
  6373. CalcStepExpr = CalcStep.get();
  6374. }
  6375. }
  6376. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
  6377. Vars, Inits, StepExpr, CalcStepExpr);
  6378. }
  6379. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  6380. Expr *NumIterations, Sema &SemaRef,
  6381. Scope *S) {
  6382. // Walk the vars and build update/final expressions for the CodeGen.
  6383. SmallVector<Expr *, 8> Updates;
  6384. SmallVector<Expr *, 8> Finals;
  6385. Expr *Step = Clause.getStep();
  6386. Expr *CalcStep = Clause.getCalcStep();
  6387. // OpenMP [2.14.3.7, linear clause]
  6388. // If linear-step is not specified it is assumed to be 1.
  6389. if (Step == nullptr)
  6390. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  6391. else if (CalcStep)
  6392. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  6393. bool HasErrors = false;
  6394. auto CurInit = Clause.inits().begin();
  6395. for (auto &RefExpr : Clause.varlists()) {
  6396. Expr *InitExpr = *CurInit;
  6397. // Build privatized reference to the current linear var.
  6398. auto DE = cast<DeclRefExpr>(RefExpr);
  6399. auto PrivateRef =
  6400. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  6401. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  6402. /*RefersToCapture=*/true);
  6403. // Build update: Var = InitExpr + IV * Step
  6404. ExprResult Update =
  6405. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
  6406. InitExpr, IV, Step, /* Subtract */ false);
  6407. Update = SemaRef.ActOnFinishFullExpr(Update.get());
  6408. // Build final: Var = InitExpr + NumIterations * Step
  6409. ExprResult Final =
  6410. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
  6411. InitExpr, NumIterations, Step, /* Subtract */ false);
  6412. Final = SemaRef.ActOnFinishFullExpr(Final.get());
  6413. if (!Update.isUsable() || !Final.isUsable()) {
  6414. Updates.push_back(nullptr);
  6415. Finals.push_back(nullptr);
  6416. HasErrors = true;
  6417. } else {
  6418. Updates.push_back(Update.get());
  6419. Finals.push_back(Final.get());
  6420. }
  6421. ++CurInit;
  6422. }
  6423. Clause.setUpdates(Updates);
  6424. Clause.setFinals(Finals);
  6425. return HasErrors;
  6426. }
  6427. OMPClause *Sema::ActOnOpenMPAlignedClause(
  6428. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  6429. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  6430. SmallVector<Expr *, 8> Vars;
  6431. for (auto &RefExpr : VarList) {
  6432. assert(RefExpr && "NULL expr in OpenMP aligned clause.");
  6433. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6434. // It will be analyzed later.
  6435. Vars.push_back(RefExpr);
  6436. continue;
  6437. }
  6438. SourceLocation ELoc = RefExpr->getExprLoc();
  6439. // OpenMP [2.1, C/C++]
  6440. // A list item is a variable name.
  6441. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6442. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6443. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6444. continue;
  6445. }
  6446. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  6447. // OpenMP [2.8.1, simd construct, Restrictions]
  6448. // The type of list items appearing in the aligned clause must be
  6449. // array, pointer, reference to array, or reference to pointer.
  6450. QualType QType = VD->getType();
  6451. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  6452. const Type *Ty = QType.getTypePtrOrNull();
  6453. if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
  6454. !Ty->isPointerType())) {
  6455. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  6456. << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
  6457. bool IsDecl =
  6458. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6459. Diag(VD->getLocation(),
  6460. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6461. << VD;
  6462. continue;
  6463. }
  6464. // OpenMP [2.8.1, simd construct, Restrictions]
  6465. // A list-item cannot appear in more than one aligned clause.
  6466. if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
  6467. Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
  6468. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  6469. << getOpenMPClauseName(OMPC_aligned);
  6470. continue;
  6471. }
  6472. Vars.push_back(DE);
  6473. }
  6474. // OpenMP [2.8.1, simd construct, Description]
  6475. // The parameter of the aligned clause, alignment, must be a constant
  6476. // positive integer expression.
  6477. // If no optional parameter is specified, implementation-defined default
  6478. // alignments for SIMD instructions on the target platforms are assumed.
  6479. if (Alignment != nullptr) {
  6480. ExprResult AlignResult =
  6481. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  6482. if (AlignResult.isInvalid())
  6483. return nullptr;
  6484. Alignment = AlignResult.get();
  6485. }
  6486. if (Vars.empty())
  6487. return nullptr;
  6488. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  6489. EndLoc, Vars, Alignment);
  6490. }
  6491. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  6492. SourceLocation StartLoc,
  6493. SourceLocation LParenLoc,
  6494. SourceLocation EndLoc) {
  6495. SmallVector<Expr *, 8> Vars;
  6496. SmallVector<Expr *, 8> SrcExprs;
  6497. SmallVector<Expr *, 8> DstExprs;
  6498. SmallVector<Expr *, 8> AssignmentOps;
  6499. for (auto &RefExpr : VarList) {
  6500. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  6501. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6502. // It will be analyzed later.
  6503. Vars.push_back(RefExpr);
  6504. SrcExprs.push_back(nullptr);
  6505. DstExprs.push_back(nullptr);
  6506. AssignmentOps.push_back(nullptr);
  6507. continue;
  6508. }
  6509. SourceLocation ELoc = RefExpr->getExprLoc();
  6510. // OpenMP [2.1, C/C++]
  6511. // A list item is a variable name.
  6512. // OpenMP [2.14.4.1, Restrictions, p.1]
  6513. // A list item that appears in a copyin clause must be threadprivate.
  6514. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6515. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6516. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6517. continue;
  6518. }
  6519. Decl *D = DE->getDecl();
  6520. VarDecl *VD = cast<VarDecl>(D);
  6521. QualType Type = VD->getType();
  6522. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6523. // It will be analyzed later.
  6524. Vars.push_back(DE);
  6525. SrcExprs.push_back(nullptr);
  6526. DstExprs.push_back(nullptr);
  6527. AssignmentOps.push_back(nullptr);
  6528. continue;
  6529. }
  6530. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  6531. // A list item that appears in a copyin clause must be threadprivate.
  6532. if (!DSAStack->isThreadPrivate(VD)) {
  6533. Diag(ELoc, diag::err_omp_required_access)
  6534. << getOpenMPClauseName(OMPC_copyin)
  6535. << getOpenMPDirectiveName(OMPD_threadprivate);
  6536. continue;
  6537. }
  6538. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  6539. // A variable of class type (or array thereof) that appears in a
  6540. // copyin clause requires an accessible, unambiguous copy assignment
  6541. // operator for the class type.
  6542. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  6543. auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
  6544. ElemType.getUnqualifiedType(), ".copyin.src");
  6545. auto *PseudoSrcExpr = buildDeclRefExpr(
  6546. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  6547. auto *DstVD =
  6548. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
  6549. auto *PseudoDstExpr =
  6550. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  6551. // For arrays generate assignment operation for single element and replace
  6552. // it by the original array element in CodeGen.
  6553. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  6554. PseudoDstExpr, PseudoSrcExpr);
  6555. if (AssignmentOp.isInvalid())
  6556. continue;
  6557. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  6558. /*DiscardedValue=*/true);
  6559. if (AssignmentOp.isInvalid())
  6560. continue;
  6561. DSAStack->addDSA(VD, DE, OMPC_copyin);
  6562. Vars.push_back(DE);
  6563. SrcExprs.push_back(PseudoSrcExpr);
  6564. DstExprs.push_back(PseudoDstExpr);
  6565. AssignmentOps.push_back(AssignmentOp.get());
  6566. }
  6567. if (Vars.empty())
  6568. return nullptr;
  6569. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  6570. SrcExprs, DstExprs, AssignmentOps);
  6571. }
  6572. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  6573. SourceLocation StartLoc,
  6574. SourceLocation LParenLoc,
  6575. SourceLocation EndLoc) {
  6576. SmallVector<Expr *, 8> Vars;
  6577. SmallVector<Expr *, 8> SrcExprs;
  6578. SmallVector<Expr *, 8> DstExprs;
  6579. SmallVector<Expr *, 8> AssignmentOps;
  6580. for (auto &RefExpr : VarList) {
  6581. assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
  6582. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6583. // It will be analyzed later.
  6584. Vars.push_back(RefExpr);
  6585. SrcExprs.push_back(nullptr);
  6586. DstExprs.push_back(nullptr);
  6587. AssignmentOps.push_back(nullptr);
  6588. continue;
  6589. }
  6590. SourceLocation ELoc = RefExpr->getExprLoc();
  6591. // OpenMP [2.1, C/C++]
  6592. // A list item is a variable name.
  6593. // OpenMP [2.14.4.1, Restrictions, p.1]
  6594. // A list item that appears in a copyin clause must be threadprivate.
  6595. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6596. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6597. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  6598. continue;
  6599. }
  6600. Decl *D = DE->getDecl();
  6601. VarDecl *VD = cast<VarDecl>(D);
  6602. QualType Type = VD->getType();
  6603. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6604. // It will be analyzed later.
  6605. Vars.push_back(DE);
  6606. SrcExprs.push_back(nullptr);
  6607. DstExprs.push_back(nullptr);
  6608. AssignmentOps.push_back(nullptr);
  6609. continue;
  6610. }
  6611. // OpenMP [2.14.4.2, Restrictions, p.2]
  6612. // A list item that appears in a copyprivate clause may not appear in a
  6613. // private or firstprivate clause on the single construct.
  6614. if (!DSAStack->isThreadPrivate(VD)) {
  6615. auto DVar = DSAStack->getTopDSA(VD, false);
  6616. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  6617. DVar.RefExpr) {
  6618. Diag(ELoc, diag::err_omp_wrong_dsa)
  6619. << getOpenMPClauseName(DVar.CKind)
  6620. << getOpenMPClauseName(OMPC_copyprivate);
  6621. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6622. continue;
  6623. }
  6624. // OpenMP [2.11.4.2, Restrictions, p.1]
  6625. // All list items that appear in a copyprivate clause must be either
  6626. // threadprivate or private in the enclosing context.
  6627. if (DVar.CKind == OMPC_unknown) {
  6628. DVar = DSAStack->getImplicitDSA(VD, false);
  6629. if (DVar.CKind == OMPC_shared) {
  6630. Diag(ELoc, diag::err_omp_required_access)
  6631. << getOpenMPClauseName(OMPC_copyprivate)
  6632. << "threadprivate or private in the enclosing context";
  6633. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6634. continue;
  6635. }
  6636. }
  6637. }
  6638. // Variably modified types are not supported.
  6639. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  6640. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  6641. << getOpenMPClauseName(OMPC_copyprivate) << Type
  6642. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  6643. bool IsDecl =
  6644. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6645. Diag(VD->getLocation(),
  6646. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6647. << VD;
  6648. continue;
  6649. }
  6650. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  6651. // A variable of class type (or array thereof) that appears in a
  6652. // copyin clause requires an accessible, unambiguous copy assignment
  6653. // operator for the class type.
  6654. Type = Context.getBaseElementType(Type).getUnqualifiedType();
  6655. auto *SrcVD =
  6656. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
  6657. auto *PseudoSrcExpr =
  6658. buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
  6659. auto *DstVD =
  6660. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
  6661. auto *PseudoDstExpr =
  6662. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  6663. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  6664. PseudoDstExpr, PseudoSrcExpr);
  6665. if (AssignmentOp.isInvalid())
  6666. continue;
  6667. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  6668. /*DiscardedValue=*/true);
  6669. if (AssignmentOp.isInvalid())
  6670. continue;
  6671. // No need to mark vars as copyprivate, they are already threadprivate or
  6672. // implicitly private.
  6673. Vars.push_back(DE);
  6674. SrcExprs.push_back(PseudoSrcExpr);
  6675. DstExprs.push_back(PseudoDstExpr);
  6676. AssignmentOps.push_back(AssignmentOp.get());
  6677. }
  6678. if (Vars.empty())
  6679. return nullptr;
  6680. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  6681. Vars, SrcExprs, DstExprs, AssignmentOps);
  6682. }
  6683. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  6684. SourceLocation StartLoc,
  6685. SourceLocation LParenLoc,
  6686. SourceLocation EndLoc) {
  6687. if (VarList.empty())
  6688. return nullptr;
  6689. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  6690. }
  6691. OMPClause *
  6692. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  6693. SourceLocation DepLoc, SourceLocation ColonLoc,
  6694. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  6695. SourceLocation LParenLoc, SourceLocation EndLoc) {
  6696. if (DepKind == OMPC_DEPEND_unknown) {
  6697. std::string Values;
  6698. std::string Sep(", ");
  6699. for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
  6700. Values += "'";
  6701. Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
  6702. Values += "'";
  6703. switch (i) {
  6704. case OMPC_DEPEND_unknown - 2:
  6705. Values += " or ";
  6706. break;
  6707. case OMPC_DEPEND_unknown - 1:
  6708. break;
  6709. default:
  6710. Values += Sep;
  6711. break;
  6712. }
  6713. }
  6714. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  6715. << Values << getOpenMPClauseName(OMPC_depend);
  6716. return nullptr;
  6717. }
  6718. SmallVector<Expr *, 8> Vars;
  6719. for (auto &RefExpr : VarList) {
  6720. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  6721. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6722. // It will be analyzed later.
  6723. Vars.push_back(RefExpr);
  6724. continue;
  6725. }
  6726. SourceLocation ELoc = RefExpr->getExprLoc();
  6727. // OpenMP [2.11.1.1, Restrictions, p.3]
  6728. // A variable that is part of another variable (such as a field of a
  6729. // structure) but is not an array element or an array section cannot appear
  6730. // in a depend clause.
  6731. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  6732. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
  6733. ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  6734. if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (!ASE && !DE) ||
  6735. (DE && !isa<VarDecl>(DE->getDecl())) ||
  6736. (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
  6737. !ASE->getBase()->getType()->isArrayType())) {
  6738. Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
  6739. << RefExpr->getSourceRange();
  6740. continue;
  6741. }
  6742. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  6743. }
  6744. if (Vars.empty())
  6745. return nullptr;
  6746. return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
  6747. DepLoc, ColonLoc, Vars);
  6748. }
  6749. #endif // HLSL Change