SemaOpenMP.cpp 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381
  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 "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclOpenMP.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/AST/StmtOpenMP.h"
  21. #include "clang/AST/StmtVisitor.h"
  22. #include "clang/Basic/OpenMPKinds.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/Scope.h"
  27. #include "clang/Sema/ScopeInfo.h"
  28. #include "clang/Sema/SemaInternal.h"
  29. using namespace clang;
  30. //===----------------------------------------------------------------------===//
  31. // Stack of data-sharing attributes for variables
  32. //===----------------------------------------------------------------------===//
  33. namespace {
  34. /// \brief Default data sharing attributes, which can be applied to directive.
  35. enum DefaultDataSharingAttributes {
  36. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  37. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  38. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
  39. };
  40. template <class T> struct MatchesAny {
  41. explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
  42. bool operator()(T Kind) {
  43. for (auto KindEl : Arr)
  44. if (KindEl == Kind)
  45. return true;
  46. return false;
  47. }
  48. private:
  49. ArrayRef<T> Arr;
  50. };
  51. struct MatchesAlways {
  52. MatchesAlways() {}
  53. template <class T> bool operator()(T) { return true; }
  54. };
  55. typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
  56. typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
  57. /// \brief Stack for tracking declarations used in OpenMP directives and
  58. /// clauses and their data-sharing attributes.
  59. class DSAStackTy {
  60. public:
  61. struct DSAVarData {
  62. OpenMPDirectiveKind DKind;
  63. OpenMPClauseKind CKind;
  64. DeclRefExpr *RefExpr;
  65. SourceLocation ImplicitDSALoc;
  66. DSAVarData()
  67. : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
  68. ImplicitDSALoc() {}
  69. };
  70. private:
  71. struct DSAInfo {
  72. OpenMPClauseKind Attributes;
  73. DeclRefExpr *RefExpr;
  74. };
  75. typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
  76. typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
  77. struct SharingMapTy {
  78. DeclSAMapTy SharingMap;
  79. AlignedMapTy AlignedMap;
  80. DefaultDataSharingAttributes DefaultAttr;
  81. SourceLocation DefaultAttrLoc;
  82. OpenMPDirectiveKind Directive;
  83. DeclarationNameInfo DirectiveName;
  84. Scope *CurScope;
  85. SourceLocation ConstructLoc;
  86. bool OrderedRegion;
  87. SourceLocation InnerTeamsRegionLoc;
  88. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  89. Scope *CurScope, SourceLocation Loc)
  90. : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
  91. Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
  92. ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {}
  93. SharingMapTy()
  94. : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
  95. Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
  96. ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {}
  97. };
  98. typedef SmallVector<SharingMapTy, 64> StackTy;
  99. /// \brief Stack of used declaration and their data-sharing attributes.
  100. StackTy Stack;
  101. Sema &SemaRef;
  102. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  103. DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
  104. /// \brief Checks if the variable is a local for OpenMP region.
  105. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  106. public:
  107. explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
  108. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  109. Scope *CurScope, SourceLocation Loc) {
  110. Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
  111. Stack.back().DefaultAttrLoc = Loc;
  112. }
  113. void pop() {
  114. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
  115. Stack.pop_back();
  116. }
  117. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  118. /// add it and return NULL; otherwise return previous occurrence's expression
  119. /// for diagnostics.
  120. DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
  121. /// \brief Adds explicit data sharing attribute to the specified declaration.
  122. void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
  123. /// \brief Returns data sharing attributes from top of the stack for the
  124. /// specified declaration.
  125. DSAVarData getTopDSA(VarDecl *D, bool FromParent);
  126. /// \brief Returns data-sharing attributes for the specified declaration.
  127. DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
  128. /// \brief Checks if the specified variables has data-sharing attributes which
  129. /// match specified \a CPred predicate in any directive which matches \a DPred
  130. /// predicate.
  131. template <class ClausesPredicate, class DirectivesPredicate>
  132. DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
  133. DirectivesPredicate DPred, bool FromParent);
  134. /// \brief Checks if the specified variables has data-sharing attributes which
  135. /// match specified \a CPred predicate in any innermost directive which
  136. /// matches \a DPred predicate.
  137. template <class ClausesPredicate, class DirectivesPredicate>
  138. DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  139. DirectivesPredicate DPred,
  140. bool FromParent);
  141. /// \brief Finds a directive which matches specified \a DPred predicate.
  142. template <class NamedDirectivesPredicate>
  143. bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
  144. /// \brief Returns currently analyzed directive.
  145. OpenMPDirectiveKind getCurrentDirective() const {
  146. return Stack.back().Directive;
  147. }
  148. /// \brief Returns parent directive.
  149. OpenMPDirectiveKind getParentDirective() const {
  150. if (Stack.size() > 2)
  151. return Stack[Stack.size() - 2].Directive;
  152. return OMPD_unknown;
  153. }
  154. /// \brief Set default data sharing attribute to none.
  155. void setDefaultDSANone(SourceLocation Loc) {
  156. Stack.back().DefaultAttr = DSA_none;
  157. Stack.back().DefaultAttrLoc = Loc;
  158. }
  159. /// \brief Set default data sharing attribute to shared.
  160. void setDefaultDSAShared(SourceLocation Loc) {
  161. Stack.back().DefaultAttr = DSA_shared;
  162. Stack.back().DefaultAttrLoc = Loc;
  163. }
  164. DefaultDataSharingAttributes getDefaultDSA() const {
  165. return Stack.back().DefaultAttr;
  166. }
  167. SourceLocation getDefaultDSALocation() const {
  168. return Stack.back().DefaultAttrLoc;
  169. }
  170. /// \brief Checks if the specified variable is a threadprivate.
  171. bool isThreadPrivate(VarDecl *D) {
  172. DSAVarData DVar = getTopDSA(D, false);
  173. return isOpenMPThreadPrivate(DVar.CKind);
  174. }
  175. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  176. void setOrderedRegion(bool IsOrdered = true) {
  177. Stack.back().OrderedRegion = IsOrdered;
  178. }
  179. /// \brief Returns true, if parent region is ordered (has associated
  180. /// 'ordered' clause), false - otherwise.
  181. bool isParentOrderedRegion() const {
  182. if (Stack.size() > 2)
  183. return Stack[Stack.size() - 2].OrderedRegion;
  184. return false;
  185. }
  186. /// \brief Marks current target region as one with closely nested teams
  187. /// region.
  188. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  189. if (Stack.size() > 2)
  190. Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
  191. }
  192. /// \brief Returns true, if current region has closely nested teams region.
  193. bool hasInnerTeamsRegion() const {
  194. return getInnerTeamsRegionLoc().isValid();
  195. }
  196. /// \brief Returns location of the nested teams region (if any).
  197. SourceLocation getInnerTeamsRegionLoc() const {
  198. if (Stack.size() > 1)
  199. return Stack.back().InnerTeamsRegionLoc;
  200. return SourceLocation();
  201. }
  202. Scope *getCurScope() const { return Stack.back().CurScope; }
  203. Scope *getCurScope() { return Stack.back().CurScope; }
  204. SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
  205. };
  206. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  207. return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
  208. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  209. }
  210. } // namespace
  211. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
  212. VarDecl *D) {
  213. DSAVarData DVar;
  214. if (Iter == std::prev(Stack.rend())) {
  215. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  216. // in a region but not in construct]
  217. // File-scope or namespace-scope variables referenced in called routines
  218. // in the region are shared unless they appear in a threadprivate
  219. // directive.
  220. if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  221. DVar.CKind = OMPC_shared;
  222. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  223. // in a region but not in construct]
  224. // Variables with static storage duration that are declared in called
  225. // routines in the region are shared.
  226. if (D->hasGlobalStorage())
  227. DVar.CKind = OMPC_shared;
  228. return DVar;
  229. }
  230. DVar.DKind = Iter->Directive;
  231. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  232. // in a Construct, C/C++, predetermined, p.1]
  233. // Variables with automatic storage duration that are declared in a scope
  234. // inside the construct are private.
  235. if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
  236. (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
  237. DVar.CKind = OMPC_private;
  238. return DVar;
  239. }
  240. // Explicitly specified attributes and local variables with predetermined
  241. // attributes.
  242. if (Iter->SharingMap.count(D)) {
  243. DVar.RefExpr = Iter->SharingMap[D].RefExpr;
  244. DVar.CKind = Iter->SharingMap[D].Attributes;
  245. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  246. return DVar;
  247. }
  248. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  249. // in a Construct, C/C++, implicitly determined, p.1]
  250. // In a parallel or task construct, the data-sharing attributes of these
  251. // variables are determined by the default clause, if present.
  252. switch (Iter->DefaultAttr) {
  253. case DSA_shared:
  254. DVar.CKind = OMPC_shared;
  255. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  256. return DVar;
  257. case DSA_none:
  258. return DVar;
  259. case DSA_unspecified:
  260. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  261. // in a Construct, implicitly determined, p.2]
  262. // In a parallel construct, if no default clause is present, these
  263. // variables are shared.
  264. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  265. if (isOpenMPParallelDirective(DVar.DKind) ||
  266. isOpenMPTeamsDirective(DVar.DKind)) {
  267. DVar.CKind = OMPC_shared;
  268. return DVar;
  269. }
  270. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  271. // in a Construct, implicitly determined, p.4]
  272. // In a task construct, if no default clause is present, a variable that in
  273. // the enclosing context is determined to be shared by all implicit tasks
  274. // bound to the current team is shared.
  275. if (DVar.DKind == OMPD_task) {
  276. DSAVarData DVarTemp;
  277. for (StackTy::reverse_iterator I = std::next(Iter),
  278. EE = std::prev(Stack.rend());
  279. I != EE; ++I) {
  280. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  281. // Referenced
  282. // in a Construct, implicitly determined, p.6]
  283. // In a task construct, if no default clause is present, a variable
  284. // whose data-sharing attribute is not determined by the rules above is
  285. // firstprivate.
  286. DVarTemp = getDSA(I, D);
  287. if (DVarTemp.CKind != OMPC_shared) {
  288. DVar.RefExpr = nullptr;
  289. DVar.DKind = OMPD_task;
  290. DVar.CKind = OMPC_firstprivate;
  291. return DVar;
  292. }
  293. if (isParallelOrTaskRegion(I->Directive))
  294. break;
  295. }
  296. DVar.DKind = OMPD_task;
  297. DVar.CKind =
  298. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  299. return DVar;
  300. }
  301. }
  302. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  303. // in a Construct, implicitly determined, p.3]
  304. // For constructs other than task, if no default clause is present, these
  305. // variables inherit their data-sharing attributes from the enclosing
  306. // context.
  307. return getDSA(std::next(Iter), D);
  308. }
  309. DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
  310. assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
  311. auto It = Stack.back().AlignedMap.find(D);
  312. if (It == Stack.back().AlignedMap.end()) {
  313. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  314. Stack.back().AlignedMap[D] = NewDE;
  315. return nullptr;
  316. } else {
  317. assert(It->second && "Unexpected nullptr expr in the aligned map");
  318. return It->second;
  319. }
  320. return nullptr;
  321. }
  322. void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
  323. if (A == OMPC_threadprivate) {
  324. Stack[0].SharingMap[D].Attributes = A;
  325. Stack[0].SharingMap[D].RefExpr = E;
  326. } else {
  327. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  328. Stack.back().SharingMap[D].Attributes = A;
  329. Stack.back().SharingMap[D].RefExpr = E;
  330. }
  331. }
  332. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  333. if (Stack.size() > 2) {
  334. reverse_iterator I = Iter, E = std::prev(Stack.rend());
  335. Scope *TopScope = nullptr;
  336. while (I != E && !isParallelOrTaskRegion(I->Directive)) {
  337. ++I;
  338. }
  339. if (I == E)
  340. return false;
  341. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  342. Scope *CurScope = getCurScope();
  343. while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
  344. CurScope = CurScope->getParent();
  345. }
  346. return CurScope != TopScope;
  347. }
  348. return false;
  349. }
  350. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
  351. DSAVarData DVar;
  352. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  353. // in a Construct, C/C++, predetermined, p.1]
  354. // Variables appearing in threadprivate directives are threadprivate.
  355. if (D->getTLSKind() != VarDecl::TLS_None) {
  356. DVar.CKind = OMPC_threadprivate;
  357. return DVar;
  358. }
  359. if (Stack[0].SharingMap.count(D)) {
  360. DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
  361. DVar.CKind = OMPC_threadprivate;
  362. return DVar;
  363. }
  364. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  365. // in a Construct, C/C++, predetermined, p.1]
  366. // Variables with automatic storage duration that are declared in a scope
  367. // inside the construct are private.
  368. OpenMPDirectiveKind Kind =
  369. FromParent ? getParentDirective() : getCurrentDirective();
  370. auto StartI = std::next(Stack.rbegin());
  371. auto EndI = std::prev(Stack.rend());
  372. if (FromParent && StartI != EndI) {
  373. StartI = std::next(StartI);
  374. }
  375. if (!isParallelOrTaskRegion(Kind)) {
  376. if (isOpenMPLocal(D, StartI) &&
  377. ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
  378. D->getStorageClass() == SC_None)) ||
  379. isa<ParmVarDecl>(D))) {
  380. DVar.CKind = OMPC_private;
  381. return DVar;
  382. }
  383. }
  384. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  385. // in a Construct, C/C++, predetermined, p.4]
  386. // Static data members are shared.
  387. if (D->isStaticDataMember()) {
  388. // Variables with const-qualified type having no mutable member may be
  389. // listed in a firstprivate clause, even if they are static data members.
  390. DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
  391. MatchesAlways(), FromParent);
  392. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  393. return DVar;
  394. DVar.CKind = OMPC_shared;
  395. return DVar;
  396. }
  397. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  398. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  399. while (Type->isArrayType()) {
  400. QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
  401. Type = ElemType.getNonReferenceType().getCanonicalType();
  402. }
  403. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  404. // in a Construct, C/C++, predetermined, p.6]
  405. // Variables with const qualified type having no mutable member are
  406. // shared.
  407. CXXRecordDecl *RD =
  408. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  409. if (IsConstant &&
  410. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
  411. // Variables with const-qualified type having no mutable member may be
  412. // listed in a firstprivate clause, even if they are static data members.
  413. DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
  414. MatchesAlways(), FromParent);
  415. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  416. return DVar;
  417. DVar.CKind = OMPC_shared;
  418. return DVar;
  419. }
  420. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  421. // in a Construct, C/C++, predetermined, p.7]
  422. // Variables with static storage duration that are declared in a scope
  423. // inside the construct are shared.
  424. if (D->isStaticLocal()) {
  425. DVar.CKind = OMPC_shared;
  426. return DVar;
  427. }
  428. // Explicitly specified attributes and local variables with predetermined
  429. // attributes.
  430. auto I = std::prev(StartI);
  431. if (I->SharingMap.count(D)) {
  432. DVar.RefExpr = I->SharingMap[D].RefExpr;
  433. DVar.CKind = I->SharingMap[D].Attributes;
  434. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  435. }
  436. return DVar;
  437. }
  438. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
  439. auto StartI = Stack.rbegin();
  440. auto EndI = std::prev(Stack.rend());
  441. if (FromParent && StartI != EndI) {
  442. StartI = std::next(StartI);
  443. }
  444. return getDSA(StartI, D);
  445. }
  446. template <class ClausesPredicate, class DirectivesPredicate>
  447. DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
  448. DirectivesPredicate DPred,
  449. bool FromParent) {
  450. auto StartI = std::next(Stack.rbegin());
  451. auto EndI = std::prev(Stack.rend());
  452. if (FromParent && StartI != EndI) {
  453. StartI = std::next(StartI);
  454. }
  455. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  456. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  457. continue;
  458. DSAVarData DVar = getDSA(I, D);
  459. if (CPred(DVar.CKind))
  460. return DVar;
  461. }
  462. return DSAVarData();
  463. }
  464. template <class ClausesPredicate, class DirectivesPredicate>
  465. DSAStackTy::DSAVarData
  466. DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
  467. DirectivesPredicate DPred, bool FromParent) {
  468. auto StartI = std::next(Stack.rbegin());
  469. auto EndI = std::prev(Stack.rend());
  470. if (FromParent && StartI != EndI) {
  471. StartI = std::next(StartI);
  472. }
  473. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  474. if (!DPred(I->Directive))
  475. break;
  476. DSAVarData DVar = getDSA(I, D);
  477. if (CPred(DVar.CKind))
  478. return DVar;
  479. return DSAVarData();
  480. }
  481. return DSAVarData();
  482. }
  483. template <class NamedDirectivesPredicate>
  484. bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
  485. auto StartI = std::next(Stack.rbegin());
  486. auto EndI = std::prev(Stack.rend());
  487. if (FromParent && StartI != EndI) {
  488. StartI = std::next(StartI);
  489. }
  490. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  491. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  492. return true;
  493. }
  494. return false;
  495. }
  496. void Sema::InitDataSharingAttributesStack() {
  497. VarDataSharingAttributesStack = new DSAStackTy(*this);
  498. }
  499. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  500. bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
  501. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  502. if (DSAStack->getCurrentDirective() != OMPD_unknown) {
  503. auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
  504. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  505. return true;
  506. DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
  507. /*FromParent=*/false);
  508. return DVarPrivate.CKind != OMPC_unknown;
  509. }
  510. return false;
  511. }
  512. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  513. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  514. const DeclarationNameInfo &DirName,
  515. Scope *CurScope, SourceLocation Loc) {
  516. DSAStack->push(DKind, DirName, CurScope, Loc);
  517. PushExpressionEvaluationContext(PotentiallyEvaluated);
  518. }
  519. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  520. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  521. // A variable of class type (or array thereof) that appears in a lastprivate
  522. // clause requires an accessible, unambiguous default constructor for the
  523. // class type, unless the list item is also specified in a firstprivate
  524. // clause.
  525. if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  526. for (auto C : D->clauses()) {
  527. if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
  528. for (auto VarRef : Clause->varlists()) {
  529. if (VarRef->isValueDependent() || VarRef->isTypeDependent())
  530. continue;
  531. auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
  532. auto DVar = DSAStack->getTopDSA(VD, false);
  533. if (DVar.CKind == OMPC_lastprivate) {
  534. SourceLocation ELoc = VarRef->getExprLoc();
  535. auto Type = VarRef->getType();
  536. if (Type->isArrayType())
  537. Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
  538. CXXRecordDecl *RD =
  539. getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  540. // FIXME This code must be replaced by actual constructing of the
  541. // lastprivate variable.
  542. if (RD) {
  543. CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
  544. PartialDiagnostic PD =
  545. PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
  546. if (!CD ||
  547. CheckConstructorAccess(
  548. ELoc, CD, InitializedEntity::InitializeTemporary(Type),
  549. CD->getAccess(), PD) == AR_inaccessible ||
  550. CD->isDeleted()) {
  551. Diag(ELoc, diag::err_omp_required_method)
  552. << getOpenMPClauseName(OMPC_lastprivate) << 0;
  553. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  554. VarDecl::DeclarationOnly;
  555. Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
  556. : diag::note_defined_here)
  557. << VD;
  558. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  559. continue;
  560. }
  561. MarkFunctionReferenced(ELoc, CD);
  562. DiagnoseUseOfDecl(CD, ELoc);
  563. }
  564. }
  565. }
  566. }
  567. }
  568. }
  569. DSAStack->pop();
  570. DiscardCleanupsInEvaluationContext();
  571. PopExpressionEvaluationContext();
  572. }
  573. namespace {
  574. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  575. private:
  576. Sema &SemaRef;
  577. public:
  578. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  579. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  580. NamedDecl *ND = Candidate.getCorrectionDecl();
  581. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
  582. return VD->hasGlobalStorage() &&
  583. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  584. SemaRef.getCurScope());
  585. }
  586. return false;
  587. }
  588. };
  589. } // namespace
  590. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  591. CXXScopeSpec &ScopeSpec,
  592. const DeclarationNameInfo &Id) {
  593. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  594. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  595. if (Lookup.isAmbiguous())
  596. return ExprError();
  597. VarDecl *VD;
  598. if (!Lookup.isSingleResult()) {
  599. if (TypoCorrection Corrected = CorrectTypo(
  600. Id, LookupOrdinaryName, CurScope, nullptr,
  601. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  602. diagnoseTypo(Corrected,
  603. PDiag(Lookup.empty()
  604. ? diag::err_undeclared_var_use_suggest
  605. : diag::err_omp_expected_var_arg_suggest)
  606. << Id.getName());
  607. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  608. } else {
  609. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  610. : diag::err_omp_expected_var_arg)
  611. << Id.getName();
  612. return ExprError();
  613. }
  614. } else {
  615. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  616. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  617. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  618. return ExprError();
  619. }
  620. }
  621. Lookup.suppressDiagnostics();
  622. // OpenMP [2.9.2, Syntax, C/C++]
  623. // Variables must be file-scope, namespace-scope, or static block-scope.
  624. if (!VD->hasGlobalStorage()) {
  625. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  626. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  627. bool IsDecl =
  628. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  629. Diag(VD->getLocation(),
  630. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  631. << VD;
  632. return ExprError();
  633. }
  634. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  635. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  636. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  637. // A threadprivate directive for file-scope variables must appear outside
  638. // any definition or declaration.
  639. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  640. !getCurLexicalContext()->isTranslationUnit()) {
  641. Diag(Id.getLoc(), diag::err_omp_var_scope)
  642. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  643. bool IsDecl =
  644. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  645. Diag(VD->getLocation(),
  646. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  647. << VD;
  648. return ExprError();
  649. }
  650. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  651. // A threadprivate directive for static class member variables must appear
  652. // in the class definition, in the same scope in which the member
  653. // variables are declared.
  654. if (CanonicalVD->isStaticDataMember() &&
  655. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  656. Diag(Id.getLoc(), diag::err_omp_var_scope)
  657. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  658. bool IsDecl =
  659. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  660. Diag(VD->getLocation(),
  661. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  662. << VD;
  663. return ExprError();
  664. }
  665. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  666. // A threadprivate directive for namespace-scope variables must appear
  667. // outside any definition or declaration other than the namespace
  668. // definition itself.
  669. if (CanonicalVD->getDeclContext()->isNamespace() &&
  670. (!getCurLexicalContext()->isFileContext() ||
  671. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  672. Diag(Id.getLoc(), diag::err_omp_var_scope)
  673. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  674. bool IsDecl =
  675. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  676. Diag(VD->getLocation(),
  677. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  678. << VD;
  679. return ExprError();
  680. }
  681. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  682. // A threadprivate directive for static block-scope variables must appear
  683. // in the scope of the variable and not in a nested scope.
  684. if (CanonicalVD->isStaticLocal() && CurScope &&
  685. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  686. Diag(Id.getLoc(), diag::err_omp_var_scope)
  687. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  688. bool IsDecl =
  689. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  690. Diag(VD->getLocation(),
  691. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  692. << VD;
  693. return ExprError();
  694. }
  695. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  696. // A threadprivate directive must lexically precede all references to any
  697. // of the variables in its list.
  698. if (VD->isUsed()) {
  699. Diag(Id.getLoc(), diag::err_omp_var_used)
  700. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  701. return ExprError();
  702. }
  703. QualType ExprType = VD->getType().getNonReferenceType();
  704. ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
  705. return DE;
  706. }
  707. Sema::DeclGroupPtrTy
  708. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  709. ArrayRef<Expr *> VarList) {
  710. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  711. CurContext->addDecl(D);
  712. return DeclGroupPtrTy::make(DeclGroupRef(D));
  713. }
  714. return DeclGroupPtrTy();
  715. }
  716. namespace {
  717. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  718. Sema &SemaRef;
  719. public:
  720. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  721. if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
  722. if (VD->hasLocalStorage()) {
  723. SemaRef.Diag(E->getLocStart(),
  724. diag::err_omp_local_var_in_threadprivate_init)
  725. << E->getSourceRange();
  726. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  727. << VD << VD->getSourceRange();
  728. return true;
  729. }
  730. }
  731. return false;
  732. }
  733. bool VisitStmt(const Stmt *S) {
  734. for (auto Child : S->children()) {
  735. if (Child && Visit(Child))
  736. return true;
  737. }
  738. return false;
  739. }
  740. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  741. };
  742. } // namespace
  743. OMPThreadPrivateDecl *
  744. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  745. SmallVector<Expr *, 8> Vars;
  746. for (auto &RefExpr : VarList) {
  747. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  748. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  749. SourceLocation ILoc = DE->getExprLoc();
  750. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  751. // A threadprivate variable must not have an incomplete type.
  752. if (RequireCompleteType(ILoc, VD->getType(),
  753. diag::err_omp_threadprivate_incomplete_type)) {
  754. continue;
  755. }
  756. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  757. // A threadprivate variable must not have a reference type.
  758. if (VD->getType()->isReferenceType()) {
  759. Diag(ILoc, diag::err_omp_ref_type_arg)
  760. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  761. bool IsDecl =
  762. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  763. Diag(VD->getLocation(),
  764. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  765. << VD;
  766. continue;
  767. }
  768. // Check if this is a TLS variable.
  769. if (VD->getTLSKind()) {
  770. Diag(ILoc, diag::err_omp_var_thread_local) << VD;
  771. bool IsDecl =
  772. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  773. Diag(VD->getLocation(),
  774. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  775. << VD;
  776. continue;
  777. }
  778. // Check if initial value of threadprivate variable reference variable with
  779. // local storage (it is not supported by runtime).
  780. if (auto Init = VD->getAnyInitializer()) {
  781. LocalVarRefChecker Checker(*this);
  782. if (Checker.Visit(Init))
  783. continue;
  784. }
  785. Vars.push_back(RefExpr);
  786. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  787. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  788. Context, SourceRange(Loc, Loc)));
  789. if (auto *ML = Context.getASTMutationListener())
  790. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  791. }
  792. OMPThreadPrivateDecl *D = nullptr;
  793. if (!Vars.empty()) {
  794. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  795. Vars);
  796. D->setAccess(AS_public);
  797. }
  798. return D;
  799. }
  800. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  801. const VarDecl *VD, DSAStackTy::DSAVarData DVar,
  802. bool IsLoopIterVar = false) {
  803. if (DVar.RefExpr) {
  804. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  805. << getOpenMPClauseName(DVar.CKind);
  806. return;
  807. }
  808. enum {
  809. PDSA_StaticMemberShared,
  810. PDSA_StaticLocalVarShared,
  811. PDSA_LoopIterVarPrivate,
  812. PDSA_LoopIterVarLinear,
  813. PDSA_LoopIterVarLastprivate,
  814. PDSA_ConstVarShared,
  815. PDSA_GlobalVarShared,
  816. PDSA_TaskVarFirstprivate,
  817. PDSA_LocalVarPrivate,
  818. PDSA_Implicit
  819. } Reason = PDSA_Implicit;
  820. bool ReportHint = false;
  821. auto ReportLoc = VD->getLocation();
  822. if (IsLoopIterVar) {
  823. if (DVar.CKind == OMPC_private)
  824. Reason = PDSA_LoopIterVarPrivate;
  825. else if (DVar.CKind == OMPC_lastprivate)
  826. Reason = PDSA_LoopIterVarLastprivate;
  827. else
  828. Reason = PDSA_LoopIterVarLinear;
  829. } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
  830. Reason = PDSA_TaskVarFirstprivate;
  831. ReportLoc = DVar.ImplicitDSALoc;
  832. } else if (VD->isStaticLocal())
  833. Reason = PDSA_StaticLocalVarShared;
  834. else if (VD->isStaticDataMember())
  835. Reason = PDSA_StaticMemberShared;
  836. else if (VD->isFileVarDecl())
  837. Reason = PDSA_GlobalVarShared;
  838. else if (VD->getType().isConstant(SemaRef.getASTContext()))
  839. Reason = PDSA_ConstVarShared;
  840. else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  841. ReportHint = true;
  842. Reason = PDSA_LocalVarPrivate;
  843. }
  844. if (Reason != PDSA_Implicit) {
  845. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  846. << Reason << ReportHint
  847. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  848. } else if (DVar.ImplicitDSALoc.isValid()) {
  849. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  850. << getOpenMPClauseName(DVar.CKind);
  851. }
  852. }
  853. namespace {
  854. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  855. DSAStackTy *Stack;
  856. Sema &SemaRef;
  857. bool ErrorFound;
  858. CapturedStmt *CS;
  859. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  860. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  861. public:
  862. void VisitDeclRefExpr(DeclRefExpr *E) {
  863. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  864. // Skip internally declared variables.
  865. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
  866. return;
  867. auto DVar = Stack->getTopDSA(VD, false);
  868. // Check if the variable has explicit DSA set and stop analysis if it so.
  869. if (DVar.RefExpr) return;
  870. auto ELoc = E->getExprLoc();
  871. auto DKind = Stack->getCurrentDirective();
  872. // The default(none) clause requires that each variable that is referenced
  873. // in the construct, and does not have a predetermined data-sharing
  874. // attribute, must have its data-sharing attribute explicitly determined
  875. // by being listed in a data-sharing attribute clause.
  876. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  877. isParallelOrTaskRegion(DKind) &&
  878. VarsWithInheritedDSA.count(VD) == 0) {
  879. VarsWithInheritedDSA[VD] = E;
  880. return;
  881. }
  882. // OpenMP [2.9.3.6, Restrictions, p.2]
  883. // A list item that appears in a reduction clause of the innermost
  884. // enclosing worksharing or parallel construct may not be accessed in an
  885. // explicit task.
  886. DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  887. [](OpenMPDirectiveKind K) -> bool {
  888. return isOpenMPParallelDirective(K) ||
  889. isOpenMPWorksharingDirective(K) ||
  890. isOpenMPTeamsDirective(K);
  891. },
  892. false);
  893. if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
  894. ErrorFound = true;
  895. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  896. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  897. return;
  898. }
  899. // Define implicit data-sharing attributes for task.
  900. DVar = Stack->getImplicitDSA(VD, false);
  901. if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
  902. ImplicitFirstprivate.push_back(E);
  903. }
  904. }
  905. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  906. for (auto *C : S->clauses()) {
  907. // Skip analysis of arguments of implicitly defined firstprivate clause
  908. // for task directives.
  909. if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
  910. for (auto *CC : C->children()) {
  911. if (CC)
  912. Visit(CC);
  913. }
  914. }
  915. }
  916. void VisitStmt(Stmt *S) {
  917. for (auto *C : S->children()) {
  918. if (C && !isa<OMPExecutableDirective>(C))
  919. Visit(C);
  920. }
  921. }
  922. bool isErrorFound() { return ErrorFound; }
  923. ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
  924. llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
  925. return VarsWithInheritedDSA;
  926. }
  927. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  928. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  929. };
  930. } // namespace
  931. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  932. switch (DKind) {
  933. case OMPD_parallel: {
  934. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  935. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  936. Sema::CapturedParamNameType Params[] = {
  937. std::make_pair(".global_tid.", KmpInt32PtrTy),
  938. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  939. std::make_pair(StringRef(), QualType()) // __context with shared vars
  940. };
  941. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  942. Params);
  943. break;
  944. }
  945. case OMPD_simd: {
  946. Sema::CapturedParamNameType Params[] = {
  947. std::make_pair(StringRef(), QualType()) // __context with shared vars
  948. };
  949. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  950. Params);
  951. break;
  952. }
  953. case OMPD_for: {
  954. Sema::CapturedParamNameType Params[] = {
  955. std::make_pair(StringRef(), QualType()) // __context with shared vars
  956. };
  957. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  958. Params);
  959. break;
  960. }
  961. case OMPD_for_simd: {
  962. Sema::CapturedParamNameType Params[] = {
  963. std::make_pair(StringRef(), QualType()) // __context with shared vars
  964. };
  965. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  966. Params);
  967. break;
  968. }
  969. case OMPD_sections: {
  970. Sema::CapturedParamNameType Params[] = {
  971. std::make_pair(StringRef(), QualType()) // __context with shared vars
  972. };
  973. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  974. Params);
  975. break;
  976. }
  977. case OMPD_section: {
  978. Sema::CapturedParamNameType Params[] = {
  979. std::make_pair(StringRef(), QualType()) // __context with shared vars
  980. };
  981. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  982. Params);
  983. break;
  984. }
  985. case OMPD_single: {
  986. Sema::CapturedParamNameType Params[] = {
  987. std::make_pair(StringRef(), QualType()) // __context with shared vars
  988. };
  989. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  990. Params);
  991. break;
  992. }
  993. case OMPD_master: {
  994. Sema::CapturedParamNameType Params[] = {
  995. std::make_pair(StringRef(), QualType()) // __context with shared vars
  996. };
  997. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  998. Params);
  999. break;
  1000. }
  1001. case OMPD_critical: {
  1002. Sema::CapturedParamNameType Params[] = {
  1003. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1004. };
  1005. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1006. Params);
  1007. break;
  1008. }
  1009. case OMPD_parallel_for: {
  1010. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1011. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1012. Sema::CapturedParamNameType Params[] = {
  1013. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1014. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1015. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1016. };
  1017. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1018. Params);
  1019. break;
  1020. }
  1021. case OMPD_parallel_for_simd: {
  1022. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1023. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1024. Sema::CapturedParamNameType Params[] = {
  1025. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1026. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1027. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1028. };
  1029. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1030. Params);
  1031. break;
  1032. }
  1033. case OMPD_parallel_sections: {
  1034. Sema::CapturedParamNameType Params[] = {
  1035. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1036. };
  1037. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1038. Params);
  1039. break;
  1040. }
  1041. case OMPD_task: {
  1042. Sema::CapturedParamNameType Params[] = {
  1043. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1044. };
  1045. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1046. Params);
  1047. break;
  1048. }
  1049. case OMPD_ordered: {
  1050. Sema::CapturedParamNameType Params[] = {
  1051. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1052. };
  1053. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1054. Params);
  1055. break;
  1056. }
  1057. case OMPD_atomic: {
  1058. Sema::CapturedParamNameType Params[] = {
  1059. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1060. };
  1061. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1062. Params);
  1063. break;
  1064. }
  1065. case OMPD_target: {
  1066. Sema::CapturedParamNameType Params[] = {
  1067. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1068. };
  1069. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1070. Params);
  1071. break;
  1072. }
  1073. case OMPD_teams: {
  1074. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1075. QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
  1076. Sema::CapturedParamNameType Params[] = {
  1077. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1078. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1079. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1080. };
  1081. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1082. Params);
  1083. break;
  1084. }
  1085. case OMPD_threadprivate:
  1086. case OMPD_taskyield:
  1087. case OMPD_barrier:
  1088. case OMPD_taskwait:
  1089. case OMPD_flush:
  1090. llvm_unreachable("OpenMP Directive is not allowed");
  1091. case OMPD_unknown:
  1092. llvm_unreachable("Unknown OpenMP directive");
  1093. }
  1094. }
  1095. static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  1096. OpenMPDirectiveKind CurrentRegion,
  1097. const DeclarationNameInfo &CurrentName,
  1098. SourceLocation StartLoc) {
  1099. // Allowed nesting of constructs
  1100. // +------------------+-----------------+------------------------------------+
  1101. // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
  1102. // +------------------+-----------------+------------------------------------+
  1103. // | parallel | parallel | * |
  1104. // | parallel | for | * |
  1105. // | parallel | for simd | * |
  1106. // | parallel | master | * |
  1107. // | parallel | critical | * |
  1108. // | parallel | simd | * |
  1109. // | parallel | sections | * |
  1110. // | parallel | section | + |
  1111. // | parallel | single | * |
  1112. // | parallel | parallel for | * |
  1113. // | parallel |parallel for simd| * |
  1114. // | parallel |parallel sections| * |
  1115. // | parallel | task | * |
  1116. // | parallel | taskyield | * |
  1117. // | parallel | barrier | * |
  1118. // | parallel | taskwait | * |
  1119. // | parallel | flush | * |
  1120. // | parallel | ordered | + |
  1121. // | parallel | atomic | * |
  1122. // | parallel | target | * |
  1123. // | parallel | teams | + |
  1124. // +------------------+-----------------+------------------------------------+
  1125. // | for | parallel | * |
  1126. // | for | for | + |
  1127. // | for | for simd | + |
  1128. // | for | master | + |
  1129. // | for | critical | * |
  1130. // | for | simd | * |
  1131. // | for | sections | + |
  1132. // | for | section | + |
  1133. // | for | single | + |
  1134. // | for | parallel for | * |
  1135. // | for |parallel for simd| * |
  1136. // | for |parallel sections| * |
  1137. // | for | task | * |
  1138. // | for | taskyield | * |
  1139. // | for | barrier | + |
  1140. // | for | taskwait | * |
  1141. // | for | flush | * |
  1142. // | for | ordered | * (if construct is ordered) |
  1143. // | for | atomic | * |
  1144. // | for | target | * |
  1145. // | for | teams | + |
  1146. // +------------------+-----------------+------------------------------------+
  1147. // | master | parallel | * |
  1148. // | master | for | + |
  1149. // | master | for simd | + |
  1150. // | master | master | * |
  1151. // | master | critical | * |
  1152. // | master | simd | * |
  1153. // | master | sections | + |
  1154. // | master | section | + |
  1155. // | master | single | + |
  1156. // | master | parallel for | * |
  1157. // | master |parallel for simd| * |
  1158. // | master |parallel sections| * |
  1159. // | master | task | * |
  1160. // | master | taskyield | * |
  1161. // | master | barrier | + |
  1162. // | master | taskwait | * |
  1163. // | master | flush | * |
  1164. // | master | ordered | + |
  1165. // | master | atomic | * |
  1166. // | master | target | * |
  1167. // | master | teams | + |
  1168. // +------------------+-----------------+------------------------------------+
  1169. // | critical | parallel | * |
  1170. // | critical | for | + |
  1171. // | critical | for simd | + |
  1172. // | critical | master | * |
  1173. // | critical | critical | * (should have different names) |
  1174. // | critical | simd | * |
  1175. // | critical | sections | + |
  1176. // | critical | section | + |
  1177. // | critical | single | + |
  1178. // | critical | parallel for | * |
  1179. // | critical |parallel for simd| * |
  1180. // | critical |parallel sections| * |
  1181. // | critical | task | * |
  1182. // | critical | taskyield | * |
  1183. // | critical | barrier | + |
  1184. // | critical | taskwait | * |
  1185. // | critical | ordered | + |
  1186. // | critical | atomic | * |
  1187. // | critical | target | * |
  1188. // | critical | teams | + |
  1189. // +------------------+-----------------+------------------------------------+
  1190. // | simd | parallel | |
  1191. // | simd | for | |
  1192. // | simd | for simd | |
  1193. // | simd | master | |
  1194. // | simd | critical | |
  1195. // | simd | simd | |
  1196. // | simd | sections | |
  1197. // | simd | section | |
  1198. // | simd | single | |
  1199. // | simd | parallel for | |
  1200. // | simd |parallel for simd| |
  1201. // | simd |parallel sections| |
  1202. // | simd | task | |
  1203. // | simd | taskyield | |
  1204. // | simd | barrier | |
  1205. // | simd | taskwait | |
  1206. // | simd | flush | |
  1207. // | simd | ordered | |
  1208. // | simd | atomic | |
  1209. // | simd | target | |
  1210. // | simd | teams | |
  1211. // +------------------+-----------------+------------------------------------+
  1212. // | for simd | parallel | |
  1213. // | for simd | for | |
  1214. // | for simd | for simd | |
  1215. // | for simd | master | |
  1216. // | for simd | critical | |
  1217. // | for simd | simd | |
  1218. // | for simd | sections | |
  1219. // | for simd | section | |
  1220. // | for simd | single | |
  1221. // | for simd | parallel for | |
  1222. // | for simd |parallel for simd| |
  1223. // | for simd |parallel sections| |
  1224. // | for simd | task | |
  1225. // | for simd | taskyield | |
  1226. // | for simd | barrier | |
  1227. // | for simd | taskwait | |
  1228. // | for simd | flush | |
  1229. // | for simd | ordered | |
  1230. // | for simd | atomic | |
  1231. // | for simd | target | |
  1232. // | for simd | teams | |
  1233. // +------------------+-----------------+------------------------------------+
  1234. // | parallel for simd| parallel | |
  1235. // | parallel for simd| for | |
  1236. // | parallel for simd| for simd | |
  1237. // | parallel for simd| master | |
  1238. // | parallel for simd| critical | |
  1239. // | parallel for simd| simd | |
  1240. // | parallel for simd| sections | |
  1241. // | parallel for simd| section | |
  1242. // | parallel for simd| single | |
  1243. // | parallel for simd| parallel for | |
  1244. // | parallel for simd|parallel for simd| |
  1245. // | parallel for simd|parallel sections| |
  1246. // | parallel for simd| task | |
  1247. // | parallel for simd| taskyield | |
  1248. // | parallel for simd| barrier | |
  1249. // | parallel for simd| taskwait | |
  1250. // | parallel for simd| flush | |
  1251. // | parallel for simd| ordered | |
  1252. // | parallel for simd| atomic | |
  1253. // | parallel for simd| target | |
  1254. // | parallel for simd| teams | |
  1255. // +------------------+-----------------+------------------------------------+
  1256. // | sections | parallel | * |
  1257. // | sections | for | + |
  1258. // | sections | for simd | + |
  1259. // | sections | master | + |
  1260. // | sections | critical | * |
  1261. // | sections | simd | * |
  1262. // | sections | sections | + |
  1263. // | sections | section | * |
  1264. // | sections | single | + |
  1265. // | sections | parallel for | * |
  1266. // | sections |parallel for simd| * |
  1267. // | sections |parallel sections| * |
  1268. // | sections | task | * |
  1269. // | sections | taskyield | * |
  1270. // | sections | barrier | + |
  1271. // | sections | taskwait | * |
  1272. // | sections | flush | * |
  1273. // | sections | ordered | + |
  1274. // | sections | atomic | * |
  1275. // | sections | target | * |
  1276. // | sections | teams | + |
  1277. // +------------------+-----------------+------------------------------------+
  1278. // | section | parallel | * |
  1279. // | section | for | + |
  1280. // | section | for simd | + |
  1281. // | section | master | + |
  1282. // | section | critical | * |
  1283. // | section | simd | * |
  1284. // | section | sections | + |
  1285. // | section | section | + |
  1286. // | section | single | + |
  1287. // | section | parallel for | * |
  1288. // | section |parallel for simd| * |
  1289. // | section |parallel sections| * |
  1290. // | section | task | * |
  1291. // | section | taskyield | * |
  1292. // | section | barrier | + |
  1293. // | section | taskwait | * |
  1294. // | section | flush | * |
  1295. // | section | ordered | + |
  1296. // | section | atomic | * |
  1297. // | section | target | * |
  1298. // | section | teams | + |
  1299. // +------------------+-----------------+------------------------------------+
  1300. // | single | parallel | * |
  1301. // | single | for | + |
  1302. // | single | for simd | + |
  1303. // | single | master | + |
  1304. // | single | critical | * |
  1305. // | single | simd | * |
  1306. // | single | sections | + |
  1307. // | single | section | + |
  1308. // | single | single | + |
  1309. // | single | parallel for | * |
  1310. // | single |parallel for simd| * |
  1311. // | single |parallel sections| * |
  1312. // | single | task | * |
  1313. // | single | taskyield | * |
  1314. // | single | barrier | + |
  1315. // | single | taskwait | * |
  1316. // | single | flush | * |
  1317. // | single | ordered | + |
  1318. // | single | atomic | * |
  1319. // | single | target | * |
  1320. // | single | teams | + |
  1321. // +------------------+-----------------+------------------------------------+
  1322. // | parallel for | parallel | * |
  1323. // | parallel for | for | + |
  1324. // | parallel for | for simd | + |
  1325. // | parallel for | master | + |
  1326. // | parallel for | critical | * |
  1327. // | parallel for | simd | * |
  1328. // | parallel for | sections | + |
  1329. // | parallel for | section | + |
  1330. // | parallel for | single | + |
  1331. // | parallel for | parallel for | * |
  1332. // | parallel for |parallel for simd| * |
  1333. // | parallel for |parallel sections| * |
  1334. // | parallel for | task | * |
  1335. // | parallel for | taskyield | * |
  1336. // | parallel for | barrier | + |
  1337. // | parallel for | taskwait | * |
  1338. // | parallel for | flush | * |
  1339. // | parallel for | ordered | * (if construct is ordered) |
  1340. // | parallel for | atomic | * |
  1341. // | parallel for | target | * |
  1342. // | parallel for | teams | + |
  1343. // +------------------+-----------------+------------------------------------+
  1344. // | parallel sections| parallel | * |
  1345. // | parallel sections| for | + |
  1346. // | parallel sections| for simd | + |
  1347. // | parallel sections| master | + |
  1348. // | parallel sections| critical | + |
  1349. // | parallel sections| simd | * |
  1350. // | parallel sections| sections | + |
  1351. // | parallel sections| section | * |
  1352. // | parallel sections| single | + |
  1353. // | parallel sections| parallel for | * |
  1354. // | parallel sections|parallel for simd| * |
  1355. // | parallel sections|parallel sections| * |
  1356. // | parallel sections| task | * |
  1357. // | parallel sections| taskyield | * |
  1358. // | parallel sections| barrier | + |
  1359. // | parallel sections| taskwait | * |
  1360. // | parallel sections| flush | * |
  1361. // | parallel sections| ordered | + |
  1362. // | parallel sections| atomic | * |
  1363. // | parallel sections| target | * |
  1364. // | parallel sections| teams | + |
  1365. // +------------------+-----------------+------------------------------------+
  1366. // | task | parallel | * |
  1367. // | task | for | + |
  1368. // | task | for simd | + |
  1369. // | task | master | + |
  1370. // | task | critical | * |
  1371. // | task | simd | * |
  1372. // | task | sections | + |
  1373. // | task | section | + |
  1374. // | task | single | + |
  1375. // | task | parallel for | * |
  1376. // | task |parallel for simd| * |
  1377. // | task |parallel sections| * |
  1378. // | task | task | * |
  1379. // | task | taskyield | * |
  1380. // | task | barrier | + |
  1381. // | task | taskwait | * |
  1382. // | task | flush | * |
  1383. // | task | ordered | + |
  1384. // | task | atomic | * |
  1385. // | task | target | * |
  1386. // | task | teams | + |
  1387. // +------------------+-----------------+------------------------------------+
  1388. // | ordered | parallel | * |
  1389. // | ordered | for | + |
  1390. // | ordered | for simd | + |
  1391. // | ordered | master | * |
  1392. // | ordered | critical | * |
  1393. // | ordered | simd | * |
  1394. // | ordered | sections | + |
  1395. // | ordered | section | + |
  1396. // | ordered | single | + |
  1397. // | ordered | parallel for | * |
  1398. // | ordered |parallel for simd| * |
  1399. // | ordered |parallel sections| * |
  1400. // | ordered | task | * |
  1401. // | ordered | taskyield | * |
  1402. // | ordered | barrier | + |
  1403. // | ordered | taskwait | * |
  1404. // | ordered | flush | * |
  1405. // | ordered | ordered | + |
  1406. // | ordered | atomic | * |
  1407. // | ordered | target | * |
  1408. // | ordered | teams | + |
  1409. // +------------------+-----------------+------------------------------------+
  1410. // | atomic | parallel | |
  1411. // | atomic | for | |
  1412. // | atomic | for simd | |
  1413. // | atomic | master | |
  1414. // | atomic | critical | |
  1415. // | atomic | simd | |
  1416. // | atomic | sections | |
  1417. // | atomic | section | |
  1418. // | atomic | single | |
  1419. // | atomic | parallel for | |
  1420. // | atomic |parallel for simd| |
  1421. // | atomic |parallel sections| |
  1422. // | atomic | task | |
  1423. // | atomic | taskyield | |
  1424. // | atomic | barrier | |
  1425. // | atomic | taskwait | |
  1426. // | atomic | flush | |
  1427. // | atomic | ordered | |
  1428. // | atomic | atomic | |
  1429. // | atomic | target | |
  1430. // | atomic | teams | |
  1431. // +------------------+-----------------+------------------------------------+
  1432. // | target | parallel | * |
  1433. // | target | for | * |
  1434. // | target | for simd | * |
  1435. // | target | master | * |
  1436. // | target | critical | * |
  1437. // | target | simd | * |
  1438. // | target | sections | * |
  1439. // | target | section | * |
  1440. // | target | single | * |
  1441. // | target | parallel for | * |
  1442. // | target |parallel for simd| * |
  1443. // | target |parallel sections| * |
  1444. // | target | task | * |
  1445. // | target | taskyield | * |
  1446. // | target | barrier | * |
  1447. // | target | taskwait | * |
  1448. // | target | flush | * |
  1449. // | target | ordered | * |
  1450. // | target | atomic | * |
  1451. // | target | target | * |
  1452. // | target | teams | * |
  1453. // +------------------+-----------------+------------------------------------+
  1454. // | teams | parallel | * |
  1455. // | teams | for | + |
  1456. // | teams | for simd | + |
  1457. // | teams | master | + |
  1458. // | teams | critical | + |
  1459. // | teams | simd | + |
  1460. // | teams | sections | + |
  1461. // | teams | section | + |
  1462. // | teams | single | + |
  1463. // | teams | parallel for | * |
  1464. // | teams |parallel for simd| * |
  1465. // | teams |parallel sections| * |
  1466. // | teams | task | + |
  1467. // | teams | taskyield | + |
  1468. // | teams | barrier | + |
  1469. // | teams | taskwait | + |
  1470. // | teams | flush | + |
  1471. // | teams | ordered | + |
  1472. // | teams | atomic | + |
  1473. // | teams | target | + |
  1474. // | teams | teams | + |
  1475. // +------------------+-----------------+------------------------------------+
  1476. if (Stack->getCurScope()) {
  1477. auto ParentRegion = Stack->getParentDirective();
  1478. bool NestingProhibited = false;
  1479. bool CloseNesting = true;
  1480. enum {
  1481. NoRecommend,
  1482. ShouldBeInParallelRegion,
  1483. ShouldBeInOrderedRegion,
  1484. ShouldBeInTargetRegion
  1485. } Recommend = NoRecommend;
  1486. if (isOpenMPSimdDirective(ParentRegion)) {
  1487. // OpenMP [2.16, Nesting of Regions]
  1488. // OpenMP constructs may not be nested inside a simd region.
  1489. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  1490. return true;
  1491. }
  1492. if (ParentRegion == OMPD_atomic) {
  1493. // OpenMP [2.16, Nesting of Regions]
  1494. // OpenMP constructs may not be nested inside an atomic region.
  1495. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  1496. return true;
  1497. }
  1498. if (CurrentRegion == OMPD_section) {
  1499. // OpenMP [2.7.2, sections Construct, Restrictions]
  1500. // Orphaned section directives are prohibited. That is, the section
  1501. // directives must appear within the sections construct and must not be
  1502. // encountered elsewhere in the sections region.
  1503. if (ParentRegion != OMPD_sections &&
  1504. ParentRegion != OMPD_parallel_sections) {
  1505. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  1506. << (ParentRegion != OMPD_unknown)
  1507. << getOpenMPDirectiveName(ParentRegion);
  1508. return true;
  1509. }
  1510. return false;
  1511. }
  1512. // Allow some constructs to be orphaned (they could be used in functions,
  1513. // called from OpenMP regions with the required preconditions).
  1514. if (ParentRegion == OMPD_unknown)
  1515. return false;
  1516. if (CurrentRegion == OMPD_master) {
  1517. // OpenMP [2.16, Nesting of Regions]
  1518. // A master region may not be closely nested inside a worksharing,
  1519. // atomic, or explicit task region.
  1520. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  1521. ParentRegion == OMPD_task;
  1522. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  1523. // OpenMP [2.16, Nesting of Regions]
  1524. // A critical region may not be nested (closely or otherwise) inside a
  1525. // critical region with the same name. Note that this restriction is not
  1526. // sufficient to prevent deadlock.
  1527. SourceLocation PreviousCriticalLoc;
  1528. bool DeadLock =
  1529. Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
  1530. OpenMPDirectiveKind K,
  1531. const DeclarationNameInfo &DNI,
  1532. SourceLocation Loc)
  1533. ->bool {
  1534. if (K == OMPD_critical &&
  1535. DNI.getName() == CurrentName.getName()) {
  1536. PreviousCriticalLoc = Loc;
  1537. return true;
  1538. } else
  1539. return false;
  1540. },
  1541. false /* skip top directive */);
  1542. if (DeadLock) {
  1543. SemaRef.Diag(StartLoc,
  1544. diag::err_omp_prohibited_region_critical_same_name)
  1545. << CurrentName.getName();
  1546. if (PreviousCriticalLoc.isValid())
  1547. SemaRef.Diag(PreviousCriticalLoc,
  1548. diag::note_omp_previous_critical_region);
  1549. return true;
  1550. }
  1551. } else if (CurrentRegion == OMPD_barrier) {
  1552. // OpenMP [2.16, Nesting of Regions]
  1553. // A barrier region may not be closely nested inside a worksharing,
  1554. // explicit task, critical, ordered, atomic, or master region.
  1555. NestingProhibited =
  1556. isOpenMPWorksharingDirective(ParentRegion) ||
  1557. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  1558. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  1559. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  1560. !isOpenMPParallelDirective(CurrentRegion)) {
  1561. // OpenMP [2.16, Nesting of Regions]
  1562. // A worksharing region may not be closely nested inside a worksharing,
  1563. // explicit task, critical, ordered, atomic, or master region.
  1564. NestingProhibited =
  1565. isOpenMPWorksharingDirective(ParentRegion) ||
  1566. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  1567. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  1568. Recommend = ShouldBeInParallelRegion;
  1569. } else if (CurrentRegion == OMPD_ordered) {
  1570. // OpenMP [2.16, Nesting of Regions]
  1571. // An ordered region may not be closely nested inside a critical,
  1572. // atomic, or explicit task region.
  1573. // An ordered region must be closely nested inside a loop region (or
  1574. // parallel loop region) with an ordered clause.
  1575. NestingProhibited = ParentRegion == OMPD_critical ||
  1576. ParentRegion == OMPD_task ||
  1577. !Stack->isParentOrderedRegion();
  1578. Recommend = ShouldBeInOrderedRegion;
  1579. } else if (isOpenMPTeamsDirective(CurrentRegion)) {
  1580. // OpenMP [2.16, Nesting of Regions]
  1581. // If specified, a teams construct must be contained within a target
  1582. // construct.
  1583. NestingProhibited = ParentRegion != OMPD_target;
  1584. Recommend = ShouldBeInTargetRegion;
  1585. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  1586. }
  1587. if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
  1588. // OpenMP [2.16, Nesting of Regions]
  1589. // distribute, parallel, parallel sections, parallel workshare, and the
  1590. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  1591. // constructs that can be closely nested in the teams region.
  1592. // TODO: add distribute directive.
  1593. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
  1594. Recommend = ShouldBeInParallelRegion;
  1595. }
  1596. if (NestingProhibited) {
  1597. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  1598. << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
  1599. << getOpenMPDirectiveName(CurrentRegion);
  1600. return true;
  1601. }
  1602. }
  1603. return false;
  1604. }
  1605. StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
  1606. const DeclarationNameInfo &DirName,
  1607. ArrayRef<OMPClause *> Clauses,
  1608. Stmt *AStmt,
  1609. SourceLocation StartLoc,
  1610. SourceLocation EndLoc) {
  1611. StmtResult Res = StmtError();
  1612. if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
  1613. return StmtError();
  1614. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  1615. llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
  1616. bool ErrorFound = false;
  1617. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  1618. if (AStmt) {
  1619. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  1620. // Check default data sharing attributes for referenced variables.
  1621. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  1622. DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
  1623. if (DSAChecker.isErrorFound())
  1624. return StmtError();
  1625. // Generate list of implicitly defined firstprivate variables.
  1626. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  1627. if (!DSAChecker.getImplicitFirstprivate().empty()) {
  1628. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  1629. DSAChecker.getImplicitFirstprivate(), SourceLocation(),
  1630. SourceLocation(), SourceLocation())) {
  1631. ClausesWithImplicit.push_back(Implicit);
  1632. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  1633. DSAChecker.getImplicitFirstprivate().size();
  1634. } else
  1635. ErrorFound = true;
  1636. }
  1637. }
  1638. switch (Kind) {
  1639. case OMPD_parallel:
  1640. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  1641. EndLoc);
  1642. break;
  1643. case OMPD_simd:
  1644. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  1645. VarsWithInheritedDSA);
  1646. break;
  1647. case OMPD_for:
  1648. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  1649. VarsWithInheritedDSA);
  1650. break;
  1651. case OMPD_for_simd:
  1652. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  1653. EndLoc, VarsWithInheritedDSA);
  1654. break;
  1655. case OMPD_sections:
  1656. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  1657. EndLoc);
  1658. break;
  1659. case OMPD_section:
  1660. assert(ClausesWithImplicit.empty() &&
  1661. "No clauses are allowed for 'omp section' directive");
  1662. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  1663. break;
  1664. case OMPD_single:
  1665. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  1666. EndLoc);
  1667. break;
  1668. case OMPD_master:
  1669. assert(ClausesWithImplicit.empty() &&
  1670. "No clauses are allowed for 'omp master' directive");
  1671. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  1672. break;
  1673. case OMPD_critical:
  1674. assert(ClausesWithImplicit.empty() &&
  1675. "No clauses are allowed for 'omp critical' directive");
  1676. Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
  1677. break;
  1678. case OMPD_parallel_for:
  1679. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  1680. EndLoc, VarsWithInheritedDSA);
  1681. break;
  1682. case OMPD_parallel_for_simd:
  1683. Res = ActOnOpenMPParallelForSimdDirective(
  1684. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  1685. break;
  1686. case OMPD_parallel_sections:
  1687. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  1688. StartLoc, EndLoc);
  1689. break;
  1690. case OMPD_task:
  1691. Res =
  1692. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  1693. break;
  1694. case OMPD_taskyield:
  1695. assert(ClausesWithImplicit.empty() &&
  1696. "No clauses are allowed for 'omp taskyield' directive");
  1697. assert(AStmt == nullptr &&
  1698. "No associated statement allowed for 'omp taskyield' directive");
  1699. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  1700. break;
  1701. case OMPD_barrier:
  1702. assert(ClausesWithImplicit.empty() &&
  1703. "No clauses are allowed for 'omp barrier' directive");
  1704. assert(AStmt == nullptr &&
  1705. "No associated statement allowed for 'omp barrier' directive");
  1706. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  1707. break;
  1708. case OMPD_taskwait:
  1709. assert(ClausesWithImplicit.empty() &&
  1710. "No clauses are allowed for 'omp taskwait' directive");
  1711. assert(AStmt == nullptr &&
  1712. "No associated statement allowed for 'omp taskwait' directive");
  1713. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  1714. break;
  1715. case OMPD_flush:
  1716. assert(AStmt == nullptr &&
  1717. "No associated statement allowed for 'omp flush' directive");
  1718. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  1719. break;
  1720. case OMPD_ordered:
  1721. assert(ClausesWithImplicit.empty() &&
  1722. "No clauses are allowed for 'omp ordered' directive");
  1723. Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
  1724. break;
  1725. case OMPD_atomic:
  1726. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  1727. EndLoc);
  1728. break;
  1729. case OMPD_teams:
  1730. Res =
  1731. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  1732. break;
  1733. case OMPD_target:
  1734. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  1735. EndLoc);
  1736. break;
  1737. case OMPD_threadprivate:
  1738. llvm_unreachable("OpenMP Directive is not allowed");
  1739. case OMPD_unknown:
  1740. llvm_unreachable("Unknown OpenMP directive");
  1741. }
  1742. for (auto P : VarsWithInheritedDSA) {
  1743. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  1744. << P.first << P.second->getSourceRange();
  1745. }
  1746. if (!VarsWithInheritedDSA.empty())
  1747. return StmtError();
  1748. if (ErrorFound)
  1749. return StmtError();
  1750. return Res;
  1751. }
  1752. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  1753. Stmt *AStmt,
  1754. SourceLocation StartLoc,
  1755. SourceLocation EndLoc) {
  1756. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  1757. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  1758. // 1.2.2 OpenMP Language Terminology
  1759. // Structured block - An executable statement with a single entry at the
  1760. // top and a single exit at the bottom.
  1761. // The point of exit cannot be a branch out of the structured block.
  1762. // longjmp() and throw() must not violate the entry/exit criteria.
  1763. CS->getCapturedDecl()->setNothrow();
  1764. getCurFunction()->setHasBranchProtectedScope();
  1765. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  1766. AStmt);
  1767. }
  1768. namespace {
  1769. /// \brief Helper class for checking canonical form of the OpenMP loops and
  1770. /// extracting iteration space of each loop in the loop nest, that will be used
  1771. /// for IR generation.
  1772. class OpenMPIterationSpaceChecker {
  1773. /// \brief Reference to Sema.
  1774. Sema &SemaRef;
  1775. /// \brief A location for diagnostics (when there is no some better location).
  1776. SourceLocation DefaultLoc;
  1777. /// \brief A location for diagnostics (when increment is not compatible).
  1778. SourceLocation ConditionLoc;
  1779. /// \brief A source location for referring to loop init later.
  1780. SourceRange InitSrcRange;
  1781. /// \brief A source location for referring to condition later.
  1782. SourceRange ConditionSrcRange;
  1783. /// \brief A source location for referring to increment later.
  1784. SourceRange IncrementSrcRange;
  1785. /// \brief Loop variable.
  1786. VarDecl *Var;
  1787. /// \brief Reference to loop variable.
  1788. DeclRefExpr *VarRef;
  1789. /// \brief Lower bound (initializer for the var).
  1790. Expr *LB;
  1791. /// \brief Upper bound.
  1792. Expr *UB;
  1793. /// \brief Loop step (increment).
  1794. Expr *Step;
  1795. /// \brief This flag is true when condition is one of:
  1796. /// Var < UB
  1797. /// Var <= UB
  1798. /// UB > Var
  1799. /// UB >= Var
  1800. bool TestIsLessOp;
  1801. /// \brief This flag is true when condition is strict ( < or > ).
  1802. bool TestIsStrictOp;
  1803. /// \brief This flag is true when step is subtracted on each iteration.
  1804. bool SubtractStep;
  1805. public:
  1806. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  1807. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
  1808. InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
  1809. IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
  1810. LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
  1811. TestIsStrictOp(false), SubtractStep(false) {}
  1812. /// \brief Check init-expr for canonical loop form and save loop counter
  1813. /// variable - #Var and its initialization value - #LB.
  1814. bool CheckInit(Stmt *S);
  1815. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  1816. /// for less/greater and for strict/non-strict comparison.
  1817. bool CheckCond(Expr *S);
  1818. /// \brief Check incr-expr for canonical loop form and return true if it
  1819. /// does not conform, otherwise save loop step (#Step).
  1820. bool CheckInc(Expr *S);
  1821. /// \brief Return the loop counter variable.
  1822. VarDecl *GetLoopVar() const { return Var; }
  1823. /// \brief Return the reference expression to loop counter variable.
  1824. DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
  1825. /// \brief Source range of the loop init.
  1826. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  1827. /// \brief Source range of the loop condition.
  1828. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  1829. /// \brief Source range of the loop increment.
  1830. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  1831. /// \brief True if the step should be subtracted.
  1832. bool ShouldSubtractStep() const { return SubtractStep; }
  1833. /// \brief Build the expression to calculate the number of iterations.
  1834. Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
  1835. /// \brief Build reference expression to the counter be used for codegen.
  1836. Expr *BuildCounterVar() const;
  1837. /// \brief Build initization of the counter be used for codegen.
  1838. Expr *BuildCounterInit() const;
  1839. /// \brief Build step of the counter be used for codegen.
  1840. Expr *BuildCounterStep() const;
  1841. /// \brief Return true if any expression is dependent.
  1842. bool Dependent() const;
  1843. private:
  1844. /// \brief Check the right-hand side of an assignment in the increment
  1845. /// expression.
  1846. bool CheckIncRHS(Expr *RHS);
  1847. /// \brief Helper to set loop counter variable and its initializer.
  1848. bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
  1849. /// \brief Helper to set upper bound.
  1850. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
  1851. const SourceLocation &SL);
  1852. /// \brief Helper to set loop increment.
  1853. bool SetStep(Expr *NewStep, bool Subtract);
  1854. };
  1855. bool OpenMPIterationSpaceChecker::Dependent() const {
  1856. if (!Var) {
  1857. assert(!LB && !UB && !Step);
  1858. return false;
  1859. }
  1860. return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
  1861. (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
  1862. }
  1863. bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
  1864. DeclRefExpr *NewVarRefExpr,
  1865. Expr *NewLB) {
  1866. // State consistency checking to ensure correct usage.
  1867. assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
  1868. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  1869. if (!NewVar || !NewLB)
  1870. return true;
  1871. Var = NewVar;
  1872. VarRef = NewVarRefExpr;
  1873. LB = NewLB;
  1874. return false;
  1875. }
  1876. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  1877. const SourceRange &SR,
  1878. const SourceLocation &SL) {
  1879. // State consistency checking to ensure correct usage.
  1880. assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
  1881. !TestIsLessOp && !TestIsStrictOp);
  1882. if (!NewUB)
  1883. return true;
  1884. UB = NewUB;
  1885. TestIsLessOp = LessOp;
  1886. TestIsStrictOp = StrictOp;
  1887. ConditionSrcRange = SR;
  1888. ConditionLoc = SL;
  1889. return false;
  1890. }
  1891. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  1892. // State consistency checking to ensure correct usage.
  1893. assert(Var != nullptr && LB != nullptr && Step == nullptr);
  1894. if (!NewStep)
  1895. return true;
  1896. if (!NewStep->isValueDependent()) {
  1897. // Check that the step is integer expression.
  1898. SourceLocation StepLoc = NewStep->getLocStart();
  1899. ExprResult Val =
  1900. SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
  1901. if (Val.isInvalid())
  1902. return true;
  1903. NewStep = Val.get();
  1904. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  1905. // If test-expr is of form var relational-op b and relational-op is < or
  1906. // <= then incr-expr must cause var to increase on each iteration of the
  1907. // loop. If test-expr is of form var relational-op b and relational-op is
  1908. // > or >= then incr-expr must cause var to decrease on each iteration of
  1909. // the loop.
  1910. // If test-expr is of form b relational-op var and relational-op is < or
  1911. // <= then incr-expr must cause var to decrease on each iteration of the
  1912. // loop. If test-expr is of form b relational-op var and relational-op is
  1913. // > or >= then incr-expr must cause var to increase on each iteration of
  1914. // the loop.
  1915. llvm::APSInt Result;
  1916. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  1917. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  1918. bool IsConstNeg =
  1919. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  1920. bool IsConstPos =
  1921. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  1922. bool IsConstZero = IsConstant && !Result.getBoolValue();
  1923. if (UB && (IsConstZero ||
  1924. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  1925. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  1926. SemaRef.Diag(NewStep->getExprLoc(),
  1927. diag::err_omp_loop_incr_not_compatible)
  1928. << Var << TestIsLessOp << NewStep->getSourceRange();
  1929. SemaRef.Diag(ConditionLoc,
  1930. diag::note_omp_loop_cond_requres_compatible_incr)
  1931. << TestIsLessOp << ConditionSrcRange;
  1932. return true;
  1933. }
  1934. if (TestIsLessOp == Subtract) {
  1935. NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
  1936. NewStep).get();
  1937. Subtract = !Subtract;
  1938. }
  1939. }
  1940. Step = NewStep;
  1941. SubtractStep = Subtract;
  1942. return false;
  1943. }
  1944. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
  1945. // Check init-expr for canonical loop form and save loop counter
  1946. // variable - #Var and its initialization value - #LB.
  1947. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  1948. // var = lb
  1949. // integer-type var = lb
  1950. // random-access-iterator-type var = lb
  1951. // pointer-type var = lb
  1952. //
  1953. if (!S) {
  1954. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  1955. return true;
  1956. }
  1957. InitSrcRange = S->getSourceRange();
  1958. if (Expr *E = dyn_cast<Expr>(S))
  1959. S = E->IgnoreParens();
  1960. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  1961. if (BO->getOpcode() == BO_Assign)
  1962. if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
  1963. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  1964. BO->getRHS());
  1965. } else if (auto DS = dyn_cast<DeclStmt>(S)) {
  1966. if (DS->isSingleDecl()) {
  1967. if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  1968. if (Var->hasInit()) {
  1969. // Accept non-canonical init form here but emit ext. warning.
  1970. if (Var->getInitStyle() != VarDecl::CInit)
  1971. SemaRef.Diag(S->getLocStart(),
  1972. diag::ext_omp_loop_not_canonical_init)
  1973. << S->getSourceRange();
  1974. return SetVarAndLB(Var, nullptr, Var->getInit());
  1975. }
  1976. }
  1977. }
  1978. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
  1979. if (CE->getOperator() == OO_Equal)
  1980. if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
  1981. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  1982. CE->getArg(1));
  1983. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  1984. << S->getSourceRange();
  1985. return true;
  1986. }
  1987. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  1988. /// variable (which may be the loop variable) if possible.
  1989. static const VarDecl *GetInitVarDecl(const Expr *E) {
  1990. if (!E)
  1991. return nullptr;
  1992. E = E->IgnoreParenImpCasts();
  1993. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  1994. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  1995. if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
  1996. CE->getArg(0) != nullptr)
  1997. E = CE->getArg(0)->IgnoreParenImpCasts();
  1998. auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
  1999. if (!DRE)
  2000. return nullptr;
  2001. return dyn_cast<VarDecl>(DRE->getDecl());
  2002. }
  2003. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  2004. // Check test-expr for canonical form, save upper-bound UB, flags for
  2005. // less/greater and for strict/non-strict comparison.
  2006. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2007. // var relational-op b
  2008. // b relational-op var
  2009. //
  2010. if (!S) {
  2011. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
  2012. return true;
  2013. }
  2014. S = S->IgnoreParenImpCasts();
  2015. SourceLocation CondLoc = S->getLocStart();
  2016. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2017. if (BO->isRelationalOp()) {
  2018. if (GetInitVarDecl(BO->getLHS()) == Var)
  2019. return SetUB(BO->getRHS(),
  2020. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  2021. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2022. BO->getSourceRange(), BO->getOperatorLoc());
  2023. if (GetInitVarDecl(BO->getRHS()) == Var)
  2024. return SetUB(BO->getLHS(),
  2025. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  2026. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  2027. BO->getSourceRange(), BO->getOperatorLoc());
  2028. }
  2029. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2030. if (CE->getNumArgs() == 2) {
  2031. auto Op = CE->getOperator();
  2032. switch (Op) {
  2033. case OO_Greater:
  2034. case OO_GreaterEqual:
  2035. case OO_Less:
  2036. case OO_LessEqual:
  2037. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2038. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  2039. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2040. CE->getOperatorLoc());
  2041. if (GetInitVarDecl(CE->getArg(1)) == Var)
  2042. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  2043. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  2044. CE->getOperatorLoc());
  2045. break;
  2046. default:
  2047. break;
  2048. }
  2049. }
  2050. }
  2051. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  2052. << S->getSourceRange() << Var;
  2053. return true;
  2054. }
  2055. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  2056. // RHS of canonical loop form increment can be:
  2057. // var + incr
  2058. // incr + var
  2059. // var - incr
  2060. //
  2061. RHS = RHS->IgnoreParenImpCasts();
  2062. if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
  2063. if (BO->isAdditiveOp()) {
  2064. bool IsAdd = BO->getOpcode() == BO_Add;
  2065. if (GetInitVarDecl(BO->getLHS()) == Var)
  2066. return SetStep(BO->getRHS(), !IsAdd);
  2067. if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
  2068. return SetStep(BO->getLHS(), false);
  2069. }
  2070. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  2071. bool IsAdd = CE->getOperator() == OO_Plus;
  2072. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  2073. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2074. return SetStep(CE->getArg(1), !IsAdd);
  2075. if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
  2076. return SetStep(CE->getArg(0), false);
  2077. }
  2078. }
  2079. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2080. << RHS->getSourceRange() << Var;
  2081. return true;
  2082. }
  2083. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  2084. // Check incr-expr for canonical loop form and return true if it
  2085. // does not conform.
  2086. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  2087. // ++var
  2088. // var++
  2089. // --var
  2090. // var--
  2091. // var += incr
  2092. // var -= incr
  2093. // var = var + incr
  2094. // var = incr + var
  2095. // var = var - incr
  2096. //
  2097. if (!S) {
  2098. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
  2099. return true;
  2100. }
  2101. IncrementSrcRange = S->getSourceRange();
  2102. S = S->IgnoreParens();
  2103. if (auto UO = dyn_cast<UnaryOperator>(S)) {
  2104. if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
  2105. return SetStep(
  2106. SemaRef.ActOnIntegerConstant(UO->getLocStart(),
  2107. (UO->isDecrementOp() ? -1 : 1)).get(),
  2108. false);
  2109. } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
  2110. switch (BO->getOpcode()) {
  2111. case BO_AddAssign:
  2112. case BO_SubAssign:
  2113. if (GetInitVarDecl(BO->getLHS()) == Var)
  2114. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  2115. break;
  2116. case BO_Assign:
  2117. if (GetInitVarDecl(BO->getLHS()) == Var)
  2118. return CheckIncRHS(BO->getRHS());
  2119. break;
  2120. default:
  2121. break;
  2122. }
  2123. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  2124. switch (CE->getOperator()) {
  2125. case OO_PlusPlus:
  2126. case OO_MinusMinus:
  2127. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2128. return SetStep(
  2129. SemaRef.ActOnIntegerConstant(
  2130. CE->getLocStart(),
  2131. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
  2132. false);
  2133. break;
  2134. case OO_PlusEqual:
  2135. case OO_MinusEqual:
  2136. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2137. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  2138. break;
  2139. case OO_Equal:
  2140. if (GetInitVarDecl(CE->getArg(0)) == Var)
  2141. return CheckIncRHS(CE->getArg(1));
  2142. break;
  2143. default:
  2144. break;
  2145. }
  2146. }
  2147. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  2148. << S->getSourceRange() << Var;
  2149. return true;
  2150. }
  2151. /// \brief Build the expression to calculate the number of iterations.
  2152. Expr *
  2153. OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
  2154. const bool LimitedType) const {
  2155. ExprResult Diff;
  2156. if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
  2157. SemaRef.getLangOpts().CPlusPlus) {
  2158. // Upper - Lower
  2159. Expr *Upper = TestIsLessOp ? UB : LB;
  2160. Expr *Lower = TestIsLessOp ? LB : UB;
  2161. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  2162. if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
  2163. // BuildBinOp already emitted error, this one is to point user to upper
  2164. // and lower bound, and to tell what is passed to 'operator-'.
  2165. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  2166. << Upper->getSourceRange() << Lower->getSourceRange();
  2167. return nullptr;
  2168. }
  2169. }
  2170. if (!Diff.isUsable())
  2171. return nullptr;
  2172. // Upper - Lower [- 1]
  2173. if (TestIsStrictOp)
  2174. Diff = SemaRef.BuildBinOp(
  2175. S, DefaultLoc, BO_Sub, Diff.get(),
  2176. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  2177. if (!Diff.isUsable())
  2178. return nullptr;
  2179. // Upper - Lower [- 1] + Step
  2180. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
  2181. Step->IgnoreImplicit());
  2182. if (!Diff.isUsable())
  2183. return nullptr;
  2184. // Parentheses (for dumping/debugging purposes only).
  2185. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  2186. if (!Diff.isUsable())
  2187. return nullptr;
  2188. // (Upper - Lower [- 1] + Step) / Step
  2189. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
  2190. Step->IgnoreImplicit());
  2191. if (!Diff.isUsable())
  2192. return nullptr;
  2193. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  2194. if (LimitedType) {
  2195. auto &C = SemaRef.Context;
  2196. QualType Type = Diff.get()->getType();
  2197. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  2198. if (NewSize != C.getTypeSize(Type)) {
  2199. if (NewSize < C.getTypeSize(Type)) {
  2200. assert(NewSize == 64 && "incorrect loop var size");
  2201. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  2202. << InitSrcRange << ConditionSrcRange;
  2203. }
  2204. QualType NewType = C.getIntTypeForBitwidth(
  2205. NewSize, Type->hasSignedIntegerRepresentation());
  2206. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  2207. Sema::AA_Converting, true);
  2208. if (!Diff.isUsable())
  2209. return nullptr;
  2210. }
  2211. }
  2212. return Diff.get();
  2213. }
  2214. /// \brief Build reference expression to the counter be used for codegen.
  2215. Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
  2216. return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  2217. GetIncrementSrcRange().getBegin(), Var, false,
  2218. DefaultLoc, Var->getType(), VK_LValue);
  2219. }
  2220. /// \brief Build initization of the counter be used for codegen.
  2221. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  2222. /// \brief Build step of the counter be used for codegen.
  2223. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  2224. /// \brief Iteration space of a single for loop.
  2225. struct LoopIterationSpace {
  2226. /// \brief This expression calculates the number of iterations in the loop.
  2227. /// It is always possible to calculate it before starting the loop.
  2228. Expr *NumIterations;
  2229. /// \brief The loop counter variable.
  2230. Expr *CounterVar;
  2231. /// \brief This is initializer for the initial value of #CounterVar.
  2232. Expr *CounterInit;
  2233. /// \brief This is step for the #CounterVar used to generate its update:
  2234. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  2235. Expr *CounterStep;
  2236. /// \brief Should step be subtracted?
  2237. bool Subtract;
  2238. /// \brief Source range of the loop init.
  2239. SourceRange InitSrcRange;
  2240. /// \brief Source range of the loop condition.
  2241. SourceRange CondSrcRange;
  2242. /// \brief Source range of the loop increment.
  2243. SourceRange IncSrcRange;
  2244. };
  2245. } // namespace
  2246. /// \brief Called on a for stmt to check and extract its iteration space
  2247. /// for further processing (such as collapsing).
  2248. static bool CheckOpenMPIterationSpace(
  2249. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  2250. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  2251. Expr *NestedLoopCountExpr,
  2252. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  2253. LoopIterationSpace &ResultIterSpace) {
  2254. // OpenMP [2.6, Canonical Loop Form]
  2255. // for (init-expr; test-expr; incr-expr) structured-block
  2256. auto For = dyn_cast_or_null<ForStmt>(S);
  2257. if (!For) {
  2258. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  2259. << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
  2260. << NestedLoopCount << (CurrentNestedLoopCount > 0)
  2261. << CurrentNestedLoopCount;
  2262. if (NestedLoopCount > 1)
  2263. SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
  2264. diag::note_omp_collapse_expr)
  2265. << NestedLoopCountExpr->getSourceRange();
  2266. return true;
  2267. }
  2268. assert(For->getBody());
  2269. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  2270. // Check init.
  2271. auto Init = For->getInit();
  2272. if (ISC.CheckInit(Init)) {
  2273. return true;
  2274. }
  2275. bool HasErrors = false;
  2276. // Check loop variable's type.
  2277. auto Var = ISC.GetLoopVar();
  2278. // OpenMP [2.6, Canonical Loop Form]
  2279. // Var is one of the following:
  2280. // A variable of signed or unsigned integer type.
  2281. // For C++, a variable of a random access iterator type.
  2282. // For C, a variable of a pointer type.
  2283. auto VarType = Var->getType();
  2284. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  2285. !VarType->isPointerType() &&
  2286. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  2287. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  2288. << SemaRef.getLangOpts().CPlusPlus;
  2289. HasErrors = true;
  2290. }
  2291. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
  2292. // Construct
  2293. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  2294. // parallel for construct is (are) private.
  2295. // The loop iteration variable in the associated for-loop of a simd construct
  2296. // with just one associated for-loop is linear with a constant-linear-step
  2297. // that is the increment of the associated for-loop.
  2298. // Exclude loop var from the list of variables with implicitly defined data
  2299. // sharing attributes.
  2300. VarsWithImplicitDSA.erase(Var);
  2301. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
  2302. // a Construct, C/C++].
  2303. // The loop iteration variable in the associated for-loop of a simd construct
  2304. // with just one associated for-loop may be listed in a linear clause with a
  2305. // constant-linear-step that is the increment of the associated for-loop.
  2306. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  2307. // parallel for construct may be listed in a private or lastprivate clause.
  2308. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
  2309. auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
  2310. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  2311. // declared in the loop and it is predetermined as a private.
  2312. auto PredeterminedCKind =
  2313. isOpenMPSimdDirective(DKind)
  2314. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  2315. : OMPC_private;
  2316. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  2317. DVar.CKind != PredeterminedCKind) ||
  2318. (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
  2319. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
  2320. DVar.CKind != OMPC_lastprivate)) &&
  2321. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  2322. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  2323. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  2324. << getOpenMPClauseName(PredeterminedCKind);
  2325. ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
  2326. HasErrors = true;
  2327. } else if (LoopVarRefExpr != nullptr) {
  2328. // Make the loop iteration variable private (for worksharing constructs),
  2329. // linear (for simd directives with the only one associated loop) or
  2330. // lastprivate (for simd directives with several collapsed loops).
  2331. // FIXME: the next check and error message must be removed once the
  2332. // capturing of global variables in loops is fixed.
  2333. if (DVar.CKind == OMPC_unknown)
  2334. DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
  2335. /*FromParent=*/false);
  2336. if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
  2337. SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
  2338. << getOpenMPClauseName(PredeterminedCKind)
  2339. << getOpenMPDirectiveName(DKind);
  2340. HasErrors = true;
  2341. } else
  2342. DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
  2343. }
  2344. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  2345. // Check test-expr.
  2346. HasErrors |= ISC.CheckCond(For->getCond());
  2347. // Check incr-expr.
  2348. HasErrors |= ISC.CheckInc(For->getInc());
  2349. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  2350. return HasErrors;
  2351. // Build the loop's iteration space representation.
  2352. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  2353. DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
  2354. ResultIterSpace.CounterVar = ISC.BuildCounterVar();
  2355. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  2356. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  2357. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  2358. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  2359. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  2360. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  2361. HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
  2362. ResultIterSpace.CounterVar == nullptr ||
  2363. ResultIterSpace.CounterInit == nullptr ||
  2364. ResultIterSpace.CounterStep == nullptr);
  2365. return HasErrors;
  2366. }
  2367. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  2368. static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  2369. StringRef Name) {
  2370. DeclContext *DC = SemaRef.CurContext;
  2371. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  2372. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  2373. VarDecl *Decl =
  2374. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  2375. Decl->setImplicit();
  2376. return Decl;
  2377. }
  2378. /// \brief Build 'VarRef = Start + Iter * Step'.
  2379. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
  2380. SourceLocation Loc, ExprResult VarRef,
  2381. ExprResult Start, ExprResult Iter,
  2382. ExprResult Step, bool Subtract) {
  2383. // Add parentheses (for debugging purposes only).
  2384. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  2385. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  2386. !Step.isUsable())
  2387. return ExprError();
  2388. ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
  2389. Step.get()->IgnoreImplicit());
  2390. if (!Update.isUsable())
  2391. return ExprError();
  2392. // Build 'VarRef = Start + Iter * Step'.
  2393. Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
  2394. Start.get()->IgnoreImplicit(), Update.get());
  2395. if (!Update.isUsable())
  2396. return ExprError();
  2397. Update = SemaRef.PerformImplicitConversion(
  2398. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  2399. if (!Update.isUsable())
  2400. return ExprError();
  2401. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  2402. return Update;
  2403. }
  2404. /// \brief Convert integer expression \a E to make it have at least \a Bits
  2405. /// bits.
  2406. static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
  2407. Sema &SemaRef) {
  2408. if (E == nullptr)
  2409. return ExprError();
  2410. auto &C = SemaRef.Context;
  2411. QualType OldType = E->getType();
  2412. unsigned HasBits = C.getTypeSize(OldType);
  2413. if (HasBits >= Bits)
  2414. return ExprResult(E);
  2415. // OK to convert to signed, because new type has more bits than old.
  2416. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  2417. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  2418. true);
  2419. }
  2420. /// \brief Check if the given expression \a E is a constant integer that fits
  2421. /// into \a Bits bits.
  2422. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  2423. if (E == nullptr)
  2424. return false;
  2425. llvm::APSInt Result;
  2426. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  2427. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  2428. return false;
  2429. }
  2430. /// \brief Called on a for stmt to check itself and nested loops (if any).
  2431. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  2432. /// number of collapsed loops otherwise.
  2433. static unsigned
  2434. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
  2435. Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
  2436. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
  2437. OMPLoopDirective::HelperExprs &Built) {
  2438. unsigned NestedLoopCount = 1;
  2439. if (NestedLoopCountExpr) {
  2440. // Found 'collapse' clause - calculate collapse number.
  2441. llvm::APSInt Result;
  2442. if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  2443. NestedLoopCount = Result.getLimitedValue();
  2444. }
  2445. // This is helper routine for loop directives (e.g., 'for', 'simd',
  2446. // 'for simd', etc.).
  2447. SmallVector<LoopIterationSpace, 4> IterSpaces;
  2448. IterSpaces.resize(NestedLoopCount);
  2449. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  2450. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  2451. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  2452. NestedLoopCount, NestedLoopCountExpr,
  2453. VarsWithImplicitDSA, IterSpaces[Cnt]))
  2454. return 0;
  2455. // Move on to the next nested for loop, or to the loop body.
  2456. // OpenMP [2.8.1, simd construct, Restrictions]
  2457. // All loops associated with the construct must be perfectly nested; that
  2458. // is, there must be no intervening code nor any OpenMP directive between
  2459. // any two loops.
  2460. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  2461. }
  2462. Built.clear(/* size */ NestedLoopCount);
  2463. if (SemaRef.CurContext->isDependentContext())
  2464. return NestedLoopCount;
  2465. // An example of what is generated for the following code:
  2466. //
  2467. // #pragma omp simd collapse(2)
  2468. // for (i = 0; i < NI; ++i)
  2469. // for (j = J0; j < NJ; j+=2) {
  2470. // <loop body>
  2471. // }
  2472. //
  2473. // We generate the code below.
  2474. // Note: the loop body may be outlined in CodeGen.
  2475. // Note: some counters may be C++ classes, operator- is used to find number of
  2476. // iterations and operator+= to calculate counter value.
  2477. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  2478. // or i64 is currently supported).
  2479. //
  2480. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  2481. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  2482. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  2483. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  2484. // // similar updates for vars in clauses (e.g. 'linear')
  2485. // <loop body (using local i and j)>
  2486. // }
  2487. // i = NI; // assign final values of counters
  2488. // j = NJ;
  2489. //
  2490. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  2491. // the iteration counts of the collapsed for loops.
  2492. auto N0 = IterSpaces[0].NumIterations;
  2493. ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
  2494. ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
  2495. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  2496. return NestedLoopCount;
  2497. auto &C = SemaRef.Context;
  2498. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  2499. Scope *CurScope = DSA.getCurScope();
  2500. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  2501. auto N = IterSpaces[Cnt].NumIterations;
  2502. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  2503. if (LastIteration32.isUsable())
  2504. LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
  2505. LastIteration32.get(), N);
  2506. if (LastIteration64.isUsable())
  2507. LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
  2508. LastIteration64.get(), N);
  2509. }
  2510. // Choose either the 32-bit or 64-bit version.
  2511. ExprResult LastIteration = LastIteration64;
  2512. if (LastIteration32.isUsable() &&
  2513. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  2514. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  2515. FitsInto(
  2516. 32 /* Bits */,
  2517. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  2518. LastIteration64.get(), SemaRef)))
  2519. LastIteration = LastIteration32;
  2520. if (!LastIteration.isUsable())
  2521. return 0;
  2522. // Save the number of iterations.
  2523. ExprResult NumIterations = LastIteration;
  2524. {
  2525. LastIteration = SemaRef.BuildBinOp(
  2526. CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
  2527. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  2528. if (!LastIteration.isUsable())
  2529. return 0;
  2530. }
  2531. // Calculate the last iteration number beforehand instead of doing this on
  2532. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  2533. llvm::APSInt Result;
  2534. bool IsConstant =
  2535. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  2536. ExprResult CalcLastIteration;
  2537. if (!IsConstant) {
  2538. SourceLocation SaveLoc;
  2539. VarDecl *SaveVar =
  2540. BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
  2541. ".omp.last.iteration");
  2542. ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
  2543. SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
  2544. CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
  2545. SaveRef.get(), LastIteration.get());
  2546. LastIteration = SaveRef;
  2547. // Prepare SaveRef + 1.
  2548. NumIterations = SemaRef.BuildBinOp(
  2549. CurScope, SaveLoc, BO_Add, SaveRef.get(),
  2550. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  2551. if (!NumIterations.isUsable())
  2552. return 0;
  2553. }
  2554. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  2555. // Precondition tests if there is at least one iteration (LastIteration > 0).
  2556. ExprResult PreCond = SemaRef.BuildBinOp(
  2557. CurScope, InitLoc, BO_GT, LastIteration.get(),
  2558. SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
  2559. QualType VType = LastIteration.get()->getType();
  2560. // Build variables passed into runtime, nesessary for worksharing directives.
  2561. ExprResult LB, UB, IL, ST, EUB;
  2562. if (isOpenMPWorksharingDirective(DKind)) {
  2563. // Lower bound variable, initialized with zero.
  2564. VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  2565. LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
  2566. SemaRef.AddInitializerToDecl(
  2567. LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  2568. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  2569. // Upper bound variable, initialized with last iteration number.
  2570. VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  2571. UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
  2572. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  2573. /*DirectInit*/ false,
  2574. /*TypeMayContainAuto*/ false);
  2575. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  2576. // This will be used to implement clause 'lastprivate'.
  2577. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  2578. VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  2579. IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
  2580. SemaRef.AddInitializerToDecl(
  2581. ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  2582. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  2583. // Stride variable returned by runtime (we initialize it to 1 by default).
  2584. VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
  2585. ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
  2586. SemaRef.AddInitializerToDecl(
  2587. STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  2588. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  2589. // Build expression: UB = min(UB, LastIteration)
  2590. // It is nesessary for CodeGen of directives with static scheduling.
  2591. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  2592. UB.get(), LastIteration.get());
  2593. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  2594. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  2595. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  2596. CondOp.get());
  2597. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  2598. }
  2599. // Build the iteration variable and its initialization before loop.
  2600. ExprResult IV;
  2601. ExprResult Init;
  2602. {
  2603. VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
  2604. IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
  2605. Expr *RHS = isOpenMPWorksharingDirective(DKind)
  2606. ? LB.get()
  2607. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  2608. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  2609. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  2610. }
  2611. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  2612. SourceLocation CondLoc;
  2613. ExprResult Cond =
  2614. isOpenMPWorksharingDirective(DKind)
  2615. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  2616. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  2617. NumIterations.get());
  2618. // Loop condition with 1 iteration separated (IV < LastIteration)
  2619. ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
  2620. IV.get(), LastIteration.get());
  2621. // Loop increment (IV = IV + 1)
  2622. SourceLocation IncLoc;
  2623. ExprResult Inc =
  2624. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  2625. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  2626. if (!Inc.isUsable())
  2627. return 0;
  2628. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  2629. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  2630. if (!Inc.isUsable())
  2631. return 0;
  2632. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  2633. // Used for directives with static scheduling.
  2634. ExprResult NextLB, NextUB;
  2635. if (isOpenMPWorksharingDirective(DKind)) {
  2636. // LB + ST
  2637. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  2638. if (!NextLB.isUsable())
  2639. return 0;
  2640. // LB = LB + ST
  2641. NextLB =
  2642. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  2643. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  2644. if (!NextLB.isUsable())
  2645. return 0;
  2646. // UB + ST
  2647. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  2648. if (!NextUB.isUsable())
  2649. return 0;
  2650. // UB = UB + ST
  2651. NextUB =
  2652. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  2653. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  2654. if (!NextUB.isUsable())
  2655. return 0;
  2656. }
  2657. // Build updates and final values of the loop counters.
  2658. bool HasErrors = false;
  2659. Built.Counters.resize(NestedLoopCount);
  2660. Built.Updates.resize(NestedLoopCount);
  2661. Built.Finals.resize(NestedLoopCount);
  2662. {
  2663. ExprResult Div;
  2664. // Go from inner nested loop to outer.
  2665. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  2666. LoopIterationSpace &IS = IterSpaces[Cnt];
  2667. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  2668. // Build: Iter = (IV / Div) % IS.NumIters
  2669. // where Div is product of previous iterations' IS.NumIters.
  2670. ExprResult Iter;
  2671. if (Div.isUsable()) {
  2672. Iter =
  2673. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  2674. } else {
  2675. Iter = IV;
  2676. assert((Cnt == (int)NestedLoopCount - 1) &&
  2677. "unusable div expected on first iteration only");
  2678. }
  2679. if (Cnt != 0 && Iter.isUsable())
  2680. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  2681. IS.NumIterations);
  2682. if (!Iter.isUsable()) {
  2683. HasErrors = true;
  2684. break;
  2685. }
  2686. // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
  2687. ExprResult Update =
  2688. BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
  2689. IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
  2690. if (!Update.isUsable()) {
  2691. HasErrors = true;
  2692. break;
  2693. }
  2694. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  2695. ExprResult Final = BuildCounterUpdate(
  2696. SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
  2697. IS.NumIterations, IS.CounterStep, IS.Subtract);
  2698. if (!Final.isUsable()) {
  2699. HasErrors = true;
  2700. break;
  2701. }
  2702. // Build Div for the next iteration: Div <- Div * IS.NumIters
  2703. if (Cnt != 0) {
  2704. if (Div.isUnset())
  2705. Div = IS.NumIterations;
  2706. else
  2707. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  2708. IS.NumIterations);
  2709. // Add parentheses (for debugging purposes only).
  2710. if (Div.isUsable())
  2711. Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
  2712. if (!Div.isUsable()) {
  2713. HasErrors = true;
  2714. break;
  2715. }
  2716. }
  2717. if (!Update.isUsable() || !Final.isUsable()) {
  2718. HasErrors = true;
  2719. break;
  2720. }
  2721. // Save results
  2722. Built.Counters[Cnt] = IS.CounterVar;
  2723. Built.Updates[Cnt] = Update.get();
  2724. Built.Finals[Cnt] = Final.get();
  2725. }
  2726. }
  2727. if (HasErrors)
  2728. return 0;
  2729. // Save results
  2730. Built.IterationVarRef = IV.get();
  2731. Built.LastIteration = LastIteration.get();
  2732. Built.CalcLastIteration = CalcLastIteration.get();
  2733. Built.PreCond = PreCond.get();
  2734. Built.Cond = Cond.get();
  2735. Built.SeparatedCond = SeparatedCond.get();
  2736. Built.Init = Init.get();
  2737. Built.Inc = Inc.get();
  2738. Built.LB = LB.get();
  2739. Built.UB = UB.get();
  2740. Built.IL = IL.get();
  2741. Built.ST = ST.get();
  2742. Built.EUB = EUB.get();
  2743. Built.NLB = NextLB.get();
  2744. Built.NUB = NextUB.get();
  2745. return NestedLoopCount;
  2746. }
  2747. static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  2748. auto CollapseFilter = [](const OMPClause *C) -> bool {
  2749. return C->getClauseKind() == OMPC_collapse;
  2750. };
  2751. OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
  2752. Clauses, CollapseFilter);
  2753. if (I)
  2754. return cast<OMPCollapseClause>(*I)->getNumForLoops();
  2755. return nullptr;
  2756. }
  2757. StmtResult Sema::ActOnOpenMPSimdDirective(
  2758. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  2759. SourceLocation EndLoc,
  2760. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  2761. OMPLoopDirective::HelperExprs B;
  2762. // In presence of clause 'collapse', it will define the nested loops number.
  2763. unsigned NestedLoopCount =
  2764. CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
  2765. *DSAStack, VarsWithImplicitDSA, B);
  2766. if (NestedLoopCount == 0)
  2767. return StmtError();
  2768. assert((CurContext->isDependentContext() || B.builtAll()) &&
  2769. "omp simd loop exprs were not built");
  2770. getCurFunction()->setHasBranchProtectedScope();
  2771. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  2772. Clauses, AStmt, B);
  2773. }
  2774. StmtResult Sema::ActOnOpenMPForDirective(
  2775. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  2776. SourceLocation EndLoc,
  2777. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  2778. OMPLoopDirective::HelperExprs B;
  2779. // In presence of clause 'collapse', it will define the nested loops number.
  2780. unsigned NestedLoopCount =
  2781. CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
  2782. *DSAStack, VarsWithImplicitDSA, B);
  2783. if (NestedLoopCount == 0)
  2784. return StmtError();
  2785. assert((CurContext->isDependentContext() || B.builtAll()) &&
  2786. "omp for loop exprs were not built");
  2787. getCurFunction()->setHasBranchProtectedScope();
  2788. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  2789. Clauses, AStmt, B);
  2790. }
  2791. StmtResult Sema::ActOnOpenMPForSimdDirective(
  2792. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  2793. SourceLocation EndLoc,
  2794. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  2795. OMPLoopDirective::HelperExprs B;
  2796. // In presence of clause 'collapse', it will define the nested loops number.
  2797. unsigned NestedLoopCount =
  2798. CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
  2799. *this, *DSAStack, VarsWithImplicitDSA, B);
  2800. if (NestedLoopCount == 0)
  2801. return StmtError();
  2802. assert((CurContext->isDependentContext() || B.builtAll()) &&
  2803. "omp for simd loop exprs were not built");
  2804. getCurFunction()->setHasBranchProtectedScope();
  2805. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  2806. Clauses, AStmt, B);
  2807. }
  2808. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  2809. Stmt *AStmt,
  2810. SourceLocation StartLoc,
  2811. SourceLocation EndLoc) {
  2812. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2813. auto BaseStmt = AStmt;
  2814. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  2815. BaseStmt = CS->getCapturedStmt();
  2816. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  2817. auto S = C->children();
  2818. if (!S)
  2819. return StmtError();
  2820. // All associated statements must be '#pragma omp section' except for
  2821. // the first one.
  2822. for (++S; S; ++S) {
  2823. auto SectionStmt = *S;
  2824. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  2825. if (SectionStmt)
  2826. Diag(SectionStmt->getLocStart(),
  2827. diag::err_omp_sections_substmt_not_section);
  2828. return StmtError();
  2829. }
  2830. }
  2831. } else {
  2832. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  2833. return StmtError();
  2834. }
  2835. getCurFunction()->setHasBranchProtectedScope();
  2836. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  2837. AStmt);
  2838. }
  2839. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  2840. SourceLocation StartLoc,
  2841. SourceLocation EndLoc) {
  2842. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2843. getCurFunction()->setHasBranchProtectedScope();
  2844. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
  2845. }
  2846. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  2847. Stmt *AStmt,
  2848. SourceLocation StartLoc,
  2849. SourceLocation EndLoc) {
  2850. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2851. getCurFunction()->setHasBranchProtectedScope();
  2852. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  2853. }
  2854. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  2855. SourceLocation StartLoc,
  2856. SourceLocation EndLoc) {
  2857. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2858. getCurFunction()->setHasBranchProtectedScope();
  2859. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  2860. }
  2861. StmtResult
  2862. Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
  2863. Stmt *AStmt, SourceLocation StartLoc,
  2864. SourceLocation EndLoc) {
  2865. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2866. getCurFunction()->setHasBranchProtectedScope();
  2867. return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  2868. AStmt);
  2869. }
  2870. StmtResult Sema::ActOnOpenMPParallelForDirective(
  2871. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  2872. SourceLocation EndLoc,
  2873. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  2874. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2875. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2876. // 1.2.2 OpenMP Language Terminology
  2877. // Structured block - An executable statement with a single entry at the
  2878. // top and a single exit at the bottom.
  2879. // The point of exit cannot be a branch out of the structured block.
  2880. // longjmp() and throw() must not violate the entry/exit criteria.
  2881. CS->getCapturedDecl()->setNothrow();
  2882. OMPLoopDirective::HelperExprs B;
  2883. // In presence of clause 'collapse', it will define the nested loops number.
  2884. unsigned NestedLoopCount =
  2885. CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
  2886. *this, *DSAStack, VarsWithImplicitDSA, B);
  2887. if (NestedLoopCount == 0)
  2888. return StmtError();
  2889. assert((CurContext->isDependentContext() || B.builtAll()) &&
  2890. "omp parallel for loop exprs were not built");
  2891. getCurFunction()->setHasBranchProtectedScope();
  2892. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  2893. NestedLoopCount, Clauses, AStmt, B);
  2894. }
  2895. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  2896. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  2897. SourceLocation EndLoc,
  2898. llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
  2899. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2900. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2901. // 1.2.2 OpenMP Language Terminology
  2902. // Structured block - An executable statement with a single entry at the
  2903. // top and a single exit at the bottom.
  2904. // The point of exit cannot be a branch out of the structured block.
  2905. // longjmp() and throw() must not violate the entry/exit criteria.
  2906. CS->getCapturedDecl()->setNothrow();
  2907. OMPLoopDirective::HelperExprs B;
  2908. // In presence of clause 'collapse', it will define the nested loops number.
  2909. unsigned NestedLoopCount =
  2910. CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
  2911. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  2912. if (NestedLoopCount == 0)
  2913. return StmtError();
  2914. getCurFunction()->setHasBranchProtectedScope();
  2915. return OMPParallelForSimdDirective::Create(
  2916. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  2917. }
  2918. StmtResult
  2919. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  2920. Stmt *AStmt, SourceLocation StartLoc,
  2921. SourceLocation EndLoc) {
  2922. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2923. auto BaseStmt = AStmt;
  2924. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  2925. BaseStmt = CS->getCapturedStmt();
  2926. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  2927. auto S = C->children();
  2928. if (!S)
  2929. return StmtError();
  2930. // All associated statements must be '#pragma omp section' except for
  2931. // the first one.
  2932. for (++S; S; ++S) {
  2933. auto SectionStmt = *S;
  2934. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  2935. if (SectionStmt)
  2936. Diag(SectionStmt->getLocStart(),
  2937. diag::err_omp_parallel_sections_substmt_not_section);
  2938. return StmtError();
  2939. }
  2940. }
  2941. } else {
  2942. Diag(AStmt->getLocStart(),
  2943. diag::err_omp_parallel_sections_not_compound_stmt);
  2944. return StmtError();
  2945. }
  2946. getCurFunction()->setHasBranchProtectedScope();
  2947. return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
  2948. Clauses, AStmt);
  2949. }
  2950. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  2951. Stmt *AStmt, SourceLocation StartLoc,
  2952. SourceLocation EndLoc) {
  2953. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2954. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2955. // 1.2.2 OpenMP Language Terminology
  2956. // Structured block - An executable statement with a single entry at the
  2957. // top and a single exit at the bottom.
  2958. // The point of exit cannot be a branch out of the structured block.
  2959. // longjmp() and throw() must not violate the entry/exit criteria.
  2960. CS->getCapturedDecl()->setNothrow();
  2961. getCurFunction()->setHasBranchProtectedScope();
  2962. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  2963. }
  2964. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  2965. SourceLocation EndLoc) {
  2966. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  2967. }
  2968. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  2969. SourceLocation EndLoc) {
  2970. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  2971. }
  2972. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  2973. SourceLocation EndLoc) {
  2974. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  2975. }
  2976. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  2977. SourceLocation StartLoc,
  2978. SourceLocation EndLoc) {
  2979. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  2980. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  2981. }
  2982. StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
  2983. SourceLocation StartLoc,
  2984. SourceLocation EndLoc) {
  2985. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2986. getCurFunction()->setHasBranchProtectedScope();
  2987. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
  2988. }
  2989. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  2990. Stmt *AStmt,
  2991. SourceLocation StartLoc,
  2992. SourceLocation EndLoc) {
  2993. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2994. auto CS = cast<CapturedStmt>(AStmt);
  2995. // 1.2.2 OpenMP Language Terminology
  2996. // Structured block - An executable statement with a single entry at the
  2997. // top and a single exit at the bottom.
  2998. // The point of exit cannot be a branch out of the structured block.
  2999. // longjmp() and throw() must not violate the entry/exit criteria.
  3000. // TODO further analysis of associated statements and clauses.
  3001. OpenMPClauseKind AtomicKind = OMPC_unknown;
  3002. SourceLocation AtomicKindLoc;
  3003. for (auto *C : Clauses) {
  3004. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  3005. C->getClauseKind() == OMPC_update ||
  3006. C->getClauseKind() == OMPC_capture) {
  3007. if (AtomicKind != OMPC_unknown) {
  3008. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  3009. << SourceRange(C->getLocStart(), C->getLocEnd());
  3010. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  3011. << getOpenMPClauseName(AtomicKind);
  3012. } else {
  3013. AtomicKind = C->getClauseKind();
  3014. AtomicKindLoc = C->getLocStart();
  3015. }
  3016. }
  3017. }
  3018. auto Body = CS->getCapturedStmt();
  3019. Expr *X = nullptr;
  3020. Expr *V = nullptr;
  3021. Expr *E = nullptr;
  3022. // OpenMP [2.12.6, atomic Construct]
  3023. // In the next expressions:
  3024. // * x and v (as applicable) are both l-value expressions with scalar type.
  3025. // * During the execution of an atomic region, multiple syntactic
  3026. // occurrences of x must designate the same storage location.
  3027. // * Neither of v and expr (as applicable) may access the storage location
  3028. // designated by x.
  3029. // * Neither of x and expr (as applicable) may access the storage location
  3030. // designated by v.
  3031. // * expr is an expression with scalar type.
  3032. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  3033. // * binop, binop=, ++, and -- are not overloaded operators.
  3034. // * The expression x binop expr must be numerically equivalent to x binop
  3035. // (expr). This requirement is satisfied if the operators in expr have
  3036. // precedence greater than binop, or by using parentheses around expr or
  3037. // subexpressions of expr.
  3038. // * The expression expr binop x must be numerically equivalent to (expr)
  3039. // binop x. This requirement is satisfied if the operators in expr have
  3040. // precedence equal to or greater than binop, or by using parentheses around
  3041. // expr or subexpressions of expr.
  3042. // * For forms that allow multiple occurrences of x, the number of times
  3043. // that x is evaluated is unspecified.
  3044. enum {
  3045. NotAnExpression,
  3046. NotAnAssignmentOp,
  3047. NotAScalarType,
  3048. NotAnLValue,
  3049. NoError
  3050. } ErrorFound = NoError;
  3051. if (AtomicKind == OMPC_read) {
  3052. SourceLocation ErrorLoc, NoteLoc;
  3053. SourceRange ErrorRange, NoteRange;
  3054. // If clause is read:
  3055. // v = x;
  3056. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  3057. auto AtomicBinOp =
  3058. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  3059. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  3060. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  3061. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  3062. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  3063. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  3064. if (!X->isLValue() || !V->isLValue()) {
  3065. auto NotLValueExpr = X->isLValue() ? V : X;
  3066. ErrorFound = NotAnLValue;
  3067. ErrorLoc = AtomicBinOp->getExprLoc();
  3068. ErrorRange = AtomicBinOp->getSourceRange();
  3069. NoteLoc = NotLValueExpr->getExprLoc();
  3070. NoteRange = NotLValueExpr->getSourceRange();
  3071. }
  3072. } else if (!X->isInstantiationDependent() ||
  3073. !V->isInstantiationDependent()) {
  3074. auto NotScalarExpr =
  3075. (X->isInstantiationDependent() || X->getType()->isScalarType())
  3076. ? V
  3077. : X;
  3078. ErrorFound = NotAScalarType;
  3079. ErrorLoc = AtomicBinOp->getExprLoc();
  3080. ErrorRange = AtomicBinOp->getSourceRange();
  3081. NoteLoc = NotScalarExpr->getExprLoc();
  3082. NoteRange = NotScalarExpr->getSourceRange();
  3083. }
  3084. } else {
  3085. ErrorFound = NotAnAssignmentOp;
  3086. ErrorLoc = AtomicBody->getExprLoc();
  3087. ErrorRange = AtomicBody->getSourceRange();
  3088. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  3089. : AtomicBody->getExprLoc();
  3090. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  3091. : AtomicBody->getSourceRange();
  3092. }
  3093. } else {
  3094. ErrorFound = NotAnExpression;
  3095. NoteLoc = ErrorLoc = Body->getLocStart();
  3096. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  3097. }
  3098. if (ErrorFound != NoError) {
  3099. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  3100. << ErrorRange;
  3101. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  3102. << NoteRange;
  3103. return StmtError();
  3104. } else if (CurContext->isDependentContext())
  3105. V = X = nullptr;
  3106. } else if (AtomicKind == OMPC_write) {
  3107. SourceLocation ErrorLoc, NoteLoc;
  3108. SourceRange ErrorRange, NoteRange;
  3109. // If clause is write:
  3110. // x = expr;
  3111. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  3112. auto AtomicBinOp =
  3113. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  3114. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  3115. X = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  3116. E = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  3117. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  3118. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  3119. if (!X->isLValue()) {
  3120. ErrorFound = NotAnLValue;
  3121. ErrorLoc = AtomicBinOp->getExprLoc();
  3122. ErrorRange = AtomicBinOp->getSourceRange();
  3123. NoteLoc = X->getExprLoc();
  3124. NoteRange = X->getSourceRange();
  3125. }
  3126. } else if (!X->isInstantiationDependent() ||
  3127. !E->isInstantiationDependent()) {
  3128. auto NotScalarExpr =
  3129. (X->isInstantiationDependent() || X->getType()->isScalarType())
  3130. ? E
  3131. : X;
  3132. ErrorFound = NotAScalarType;
  3133. ErrorLoc = AtomicBinOp->getExprLoc();
  3134. ErrorRange = AtomicBinOp->getSourceRange();
  3135. NoteLoc = NotScalarExpr->getExprLoc();
  3136. NoteRange = NotScalarExpr->getSourceRange();
  3137. }
  3138. } else {
  3139. ErrorFound = NotAnAssignmentOp;
  3140. ErrorLoc = AtomicBody->getExprLoc();
  3141. ErrorRange = AtomicBody->getSourceRange();
  3142. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  3143. : AtomicBody->getExprLoc();
  3144. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  3145. : AtomicBody->getSourceRange();
  3146. }
  3147. } else {
  3148. ErrorFound = NotAnExpression;
  3149. NoteLoc = ErrorLoc = Body->getLocStart();
  3150. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  3151. }
  3152. if (ErrorFound != NoError) {
  3153. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  3154. << ErrorRange;
  3155. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  3156. << NoteRange;
  3157. return StmtError();
  3158. } else if (CurContext->isDependentContext())
  3159. E = X = nullptr;
  3160. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  3161. if (!isa<Expr>(Body)) {
  3162. Diag(Body->getLocStart(),
  3163. diag::err_omp_atomic_update_not_expression_statement)
  3164. << (AtomicKind == OMPC_update);
  3165. return StmtError();
  3166. }
  3167. } else if (AtomicKind == OMPC_capture) {
  3168. if (isa<Expr>(Body) && !isa<BinaryOperator>(Body)) {
  3169. Diag(Body->getLocStart(),
  3170. diag::err_omp_atomic_capture_not_expression_statement);
  3171. return StmtError();
  3172. } else if (!isa<Expr>(Body) && !isa<CompoundStmt>(Body)) {
  3173. Diag(Body->getLocStart(),
  3174. diag::err_omp_atomic_capture_not_compound_statement);
  3175. return StmtError();
  3176. }
  3177. }
  3178. getCurFunction()->setHasBranchProtectedScope();
  3179. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3180. X, V, E);
  3181. }
  3182. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  3183. Stmt *AStmt,
  3184. SourceLocation StartLoc,
  3185. SourceLocation EndLoc) {
  3186. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3187. // OpenMP [2.16, Nesting of Regions]
  3188. // If specified, a teams construct must be contained within a target
  3189. // construct. That target construct must contain no statements or directives
  3190. // outside of the teams construct.
  3191. if (DSAStack->hasInnerTeamsRegion()) {
  3192. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  3193. bool OMPTeamsFound = true;
  3194. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  3195. auto I = CS->body_begin();
  3196. while (I != CS->body_end()) {
  3197. auto OED = dyn_cast<OMPExecutableDirective>(*I);
  3198. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  3199. OMPTeamsFound = false;
  3200. break;
  3201. }
  3202. ++I;
  3203. }
  3204. assert(I != CS->body_end() && "Not found statement");
  3205. S = *I;
  3206. }
  3207. if (!OMPTeamsFound) {
  3208. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  3209. Diag(DSAStack->getInnerTeamsRegionLoc(),
  3210. diag::note_omp_nested_teams_construct_here);
  3211. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  3212. << isa<OMPExecutableDirective>(S);
  3213. return StmtError();
  3214. }
  3215. }
  3216. getCurFunction()->setHasBranchProtectedScope();
  3217. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3218. }
  3219. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  3220. Stmt *AStmt, SourceLocation StartLoc,
  3221. SourceLocation EndLoc) {
  3222. assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3223. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3224. // 1.2.2 OpenMP Language Terminology
  3225. // Structured block - An executable statement with a single entry at the
  3226. // top and a single exit at the bottom.
  3227. // The point of exit cannot be a branch out of the structured block.
  3228. // longjmp() and throw() must not violate the entry/exit criteria.
  3229. CS->getCapturedDecl()->setNothrow();
  3230. getCurFunction()->setHasBranchProtectedScope();
  3231. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  3232. }
  3233. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  3234. SourceLocation StartLoc,
  3235. SourceLocation LParenLoc,
  3236. SourceLocation EndLoc) {
  3237. OMPClause *Res = nullptr;
  3238. switch (Kind) {
  3239. case OMPC_if:
  3240. Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
  3241. break;
  3242. case OMPC_final:
  3243. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  3244. break;
  3245. case OMPC_num_threads:
  3246. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  3247. break;
  3248. case OMPC_safelen:
  3249. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  3250. break;
  3251. case OMPC_collapse:
  3252. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  3253. break;
  3254. case OMPC_default:
  3255. case OMPC_proc_bind:
  3256. case OMPC_schedule:
  3257. case OMPC_private:
  3258. case OMPC_firstprivate:
  3259. case OMPC_lastprivate:
  3260. case OMPC_shared:
  3261. case OMPC_reduction:
  3262. case OMPC_linear:
  3263. case OMPC_aligned:
  3264. case OMPC_copyin:
  3265. case OMPC_copyprivate:
  3266. case OMPC_ordered:
  3267. case OMPC_nowait:
  3268. case OMPC_untied:
  3269. case OMPC_mergeable:
  3270. case OMPC_threadprivate:
  3271. case OMPC_flush:
  3272. case OMPC_read:
  3273. case OMPC_write:
  3274. case OMPC_update:
  3275. case OMPC_capture:
  3276. case OMPC_seq_cst:
  3277. case OMPC_unknown:
  3278. llvm_unreachable("Clause is not allowed.");
  3279. }
  3280. return Res;
  3281. }
  3282. OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
  3283. SourceLocation LParenLoc,
  3284. SourceLocation EndLoc) {
  3285. Expr *ValExpr = Condition;
  3286. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  3287. !Condition->isInstantiationDependent() &&
  3288. !Condition->containsUnexpandedParameterPack()) {
  3289. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  3290. Condition->getExprLoc(), Condition);
  3291. if (Val.isInvalid())
  3292. return nullptr;
  3293. ValExpr = Val.get();
  3294. }
  3295. return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  3296. }
  3297. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  3298. SourceLocation StartLoc,
  3299. SourceLocation LParenLoc,
  3300. SourceLocation EndLoc) {
  3301. Expr *ValExpr = Condition;
  3302. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  3303. !Condition->isInstantiationDependent() &&
  3304. !Condition->containsUnexpandedParameterPack()) {
  3305. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  3306. Condition->getExprLoc(), Condition);
  3307. if (Val.isInvalid())
  3308. return nullptr;
  3309. ValExpr = Val.get();
  3310. }
  3311. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  3312. }
  3313. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  3314. Expr *Op) {
  3315. if (!Op)
  3316. return ExprError();
  3317. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  3318. public:
  3319. IntConvertDiagnoser()
  3320. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  3321. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  3322. QualType T) override {
  3323. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  3324. }
  3325. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  3326. QualType T) override {
  3327. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  3328. }
  3329. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  3330. QualType T,
  3331. QualType ConvTy) override {
  3332. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  3333. }
  3334. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  3335. QualType ConvTy) override {
  3336. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  3337. << ConvTy->isEnumeralType() << ConvTy;
  3338. }
  3339. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  3340. QualType T) override {
  3341. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  3342. }
  3343. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  3344. QualType ConvTy) override {
  3345. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  3346. << ConvTy->isEnumeralType() << ConvTy;
  3347. }
  3348. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  3349. QualType) override {
  3350. llvm_unreachable("conversion functions are permitted");
  3351. }
  3352. } ConvertDiagnoser;
  3353. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  3354. }
  3355. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  3356. SourceLocation StartLoc,
  3357. SourceLocation LParenLoc,
  3358. SourceLocation EndLoc) {
  3359. Expr *ValExpr = NumThreads;
  3360. if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
  3361. !NumThreads->containsUnexpandedParameterPack()) {
  3362. SourceLocation NumThreadsLoc = NumThreads->getLocStart();
  3363. ExprResult Val =
  3364. PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
  3365. if (Val.isInvalid())
  3366. return nullptr;
  3367. ValExpr = Val.get();
  3368. // OpenMP [2.5, Restrictions]
  3369. // The num_threads expression must evaluate to a positive integer value.
  3370. llvm::APSInt Result;
  3371. if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
  3372. !Result.isStrictlyPositive()) {
  3373. Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
  3374. << "num_threads" << NumThreads->getSourceRange();
  3375. return nullptr;
  3376. }
  3377. }
  3378. return new (Context)
  3379. OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  3380. }
  3381. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  3382. OpenMPClauseKind CKind) {
  3383. if (!E)
  3384. return ExprError();
  3385. if (E->isValueDependent() || E->isTypeDependent() ||
  3386. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3387. return E;
  3388. llvm::APSInt Result;
  3389. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  3390. if (ICE.isInvalid())
  3391. return ExprError();
  3392. if (!Result.isStrictlyPositive()) {
  3393. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  3394. << getOpenMPClauseName(CKind) << E->getSourceRange();
  3395. return ExprError();
  3396. }
  3397. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  3398. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  3399. << E->getSourceRange();
  3400. return ExprError();
  3401. }
  3402. return ICE;
  3403. }
  3404. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  3405. SourceLocation LParenLoc,
  3406. SourceLocation EndLoc) {
  3407. // OpenMP [2.8.1, simd construct, Description]
  3408. // The parameter of the safelen clause must be a constant
  3409. // positive integer expression.
  3410. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  3411. if (Safelen.isInvalid())
  3412. return nullptr;
  3413. return new (Context)
  3414. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  3415. }
  3416. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  3417. SourceLocation StartLoc,
  3418. SourceLocation LParenLoc,
  3419. SourceLocation EndLoc) {
  3420. // OpenMP [2.7.1, loop construct, Description]
  3421. // OpenMP [2.8.1, simd construct, Description]
  3422. // OpenMP [2.9.6, distribute construct, Description]
  3423. // The parameter of the collapse clause must be a constant
  3424. // positive integer expression.
  3425. ExprResult NumForLoopsResult =
  3426. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  3427. if (NumForLoopsResult.isInvalid())
  3428. return nullptr;
  3429. return new (Context)
  3430. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  3431. }
  3432. OMPClause *Sema::ActOnOpenMPSimpleClause(
  3433. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  3434. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  3435. OMPClause *Res = nullptr;
  3436. switch (Kind) {
  3437. case OMPC_default:
  3438. Res =
  3439. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  3440. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  3441. break;
  3442. case OMPC_proc_bind:
  3443. Res = ActOnOpenMPProcBindClause(
  3444. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  3445. LParenLoc, EndLoc);
  3446. break;
  3447. case OMPC_if:
  3448. case OMPC_final:
  3449. case OMPC_num_threads:
  3450. case OMPC_safelen:
  3451. case OMPC_collapse:
  3452. case OMPC_schedule:
  3453. case OMPC_private:
  3454. case OMPC_firstprivate:
  3455. case OMPC_lastprivate:
  3456. case OMPC_shared:
  3457. case OMPC_reduction:
  3458. case OMPC_linear:
  3459. case OMPC_aligned:
  3460. case OMPC_copyin:
  3461. case OMPC_copyprivate:
  3462. case OMPC_ordered:
  3463. case OMPC_nowait:
  3464. case OMPC_untied:
  3465. case OMPC_mergeable:
  3466. case OMPC_threadprivate:
  3467. case OMPC_flush:
  3468. case OMPC_read:
  3469. case OMPC_write:
  3470. case OMPC_update:
  3471. case OMPC_capture:
  3472. case OMPC_seq_cst:
  3473. case OMPC_unknown:
  3474. llvm_unreachable("Clause is not allowed.");
  3475. }
  3476. return Res;
  3477. }
  3478. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  3479. SourceLocation KindKwLoc,
  3480. SourceLocation StartLoc,
  3481. SourceLocation LParenLoc,
  3482. SourceLocation EndLoc) {
  3483. if (Kind == OMPC_DEFAULT_unknown) {
  3484. std::string Values;
  3485. static_assert(OMPC_DEFAULT_unknown > 0,
  3486. "OMPC_DEFAULT_unknown not greater than 0");
  3487. std::string Sep(", ");
  3488. for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
  3489. Values += "'";
  3490. Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
  3491. Values += "'";
  3492. switch (i) {
  3493. case OMPC_DEFAULT_unknown - 2:
  3494. Values += " or ";
  3495. break;
  3496. case OMPC_DEFAULT_unknown - 1:
  3497. break;
  3498. default:
  3499. Values += Sep;
  3500. break;
  3501. }
  3502. }
  3503. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  3504. << Values << getOpenMPClauseName(OMPC_default);
  3505. return nullptr;
  3506. }
  3507. switch (Kind) {
  3508. case OMPC_DEFAULT_none:
  3509. DSAStack->setDefaultDSANone(KindKwLoc);
  3510. break;
  3511. case OMPC_DEFAULT_shared:
  3512. DSAStack->setDefaultDSAShared(KindKwLoc);
  3513. break;
  3514. case OMPC_DEFAULT_unknown:
  3515. llvm_unreachable("Clause kind is not allowed.");
  3516. break;
  3517. }
  3518. return new (Context)
  3519. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  3520. }
  3521. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  3522. SourceLocation KindKwLoc,
  3523. SourceLocation StartLoc,
  3524. SourceLocation LParenLoc,
  3525. SourceLocation EndLoc) {
  3526. if (Kind == OMPC_PROC_BIND_unknown) {
  3527. std::string Values;
  3528. std::string Sep(", ");
  3529. for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
  3530. Values += "'";
  3531. Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
  3532. Values += "'";
  3533. switch (i) {
  3534. case OMPC_PROC_BIND_unknown - 2:
  3535. Values += " or ";
  3536. break;
  3537. case OMPC_PROC_BIND_unknown - 1:
  3538. break;
  3539. default:
  3540. Values += Sep;
  3541. break;
  3542. }
  3543. }
  3544. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  3545. << Values << getOpenMPClauseName(OMPC_proc_bind);
  3546. return nullptr;
  3547. }
  3548. return new (Context)
  3549. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  3550. }
  3551. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  3552. OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
  3553. SourceLocation StartLoc, SourceLocation LParenLoc,
  3554. SourceLocation ArgumentLoc, SourceLocation CommaLoc,
  3555. SourceLocation EndLoc) {
  3556. OMPClause *Res = nullptr;
  3557. switch (Kind) {
  3558. case OMPC_schedule:
  3559. Res = ActOnOpenMPScheduleClause(
  3560. static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
  3561. LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
  3562. break;
  3563. case OMPC_if:
  3564. case OMPC_final:
  3565. case OMPC_num_threads:
  3566. case OMPC_safelen:
  3567. case OMPC_collapse:
  3568. case OMPC_default:
  3569. case OMPC_proc_bind:
  3570. case OMPC_private:
  3571. case OMPC_firstprivate:
  3572. case OMPC_lastprivate:
  3573. case OMPC_shared:
  3574. case OMPC_reduction:
  3575. case OMPC_linear:
  3576. case OMPC_aligned:
  3577. case OMPC_copyin:
  3578. case OMPC_copyprivate:
  3579. case OMPC_ordered:
  3580. case OMPC_nowait:
  3581. case OMPC_untied:
  3582. case OMPC_mergeable:
  3583. case OMPC_threadprivate:
  3584. case OMPC_flush:
  3585. case OMPC_read:
  3586. case OMPC_write:
  3587. case OMPC_update:
  3588. case OMPC_capture:
  3589. case OMPC_seq_cst:
  3590. case OMPC_unknown:
  3591. llvm_unreachable("Clause is not allowed.");
  3592. }
  3593. return Res;
  3594. }
  3595. OMPClause *Sema::ActOnOpenMPScheduleClause(
  3596. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  3597. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  3598. SourceLocation EndLoc) {
  3599. if (Kind == OMPC_SCHEDULE_unknown) {
  3600. std::string Values;
  3601. std::string Sep(", ");
  3602. for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
  3603. Values += "'";
  3604. Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
  3605. Values += "'";
  3606. switch (i) {
  3607. case OMPC_SCHEDULE_unknown - 2:
  3608. Values += " or ";
  3609. break;
  3610. case OMPC_SCHEDULE_unknown - 1:
  3611. break;
  3612. default:
  3613. Values += Sep;
  3614. break;
  3615. }
  3616. }
  3617. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  3618. << Values << getOpenMPClauseName(OMPC_schedule);
  3619. return nullptr;
  3620. }
  3621. Expr *ValExpr = ChunkSize;
  3622. if (ChunkSize) {
  3623. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  3624. !ChunkSize->isInstantiationDependent() &&
  3625. !ChunkSize->containsUnexpandedParameterPack()) {
  3626. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  3627. ExprResult Val =
  3628. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  3629. if (Val.isInvalid())
  3630. return nullptr;
  3631. ValExpr = Val.get();
  3632. // OpenMP [2.7.1, Restrictions]
  3633. // chunk_size must be a loop invariant integer expression with a positive
  3634. // value.
  3635. llvm::APSInt Result;
  3636. if (ValExpr->isIntegerConstantExpr(Result, Context) &&
  3637. Result.isSigned() && !Result.isStrictlyPositive()) {
  3638. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  3639. << "schedule" << ChunkSize->getSourceRange();
  3640. return nullptr;
  3641. }
  3642. }
  3643. }
  3644. return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
  3645. EndLoc, Kind, ValExpr);
  3646. }
  3647. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  3648. SourceLocation StartLoc,
  3649. SourceLocation EndLoc) {
  3650. OMPClause *Res = nullptr;
  3651. switch (Kind) {
  3652. case OMPC_ordered:
  3653. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  3654. break;
  3655. case OMPC_nowait:
  3656. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  3657. break;
  3658. case OMPC_untied:
  3659. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  3660. break;
  3661. case OMPC_mergeable:
  3662. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  3663. break;
  3664. case OMPC_read:
  3665. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  3666. break;
  3667. case OMPC_write:
  3668. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  3669. break;
  3670. case OMPC_update:
  3671. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  3672. break;
  3673. case OMPC_capture:
  3674. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  3675. break;
  3676. case OMPC_seq_cst:
  3677. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  3678. break;
  3679. case OMPC_if:
  3680. case OMPC_final:
  3681. case OMPC_num_threads:
  3682. case OMPC_safelen:
  3683. case OMPC_collapse:
  3684. case OMPC_schedule:
  3685. case OMPC_private:
  3686. case OMPC_firstprivate:
  3687. case OMPC_lastprivate:
  3688. case OMPC_shared:
  3689. case OMPC_reduction:
  3690. case OMPC_linear:
  3691. case OMPC_aligned:
  3692. case OMPC_copyin:
  3693. case OMPC_copyprivate:
  3694. case OMPC_default:
  3695. case OMPC_proc_bind:
  3696. case OMPC_threadprivate:
  3697. case OMPC_flush:
  3698. case OMPC_unknown:
  3699. llvm_unreachable("Clause is not allowed.");
  3700. }
  3701. return Res;
  3702. }
  3703. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  3704. SourceLocation EndLoc) {
  3705. DSAStack->setOrderedRegion();
  3706. return new (Context) OMPOrderedClause(StartLoc, EndLoc);
  3707. }
  3708. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  3709. SourceLocation EndLoc) {
  3710. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  3711. }
  3712. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  3713. SourceLocation EndLoc) {
  3714. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  3715. }
  3716. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  3717. SourceLocation EndLoc) {
  3718. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  3719. }
  3720. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  3721. SourceLocation EndLoc) {
  3722. return new (Context) OMPReadClause(StartLoc, EndLoc);
  3723. }
  3724. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  3725. SourceLocation EndLoc) {
  3726. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  3727. }
  3728. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  3729. SourceLocation EndLoc) {
  3730. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  3731. }
  3732. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  3733. SourceLocation EndLoc) {
  3734. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  3735. }
  3736. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  3737. SourceLocation EndLoc) {
  3738. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  3739. }
  3740. OMPClause *Sema::ActOnOpenMPVarListClause(
  3741. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  3742. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  3743. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  3744. const DeclarationNameInfo &ReductionId) {
  3745. OMPClause *Res = nullptr;
  3746. switch (Kind) {
  3747. case OMPC_private:
  3748. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  3749. break;
  3750. case OMPC_firstprivate:
  3751. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  3752. break;
  3753. case OMPC_lastprivate:
  3754. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  3755. break;
  3756. case OMPC_shared:
  3757. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  3758. break;
  3759. case OMPC_reduction:
  3760. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  3761. EndLoc, ReductionIdScopeSpec, ReductionId);
  3762. break;
  3763. case OMPC_linear:
  3764. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  3765. ColonLoc, EndLoc);
  3766. break;
  3767. case OMPC_aligned:
  3768. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  3769. ColonLoc, EndLoc);
  3770. break;
  3771. case OMPC_copyin:
  3772. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  3773. break;
  3774. case OMPC_copyprivate:
  3775. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  3776. break;
  3777. case OMPC_flush:
  3778. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  3779. break;
  3780. case OMPC_if:
  3781. case OMPC_final:
  3782. case OMPC_num_threads:
  3783. case OMPC_safelen:
  3784. case OMPC_collapse:
  3785. case OMPC_default:
  3786. case OMPC_proc_bind:
  3787. case OMPC_schedule:
  3788. case OMPC_ordered:
  3789. case OMPC_nowait:
  3790. case OMPC_untied:
  3791. case OMPC_mergeable:
  3792. case OMPC_threadprivate:
  3793. case OMPC_read:
  3794. case OMPC_write:
  3795. case OMPC_update:
  3796. case OMPC_capture:
  3797. case OMPC_seq_cst:
  3798. case OMPC_unknown:
  3799. llvm_unreachable("Clause is not allowed.");
  3800. }
  3801. return Res;
  3802. }
  3803. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  3804. SourceLocation StartLoc,
  3805. SourceLocation LParenLoc,
  3806. SourceLocation EndLoc) {
  3807. SmallVector<Expr *, 8> Vars;
  3808. SmallVector<Expr *, 8> PrivateCopies;
  3809. for (auto &RefExpr : VarList) {
  3810. assert(RefExpr && "NULL expr in OpenMP private clause.");
  3811. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  3812. // It will be analyzed later.
  3813. Vars.push_back(RefExpr);
  3814. PrivateCopies.push_back(nullptr);
  3815. continue;
  3816. }
  3817. SourceLocation ELoc = RefExpr->getExprLoc();
  3818. // OpenMP [2.1, C/C++]
  3819. // A list item is a variable name.
  3820. // OpenMP [2.9.3.3, Restrictions, p.1]
  3821. // A variable that is part of another variable (as an array or
  3822. // structure element) cannot appear in a private clause.
  3823. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3824. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  3825. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  3826. continue;
  3827. }
  3828. Decl *D = DE->getDecl();
  3829. VarDecl *VD = cast<VarDecl>(D);
  3830. QualType Type = VD->getType();
  3831. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  3832. // It will be analyzed later.
  3833. Vars.push_back(DE);
  3834. PrivateCopies.push_back(nullptr);
  3835. continue;
  3836. }
  3837. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  3838. // A variable that appears in a private clause must not have an incomplete
  3839. // type or a reference type.
  3840. if (RequireCompleteType(ELoc, Type,
  3841. diag::err_omp_private_incomplete_type)) {
  3842. continue;
  3843. }
  3844. if (Type->isReferenceType()) {
  3845. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  3846. << getOpenMPClauseName(OMPC_private) << Type;
  3847. bool IsDecl =
  3848. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  3849. Diag(VD->getLocation(),
  3850. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  3851. << VD;
  3852. continue;
  3853. }
  3854. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  3855. // A variable of class type (or array thereof) that appears in a private
  3856. // clause requires an accessible, unambiguous default constructor for the
  3857. // class type.
  3858. while (Type->isArrayType()) {
  3859. Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
  3860. }
  3861. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  3862. // in a Construct]
  3863. // Variables with the predetermined data-sharing attributes may not be
  3864. // listed in data-sharing attributes clauses, except for the cases
  3865. // listed below. For these exceptions only, listing a predetermined
  3866. // variable in a data-sharing attribute clause is allowed and overrides
  3867. // the variable's predetermined data-sharing attributes.
  3868. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  3869. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  3870. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  3871. << getOpenMPClauseName(OMPC_private);
  3872. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  3873. continue;
  3874. }
  3875. // Generate helper private variable and initialize it with the default
  3876. // value. The address of the original variable is replaced by the address of
  3877. // the new private variable in CodeGen. This new variable is not added to
  3878. // IdResolver, so the code in the OpenMP region uses original variable for
  3879. // proper diagnostics.
  3880. auto VDPrivate =
  3881. VarDecl::Create(Context, CurContext, DE->getLocStart(),
  3882. DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
  3883. VD->getTypeSourceInfo(), /*S*/ SC_Auto);
  3884. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
  3885. if (VDPrivate->isInvalidDecl())
  3886. continue;
  3887. CurContext->addDecl(VDPrivate);
  3888. auto VDPrivateRefExpr =
  3889. DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
  3890. /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
  3891. /*RefersToEnclosingVariableOrCapture*/ false,
  3892. /*NameLoc*/ SourceLocation(), DE->getType(),
  3893. /*VK*/ VK_LValue);
  3894. DSAStack->addDSA(VD, DE, OMPC_private);
  3895. Vars.push_back(DE);
  3896. PrivateCopies.push_back(VDPrivateRefExpr);
  3897. }
  3898. if (Vars.empty())
  3899. return nullptr;
  3900. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  3901. PrivateCopies);
  3902. }
  3903. namespace {
  3904. class DiagsUninitializedSeveretyRAII {
  3905. private:
  3906. DiagnosticsEngine &Diags;
  3907. SourceLocation SavedLoc;
  3908. bool IsIgnored;
  3909. public:
  3910. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  3911. bool IsIgnored)
  3912. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  3913. if (!IsIgnored) {
  3914. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  3915. /*Map*/ diag::Severity::Ignored, Loc);
  3916. }
  3917. }
  3918. ~DiagsUninitializedSeveretyRAII() {
  3919. if (!IsIgnored)
  3920. Diags.popMappings(SavedLoc);
  3921. }
  3922. };
  3923. }
  3924. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  3925. SourceLocation StartLoc,
  3926. SourceLocation LParenLoc,
  3927. SourceLocation EndLoc) {
  3928. SmallVector<Expr *, 8> Vars;
  3929. SmallVector<Expr *, 8> PrivateCopies;
  3930. SmallVector<Expr *, 8> Inits;
  3931. bool IsImplicitClause =
  3932. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  3933. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  3934. for (auto &RefExpr : VarList) {
  3935. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  3936. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  3937. // It will be analyzed later.
  3938. Vars.push_back(RefExpr);
  3939. PrivateCopies.push_back(nullptr);
  3940. Inits.push_back(nullptr);
  3941. continue;
  3942. }
  3943. SourceLocation ELoc =
  3944. IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
  3945. // OpenMP [2.1, C/C++]
  3946. // A list item is a variable name.
  3947. // OpenMP [2.9.3.3, Restrictions, p.1]
  3948. // A variable that is part of another variable (as an array or
  3949. // structure element) cannot appear in a private clause.
  3950. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3951. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  3952. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  3953. continue;
  3954. }
  3955. Decl *D = DE->getDecl();
  3956. VarDecl *VD = cast<VarDecl>(D);
  3957. QualType Type = VD->getType();
  3958. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  3959. // It will be analyzed later.
  3960. Vars.push_back(DE);
  3961. PrivateCopies.push_back(nullptr);
  3962. Inits.push_back(nullptr);
  3963. continue;
  3964. }
  3965. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  3966. // A variable that appears in a private clause must not have an incomplete
  3967. // type or a reference type.
  3968. if (RequireCompleteType(ELoc, Type,
  3969. diag::err_omp_firstprivate_incomplete_type)) {
  3970. continue;
  3971. }
  3972. if (Type->isReferenceType()) {
  3973. if (IsImplicitClause) {
  3974. Diag(ImplicitClauseLoc,
  3975. diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
  3976. << Type;
  3977. Diag(RefExpr->getExprLoc(), diag::note_used_here);
  3978. } else {
  3979. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  3980. << getOpenMPClauseName(OMPC_firstprivate) << Type;
  3981. }
  3982. bool IsDecl =
  3983. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  3984. Diag(VD->getLocation(),
  3985. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  3986. << VD;
  3987. continue;
  3988. }
  3989. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  3990. // A variable of class type (or array thereof) that appears in a private
  3991. // clause requires an accessible, unambiguous copy constructor for the
  3992. // class type.
  3993. Type = Context.getBaseElementType(Type);
  3994. // If an implicit firstprivate variable found it was checked already.
  3995. if (!IsImplicitClause) {
  3996. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  3997. Type = Type.getNonReferenceType().getCanonicalType();
  3998. bool IsConstant = Type.isConstant(Context);
  3999. Type = Context.getBaseElementType(Type);
  4000. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  4001. // A list item that specifies a given variable may not appear in more
  4002. // than one clause on the same directive, except that a variable may be
  4003. // specified in both firstprivate and lastprivate clauses.
  4004. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  4005. DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
  4006. Diag(ELoc, diag::err_omp_wrong_dsa)
  4007. << getOpenMPClauseName(DVar.CKind)
  4008. << getOpenMPClauseName(OMPC_firstprivate);
  4009. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4010. continue;
  4011. }
  4012. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  4013. // in a Construct]
  4014. // Variables with the predetermined data-sharing attributes may not be
  4015. // listed in data-sharing attributes clauses, except for the cases
  4016. // listed below. For these exceptions only, listing a predetermined
  4017. // variable in a data-sharing attribute clause is allowed and overrides
  4018. // the variable's predetermined data-sharing attributes.
  4019. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  4020. // in a Construct, C/C++, p.2]
  4021. // Variables with const-qualified type having no mutable member may be
  4022. // listed in a firstprivate clause, even if they are static data members.
  4023. if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
  4024. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  4025. Diag(ELoc, diag::err_omp_wrong_dsa)
  4026. << getOpenMPClauseName(DVar.CKind)
  4027. << getOpenMPClauseName(OMPC_firstprivate);
  4028. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4029. continue;
  4030. }
  4031. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  4032. // OpenMP [2.9.3.4, Restrictions, p.2]
  4033. // A list item that is private within a parallel region must not appear
  4034. // in a firstprivate clause on a worksharing construct if any of the
  4035. // worksharing regions arising from the worksharing construct ever bind
  4036. // to any of the parallel regions arising from the parallel construct.
  4037. if (isOpenMPWorksharingDirective(CurrDir) &&
  4038. !isOpenMPParallelDirective(CurrDir)) {
  4039. DVar = DSAStack->getImplicitDSA(VD, true);
  4040. if (DVar.CKind != OMPC_shared &&
  4041. (isOpenMPParallelDirective(DVar.DKind) ||
  4042. DVar.DKind == OMPD_unknown)) {
  4043. Diag(ELoc, diag::err_omp_required_access)
  4044. << getOpenMPClauseName(OMPC_firstprivate)
  4045. << getOpenMPClauseName(OMPC_shared);
  4046. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4047. continue;
  4048. }
  4049. }
  4050. // OpenMP [2.9.3.4, Restrictions, p.3]
  4051. // A list item that appears in a reduction clause of a parallel construct
  4052. // must not appear in a firstprivate clause on a worksharing or task
  4053. // construct if any of the worksharing or task regions arising from the
  4054. // worksharing or task construct ever bind to any of the parallel regions
  4055. // arising from the parallel construct.
  4056. // OpenMP [2.9.3.4, Restrictions, p.4]
  4057. // A list item that appears in a reduction clause in worksharing
  4058. // construct must not appear in a firstprivate clause in a task construct
  4059. // encountered during execution of any of the worksharing regions arising
  4060. // from the worksharing construct.
  4061. if (CurrDir == OMPD_task) {
  4062. DVar =
  4063. DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  4064. [](OpenMPDirectiveKind K) -> bool {
  4065. return isOpenMPParallelDirective(K) ||
  4066. isOpenMPWorksharingDirective(K);
  4067. },
  4068. false);
  4069. if (DVar.CKind == OMPC_reduction &&
  4070. (isOpenMPParallelDirective(DVar.DKind) ||
  4071. isOpenMPWorksharingDirective(DVar.DKind))) {
  4072. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  4073. << getOpenMPDirectiveName(DVar.DKind);
  4074. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4075. continue;
  4076. }
  4077. }
  4078. }
  4079. Type = Type.getUnqualifiedType();
  4080. auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
  4081. ELoc, VD->getIdentifier(), VD->getType(),
  4082. VD->getTypeSourceInfo(), /*S*/ SC_Auto);
  4083. // Generate helper private variable and initialize it with the value of the
  4084. // original variable. The address of the original variable is replaced by
  4085. // the address of the new private variable in the CodeGen. This new variable
  4086. // is not added to IdResolver, so the code in the OpenMP region uses
  4087. // original variable for proper diagnostics and variable capturing.
  4088. Expr *VDInitRefExpr = nullptr;
  4089. // For arrays generate initializer for single element and replace it by the
  4090. // original array element in CodeGen.
  4091. if (DE->getType()->isArrayType()) {
  4092. auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
  4093. ELoc, VD->getIdentifier(), Type,
  4094. VD->getTypeSourceInfo(), /*S*/ SC_Auto);
  4095. CurContext->addHiddenDecl(VDInit);
  4096. VDInitRefExpr = DeclRefExpr::Create(
  4097. Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
  4098. /*TemplateKWLoc*/ SourceLocation(), VDInit,
  4099. /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
  4100. /*VK*/ VK_LValue);
  4101. VDInit->setIsUsed();
  4102. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  4103. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
  4104. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  4105. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  4106. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  4107. if (Result.isInvalid())
  4108. VDPrivate->setInvalidDecl();
  4109. else
  4110. VDPrivate->setInit(Result.getAs<Expr>());
  4111. } else {
  4112. AddInitializerToDecl(
  4113. VDPrivate,
  4114. DefaultLvalueConversion(
  4115. DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  4116. SourceLocation(), DE->getDecl(),
  4117. /*RefersToEnclosingVariableOrCapture=*/true,
  4118. DE->getExprLoc(), DE->getType(),
  4119. /*VK=*/VK_LValue)).get(),
  4120. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  4121. }
  4122. if (VDPrivate->isInvalidDecl()) {
  4123. if (IsImplicitClause) {
  4124. Diag(DE->getExprLoc(),
  4125. diag::note_omp_task_predetermined_firstprivate_here);
  4126. }
  4127. continue;
  4128. }
  4129. CurContext->addDecl(VDPrivate);
  4130. auto VDPrivateRefExpr =
  4131. DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
  4132. /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
  4133. /*RefersToEnclosingVariableOrCapture*/ false,
  4134. DE->getLocStart(), DE->getType(),
  4135. /*VK*/ VK_LValue);
  4136. DSAStack->addDSA(VD, DE, OMPC_firstprivate);
  4137. Vars.push_back(DE);
  4138. PrivateCopies.push_back(VDPrivateRefExpr);
  4139. Inits.push_back(VDInitRefExpr);
  4140. }
  4141. if (Vars.empty())
  4142. return nullptr;
  4143. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  4144. Vars, PrivateCopies, Inits);
  4145. }
  4146. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  4147. SourceLocation StartLoc,
  4148. SourceLocation LParenLoc,
  4149. SourceLocation EndLoc) {
  4150. SmallVector<Expr *, 8> Vars;
  4151. for (auto &RefExpr : VarList) {
  4152. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  4153. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4154. // It will be analyzed later.
  4155. Vars.push_back(RefExpr);
  4156. continue;
  4157. }
  4158. SourceLocation ELoc = RefExpr->getExprLoc();
  4159. // OpenMP [2.1, C/C++]
  4160. // A list item is a variable name.
  4161. // OpenMP [2.14.3.5, Restrictions, p.1]
  4162. // A variable that is part of another variable (as an array or structure
  4163. // element) cannot appear in a lastprivate clause.
  4164. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  4165. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4166. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4167. continue;
  4168. }
  4169. Decl *D = DE->getDecl();
  4170. VarDecl *VD = cast<VarDecl>(D);
  4171. QualType Type = VD->getType();
  4172. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  4173. // It will be analyzed later.
  4174. Vars.push_back(DE);
  4175. continue;
  4176. }
  4177. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  4178. // A variable that appears in a lastprivate clause must not have an
  4179. // incomplete type or a reference type.
  4180. if (RequireCompleteType(ELoc, Type,
  4181. diag::err_omp_lastprivate_incomplete_type)) {
  4182. continue;
  4183. }
  4184. if (Type->isReferenceType()) {
  4185. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  4186. << getOpenMPClauseName(OMPC_lastprivate) << Type;
  4187. bool IsDecl =
  4188. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4189. Diag(VD->getLocation(),
  4190. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4191. << VD;
  4192. continue;
  4193. }
  4194. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4195. // in a Construct]
  4196. // Variables with the predetermined data-sharing attributes may not be
  4197. // listed in data-sharing attributes clauses, except for the cases
  4198. // listed below.
  4199. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  4200. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  4201. DVar.CKind != OMPC_firstprivate &&
  4202. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4203. Diag(ELoc, diag::err_omp_wrong_dsa)
  4204. << getOpenMPClauseName(DVar.CKind)
  4205. << getOpenMPClauseName(OMPC_lastprivate);
  4206. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4207. continue;
  4208. }
  4209. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  4210. // OpenMP [2.14.3.5, Restrictions, p.2]
  4211. // A list item that is private within a parallel region, or that appears in
  4212. // the reduction clause of a parallel construct, must not appear in a
  4213. // lastprivate clause on a worksharing construct if any of the corresponding
  4214. // worksharing regions ever binds to any of the corresponding parallel
  4215. // regions.
  4216. if (isOpenMPWorksharingDirective(CurrDir) &&
  4217. !isOpenMPParallelDirective(CurrDir)) {
  4218. DVar = DSAStack->getImplicitDSA(VD, true);
  4219. if (DVar.CKind != OMPC_shared) {
  4220. Diag(ELoc, diag::err_omp_required_access)
  4221. << getOpenMPClauseName(OMPC_lastprivate)
  4222. << getOpenMPClauseName(OMPC_shared);
  4223. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4224. continue;
  4225. }
  4226. }
  4227. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  4228. // A variable of class type (or array thereof) that appears in a
  4229. // lastprivate clause requires an accessible, unambiguous default
  4230. // constructor for the class type, unless the list item is also specified
  4231. // in a firstprivate clause.
  4232. // A variable of class type (or array thereof) that appears in a
  4233. // lastprivate clause requires an accessible, unambiguous copy assignment
  4234. // operator for the class type.
  4235. while (Type.getNonReferenceType()->isArrayType())
  4236. Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
  4237. ->getElementType();
  4238. CXXRecordDecl *RD = getLangOpts().CPlusPlus
  4239. ? Type.getNonReferenceType()->getAsCXXRecordDecl()
  4240. : nullptr;
  4241. // FIXME This code must be replaced by actual copying and destructing of the
  4242. // lastprivate variable.
  4243. if (RD) {
  4244. CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
  4245. DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
  4246. if (MD) {
  4247. if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
  4248. MD->isDeleted()) {
  4249. Diag(ELoc, diag::err_omp_required_method)
  4250. << getOpenMPClauseName(OMPC_lastprivate) << 2;
  4251. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4252. VarDecl::DeclarationOnly;
  4253. Diag(VD->getLocation(),
  4254. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4255. << VD;
  4256. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4257. continue;
  4258. }
  4259. MarkFunctionReferenced(ELoc, MD);
  4260. DiagnoseUseOfDecl(MD, ELoc);
  4261. }
  4262. CXXDestructorDecl *DD = RD->getDestructor();
  4263. if (DD) {
  4264. PartialDiagnostic PD =
  4265. PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
  4266. if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
  4267. DD->isDeleted()) {
  4268. Diag(ELoc, diag::err_omp_required_method)
  4269. << getOpenMPClauseName(OMPC_lastprivate) << 4;
  4270. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4271. VarDecl::DeclarationOnly;
  4272. Diag(VD->getLocation(),
  4273. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4274. << VD;
  4275. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4276. continue;
  4277. }
  4278. MarkFunctionReferenced(ELoc, DD);
  4279. DiagnoseUseOfDecl(DD, ELoc);
  4280. }
  4281. }
  4282. if (DVar.CKind != OMPC_firstprivate)
  4283. DSAStack->addDSA(VD, DE, OMPC_lastprivate);
  4284. Vars.push_back(DE);
  4285. }
  4286. if (Vars.empty())
  4287. return nullptr;
  4288. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  4289. Vars);
  4290. }
  4291. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  4292. SourceLocation StartLoc,
  4293. SourceLocation LParenLoc,
  4294. SourceLocation EndLoc) {
  4295. SmallVector<Expr *, 8> Vars;
  4296. for (auto &RefExpr : VarList) {
  4297. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  4298. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4299. // It will be analyzed later.
  4300. Vars.push_back(RefExpr);
  4301. continue;
  4302. }
  4303. SourceLocation ELoc = RefExpr->getExprLoc();
  4304. // OpenMP [2.1, C/C++]
  4305. // A list item is a variable name.
  4306. // OpenMP [2.14.3.2, Restrictions, p.1]
  4307. // A variable that is part of another variable (as an array or structure
  4308. // element) cannot appear in a shared unless it is a static data member
  4309. // of a C++ class.
  4310. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  4311. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4312. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4313. continue;
  4314. }
  4315. Decl *D = DE->getDecl();
  4316. VarDecl *VD = cast<VarDecl>(D);
  4317. QualType Type = VD->getType();
  4318. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  4319. // It will be analyzed later.
  4320. Vars.push_back(DE);
  4321. continue;
  4322. }
  4323. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  4324. // in a Construct]
  4325. // Variables with the predetermined data-sharing attributes may not be
  4326. // listed in data-sharing attributes clauses, except for the cases
  4327. // listed below. For these exceptions only, listing a predetermined
  4328. // variable in a data-sharing attribute clause is allowed and overrides
  4329. // the variable's predetermined data-sharing attributes.
  4330. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  4331. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  4332. DVar.RefExpr) {
  4333. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  4334. << getOpenMPClauseName(OMPC_shared);
  4335. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4336. continue;
  4337. }
  4338. DSAStack->addDSA(VD, DE, OMPC_shared);
  4339. Vars.push_back(DE);
  4340. }
  4341. if (Vars.empty())
  4342. return nullptr;
  4343. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  4344. }
  4345. namespace {
  4346. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  4347. DSAStackTy *Stack;
  4348. public:
  4349. bool VisitDeclRefExpr(DeclRefExpr *E) {
  4350. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  4351. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  4352. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  4353. return false;
  4354. if (DVar.CKind != OMPC_unknown)
  4355. return true;
  4356. DSAStackTy::DSAVarData DVarPrivate =
  4357. Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
  4358. if (DVarPrivate.CKind != OMPC_unknown)
  4359. return true;
  4360. return false;
  4361. }
  4362. return false;
  4363. }
  4364. bool VisitStmt(Stmt *S) {
  4365. for (auto Child : S->children()) {
  4366. if (Child && Visit(Child))
  4367. return true;
  4368. }
  4369. return false;
  4370. }
  4371. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  4372. };
  4373. } // namespace
  4374. OMPClause *Sema::ActOnOpenMPReductionClause(
  4375. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  4376. SourceLocation ColonLoc, SourceLocation EndLoc,
  4377. CXXScopeSpec &ReductionIdScopeSpec,
  4378. const DeclarationNameInfo &ReductionId) {
  4379. // TODO: Allow scope specification search when 'declare reduction' is
  4380. // supported.
  4381. assert(ReductionIdScopeSpec.isEmpty() &&
  4382. "No support for scoped reduction identifiers yet.");
  4383. auto DN = ReductionId.getName();
  4384. auto OOK = DN.getCXXOverloadedOperator();
  4385. BinaryOperatorKind BOK = BO_Comma;
  4386. // OpenMP [2.14.3.6, reduction clause]
  4387. // C
  4388. // reduction-identifier is either an identifier or one of the following
  4389. // operators: +, -, *, &, |, ^, && and ||
  4390. // C++
  4391. // reduction-identifier is either an id-expression or one of the following
  4392. // operators: +, -, *, &, |, ^, && and ||
  4393. // FIXME: Only 'min' and 'max' identifiers are supported for now.
  4394. switch (OOK) {
  4395. case OO_Plus:
  4396. case OO_Minus:
  4397. BOK = BO_AddAssign;
  4398. break;
  4399. case OO_Star:
  4400. BOK = BO_MulAssign;
  4401. break;
  4402. case OO_Amp:
  4403. BOK = BO_AndAssign;
  4404. break;
  4405. case OO_Pipe:
  4406. BOK = BO_OrAssign;
  4407. break;
  4408. case OO_Caret:
  4409. BOK = BO_XorAssign;
  4410. break;
  4411. case OO_AmpAmp:
  4412. BOK = BO_LAnd;
  4413. break;
  4414. case OO_PipePipe:
  4415. BOK = BO_LOr;
  4416. break;
  4417. default:
  4418. if (auto II = DN.getAsIdentifierInfo()) {
  4419. if (II->isStr("max"))
  4420. BOK = BO_GT;
  4421. else if (II->isStr("min"))
  4422. BOK = BO_LT;
  4423. }
  4424. break;
  4425. }
  4426. SourceRange ReductionIdRange;
  4427. if (ReductionIdScopeSpec.isValid()) {
  4428. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  4429. }
  4430. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  4431. if (BOK == BO_Comma) {
  4432. // Not allowed reduction identifier is found.
  4433. Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
  4434. << ReductionIdRange;
  4435. return nullptr;
  4436. }
  4437. SmallVector<Expr *, 8> Vars;
  4438. for (auto RefExpr : VarList) {
  4439. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  4440. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4441. // It will be analyzed later.
  4442. Vars.push_back(RefExpr);
  4443. continue;
  4444. }
  4445. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  4446. RefExpr->isInstantiationDependent() ||
  4447. RefExpr->containsUnexpandedParameterPack()) {
  4448. // It will be analyzed later.
  4449. Vars.push_back(RefExpr);
  4450. continue;
  4451. }
  4452. auto ELoc = RefExpr->getExprLoc();
  4453. auto ERange = RefExpr->getSourceRange();
  4454. // OpenMP [2.1, C/C++]
  4455. // A list item is a variable or array section, subject to the restrictions
  4456. // specified in Section 2.4 on page 42 and in each of the sections
  4457. // describing clauses and directives for which a list appears.
  4458. // OpenMP [2.14.3.3, Restrictions, p.1]
  4459. // A variable that is part of another variable (as an array or
  4460. // structure element) cannot appear in a private clause.
  4461. auto DE = dyn_cast<DeclRefExpr>(RefExpr);
  4462. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4463. Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
  4464. continue;
  4465. }
  4466. auto D = DE->getDecl();
  4467. auto VD = cast<VarDecl>(D);
  4468. auto Type = VD->getType();
  4469. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  4470. // A variable that appears in a private clause must not have an incomplete
  4471. // type or a reference type.
  4472. if (RequireCompleteType(ELoc, Type,
  4473. diag::err_omp_reduction_incomplete_type))
  4474. continue;
  4475. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  4476. // Arrays may not appear in a reduction clause.
  4477. if (Type.getNonReferenceType()->isArrayType()) {
  4478. Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
  4479. bool IsDecl =
  4480. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4481. Diag(VD->getLocation(),
  4482. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4483. << VD;
  4484. continue;
  4485. }
  4486. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  4487. // A list item that appears in a reduction clause must not be
  4488. // const-qualified.
  4489. if (Type.getNonReferenceType().isConstant(Context)) {
  4490. Diag(ELoc, diag::err_omp_const_variable)
  4491. << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
  4492. bool IsDecl =
  4493. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4494. Diag(VD->getLocation(),
  4495. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4496. << VD;
  4497. continue;
  4498. }
  4499. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  4500. // If a list-item is a reference type then it must bind to the same object
  4501. // for all threads of the team.
  4502. VarDecl *VDDef = VD->getDefinition();
  4503. if (Type->isReferenceType() && VDDef) {
  4504. DSARefChecker Check(DSAStack);
  4505. if (Check.Visit(VDDef->getInit())) {
  4506. Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
  4507. Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  4508. continue;
  4509. }
  4510. }
  4511. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  4512. // The type of a list item that appears in a reduction clause must be valid
  4513. // for the reduction-identifier. For a max or min reduction in C, the type
  4514. // of the list item must be an allowed arithmetic data type: char, int,
  4515. // float, double, or _Bool, possibly modified with long, short, signed, or
  4516. // unsigned. For a max or min reduction in C++, the type of the list item
  4517. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  4518. // double, or bool, possibly modified with long, short, signed, or unsigned.
  4519. if ((BOK == BO_GT || BOK == BO_LT) &&
  4520. !(Type->isScalarType() ||
  4521. (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  4522. Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  4523. << getLangOpts().CPlusPlus;
  4524. bool IsDecl =
  4525. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4526. Diag(VD->getLocation(),
  4527. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4528. << VD;
  4529. continue;
  4530. }
  4531. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  4532. !getLangOpts().CPlusPlus && Type->isFloatingType()) {
  4533. Diag(ELoc, diag::err_omp_clause_floating_type_arg);
  4534. bool IsDecl =
  4535. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4536. Diag(VD->getLocation(),
  4537. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4538. << VD;
  4539. continue;
  4540. }
  4541. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  4542. getDiagnostics().setSuppressAllDiagnostics(true);
  4543. ExprResult ReductionOp =
  4544. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
  4545. RefExpr, RefExpr);
  4546. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4547. if (ReductionOp.isInvalid()) {
  4548. Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
  4549. << ReductionIdRange;
  4550. bool IsDecl =
  4551. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4552. Diag(VD->getLocation(),
  4553. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4554. << VD;
  4555. continue;
  4556. }
  4557. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4558. // in a Construct]
  4559. // Variables with the predetermined data-sharing attributes may not be
  4560. // listed in data-sharing attributes clauses, except for the cases
  4561. // listed below. For these exceptions only, listing a predetermined
  4562. // variable in a data-sharing attribute clause is allowed and overrides
  4563. // the variable's predetermined data-sharing attributes.
  4564. // OpenMP [2.14.3.6, Restrictions, p.3]
  4565. // Any number of reduction clauses can be specified on the directive,
  4566. // but a list item can appear only once in the reduction clauses for that
  4567. // directive.
  4568. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  4569. if (DVar.CKind == OMPC_reduction) {
  4570. Diag(ELoc, diag::err_omp_once_referenced)
  4571. << getOpenMPClauseName(OMPC_reduction);
  4572. if (DVar.RefExpr) {
  4573. Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  4574. }
  4575. } else if (DVar.CKind != OMPC_unknown) {
  4576. Diag(ELoc, diag::err_omp_wrong_dsa)
  4577. << getOpenMPClauseName(DVar.CKind)
  4578. << getOpenMPClauseName(OMPC_reduction);
  4579. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4580. continue;
  4581. }
  4582. // OpenMP [2.14.3.6, Restrictions, p.1]
  4583. // A list item that appears in a reduction clause of a worksharing
  4584. // construct must be shared in the parallel regions to which any of the
  4585. // worksharing regions arising from the worksharing construct bind.
  4586. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  4587. if (isOpenMPWorksharingDirective(CurrDir) &&
  4588. !isOpenMPParallelDirective(CurrDir)) {
  4589. DVar = DSAStack->getImplicitDSA(VD, true);
  4590. if (DVar.CKind != OMPC_shared) {
  4591. Diag(ELoc, diag::err_omp_required_access)
  4592. << getOpenMPClauseName(OMPC_reduction)
  4593. << getOpenMPClauseName(OMPC_shared);
  4594. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4595. continue;
  4596. }
  4597. }
  4598. CXXRecordDecl *RD = getLangOpts().CPlusPlus
  4599. ? Type.getNonReferenceType()->getAsCXXRecordDecl()
  4600. : nullptr;
  4601. // FIXME This code must be replaced by actual constructing/destructing of
  4602. // the reduction variable.
  4603. if (RD) {
  4604. CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
  4605. PartialDiagnostic PD =
  4606. PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
  4607. if (!CD ||
  4608. CheckConstructorAccess(ELoc, CD,
  4609. InitializedEntity::InitializeTemporary(Type),
  4610. CD->getAccess(), PD) == AR_inaccessible ||
  4611. CD->isDeleted()) {
  4612. Diag(ELoc, diag::err_omp_required_method)
  4613. << getOpenMPClauseName(OMPC_reduction) << 0;
  4614. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4615. VarDecl::DeclarationOnly;
  4616. Diag(VD->getLocation(),
  4617. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4618. << VD;
  4619. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4620. continue;
  4621. }
  4622. MarkFunctionReferenced(ELoc, CD);
  4623. DiagnoseUseOfDecl(CD, ELoc);
  4624. CXXDestructorDecl *DD = RD->getDestructor();
  4625. if (DD) {
  4626. if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
  4627. DD->isDeleted()) {
  4628. Diag(ELoc, diag::err_omp_required_method)
  4629. << getOpenMPClauseName(OMPC_reduction) << 4;
  4630. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4631. VarDecl::DeclarationOnly;
  4632. Diag(VD->getLocation(),
  4633. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4634. << VD;
  4635. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4636. continue;
  4637. }
  4638. MarkFunctionReferenced(ELoc, DD);
  4639. DiagnoseUseOfDecl(DD, ELoc);
  4640. }
  4641. }
  4642. DSAStack->addDSA(VD, DE, OMPC_reduction);
  4643. Vars.push_back(DE);
  4644. }
  4645. if (Vars.empty())
  4646. return nullptr;
  4647. return OMPReductionClause::Create(
  4648. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
  4649. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
  4650. }
  4651. OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
  4652. SourceLocation StartLoc,
  4653. SourceLocation LParenLoc,
  4654. SourceLocation ColonLoc,
  4655. SourceLocation EndLoc) {
  4656. SmallVector<Expr *, 8> Vars;
  4657. for (auto &RefExpr : VarList) {
  4658. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  4659. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4660. // It will be analyzed later.
  4661. Vars.push_back(RefExpr);
  4662. continue;
  4663. }
  4664. // OpenMP [2.14.3.7, linear clause]
  4665. // A list item that appears in a linear clause is subject to the private
  4666. // clause semantics described in Section 2.14.3.3 on page 159 except as
  4667. // noted. In addition, the value of the new list item on each iteration
  4668. // of the associated loop(s) corresponds to the value of the original
  4669. // list item before entering the construct plus the logical number of
  4670. // the iteration times linear-step.
  4671. SourceLocation ELoc = RefExpr->getExprLoc();
  4672. // OpenMP [2.1, C/C++]
  4673. // A list item is a variable name.
  4674. // OpenMP [2.14.3.3, Restrictions, p.1]
  4675. // A variable that is part of another variable (as an array or
  4676. // structure element) cannot appear in a private clause.
  4677. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  4678. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4679. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4680. continue;
  4681. }
  4682. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  4683. // OpenMP [2.14.3.7, linear clause]
  4684. // A list-item cannot appear in more than one linear clause.
  4685. // A list-item that appears in a linear clause cannot appear in any
  4686. // other data-sharing attribute clause.
  4687. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  4688. if (DVar.RefExpr) {
  4689. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  4690. << getOpenMPClauseName(OMPC_linear);
  4691. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4692. continue;
  4693. }
  4694. QualType QType = VD->getType();
  4695. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  4696. // It will be analyzed later.
  4697. Vars.push_back(DE);
  4698. continue;
  4699. }
  4700. // A variable must not have an incomplete type or a reference type.
  4701. if (RequireCompleteType(ELoc, QType,
  4702. diag::err_omp_linear_incomplete_type)) {
  4703. continue;
  4704. }
  4705. if (QType->isReferenceType()) {
  4706. Diag(ELoc, diag::err_omp_clause_ref_type_arg)
  4707. << getOpenMPClauseName(OMPC_linear) << QType;
  4708. bool IsDecl =
  4709. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4710. Diag(VD->getLocation(),
  4711. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4712. << VD;
  4713. continue;
  4714. }
  4715. // A list item must not be const-qualified.
  4716. if (QType.isConstant(Context)) {
  4717. Diag(ELoc, diag::err_omp_const_variable)
  4718. << getOpenMPClauseName(OMPC_linear);
  4719. bool IsDecl =
  4720. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4721. Diag(VD->getLocation(),
  4722. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4723. << VD;
  4724. continue;
  4725. }
  4726. // A list item must be of integral or pointer type.
  4727. QType = QType.getUnqualifiedType().getCanonicalType();
  4728. const Type *Ty = QType.getTypePtrOrNull();
  4729. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  4730. !Ty->isPointerType())) {
  4731. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
  4732. bool IsDecl =
  4733. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4734. Diag(VD->getLocation(),
  4735. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4736. << VD;
  4737. continue;
  4738. }
  4739. DSAStack->addDSA(VD, DE, OMPC_linear);
  4740. Vars.push_back(DE);
  4741. }
  4742. if (Vars.empty())
  4743. return nullptr;
  4744. Expr *StepExpr = Step;
  4745. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4746. !Step->isInstantiationDependent() &&
  4747. !Step->containsUnexpandedParameterPack()) {
  4748. SourceLocation StepLoc = Step->getLocStart();
  4749. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  4750. if (Val.isInvalid())
  4751. return nullptr;
  4752. StepExpr = Val.get();
  4753. // Warn about zero linear step (it would be probably better specified as
  4754. // making corresponding variables 'const').
  4755. llvm::APSInt Result;
  4756. if (StepExpr->isIntegerConstantExpr(Result, Context) &&
  4757. !Result.isNegative() && !Result.isStrictlyPositive())
  4758. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  4759. << (Vars.size() > 1);
  4760. }
  4761. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
  4762. Vars, StepExpr);
  4763. }
  4764. OMPClause *Sema::ActOnOpenMPAlignedClause(
  4765. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  4766. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  4767. SmallVector<Expr *, 8> Vars;
  4768. for (auto &RefExpr : VarList) {
  4769. assert(RefExpr && "NULL expr in OpenMP aligned clause.");
  4770. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4771. // It will be analyzed later.
  4772. Vars.push_back(RefExpr);
  4773. continue;
  4774. }
  4775. SourceLocation ELoc = RefExpr->getExprLoc();
  4776. // OpenMP [2.1, C/C++]
  4777. // A list item is a variable name.
  4778. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  4779. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4780. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4781. continue;
  4782. }
  4783. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  4784. // OpenMP [2.8.1, simd construct, Restrictions]
  4785. // The type of list items appearing in the aligned clause must be
  4786. // array, pointer, reference to array, or reference to pointer.
  4787. QualType QType = DE->getType()
  4788. .getNonReferenceType()
  4789. .getUnqualifiedType()
  4790. .getCanonicalType();
  4791. const Type *Ty = QType.getTypePtrOrNull();
  4792. if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
  4793. !Ty->isPointerType())) {
  4794. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  4795. << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
  4796. bool IsDecl =
  4797. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  4798. Diag(VD->getLocation(),
  4799. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4800. << VD;
  4801. continue;
  4802. }
  4803. // OpenMP [2.8.1, simd construct, Restrictions]
  4804. // A list-item cannot appear in more than one aligned clause.
  4805. if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
  4806. Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
  4807. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  4808. << getOpenMPClauseName(OMPC_aligned);
  4809. continue;
  4810. }
  4811. Vars.push_back(DE);
  4812. }
  4813. // OpenMP [2.8.1, simd construct, Description]
  4814. // The parameter of the aligned clause, alignment, must be a constant
  4815. // positive integer expression.
  4816. // If no optional parameter is specified, implementation-defined default
  4817. // alignments for SIMD instructions on the target platforms are assumed.
  4818. if (Alignment != nullptr) {
  4819. ExprResult AlignResult =
  4820. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  4821. if (AlignResult.isInvalid())
  4822. return nullptr;
  4823. Alignment = AlignResult.get();
  4824. }
  4825. if (Vars.empty())
  4826. return nullptr;
  4827. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  4828. EndLoc, Vars, Alignment);
  4829. }
  4830. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  4831. SourceLocation StartLoc,
  4832. SourceLocation LParenLoc,
  4833. SourceLocation EndLoc) {
  4834. SmallVector<Expr *, 8> Vars;
  4835. for (auto &RefExpr : VarList) {
  4836. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  4837. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4838. // It will be analyzed later.
  4839. Vars.push_back(RefExpr);
  4840. continue;
  4841. }
  4842. SourceLocation ELoc = RefExpr->getExprLoc();
  4843. // OpenMP [2.1, C/C++]
  4844. // A list item is a variable name.
  4845. // OpenMP [2.14.4.1, Restrictions, p.1]
  4846. // A list item that appears in a copyin clause must be threadprivate.
  4847. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  4848. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4849. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4850. continue;
  4851. }
  4852. Decl *D = DE->getDecl();
  4853. VarDecl *VD = cast<VarDecl>(D);
  4854. QualType Type = VD->getType();
  4855. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  4856. // It will be analyzed later.
  4857. Vars.push_back(DE);
  4858. continue;
  4859. }
  4860. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  4861. // A list item that appears in a copyin clause must be threadprivate.
  4862. if (!DSAStack->isThreadPrivate(VD)) {
  4863. Diag(ELoc, diag::err_omp_required_access)
  4864. << getOpenMPClauseName(OMPC_copyin)
  4865. << getOpenMPDirectiveName(OMPD_threadprivate);
  4866. continue;
  4867. }
  4868. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  4869. // A variable of class type (or array thereof) that appears in a
  4870. // copyin clause requires an accessible, unambiguous copy assignment
  4871. // operator for the class type.
  4872. Type = Context.getBaseElementType(Type);
  4873. CXXRecordDecl *RD =
  4874. getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  4875. // FIXME This code must be replaced by actual assignment of the
  4876. // threadprivate variable.
  4877. if (RD) {
  4878. CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
  4879. DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
  4880. if (MD) {
  4881. if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
  4882. MD->isDeleted()) {
  4883. Diag(ELoc, diag::err_omp_required_method)
  4884. << getOpenMPClauseName(OMPC_copyin) << 2;
  4885. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4886. VarDecl::DeclarationOnly;
  4887. Diag(VD->getLocation(),
  4888. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4889. << VD;
  4890. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4891. continue;
  4892. }
  4893. MarkFunctionReferenced(ELoc, MD);
  4894. DiagnoseUseOfDecl(MD, ELoc);
  4895. }
  4896. }
  4897. DSAStack->addDSA(VD, DE, OMPC_copyin);
  4898. Vars.push_back(DE);
  4899. }
  4900. if (Vars.empty())
  4901. return nullptr;
  4902. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  4903. }
  4904. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  4905. SourceLocation StartLoc,
  4906. SourceLocation LParenLoc,
  4907. SourceLocation EndLoc) {
  4908. SmallVector<Expr *, 8> Vars;
  4909. for (auto &RefExpr : VarList) {
  4910. assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
  4911. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  4912. // It will be analyzed later.
  4913. Vars.push_back(RefExpr);
  4914. continue;
  4915. }
  4916. SourceLocation ELoc = RefExpr->getExprLoc();
  4917. // OpenMP [2.1, C/C++]
  4918. // A list item is a variable name.
  4919. // OpenMP [2.14.4.1, Restrictions, p.1]
  4920. // A list item that appears in a copyin clause must be threadprivate.
  4921. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  4922. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  4923. Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
  4924. continue;
  4925. }
  4926. Decl *D = DE->getDecl();
  4927. VarDecl *VD = cast<VarDecl>(D);
  4928. QualType Type = VD->getType();
  4929. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  4930. // It will be analyzed later.
  4931. Vars.push_back(DE);
  4932. continue;
  4933. }
  4934. // OpenMP [2.14.4.2, Restrictions, p.2]
  4935. // A list item that appears in a copyprivate clause may not appear in a
  4936. // private or firstprivate clause on the single construct.
  4937. if (!DSAStack->isThreadPrivate(VD)) {
  4938. auto DVar = DSAStack->getTopDSA(VD, false);
  4939. if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
  4940. !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
  4941. Diag(ELoc, diag::err_omp_wrong_dsa)
  4942. << getOpenMPClauseName(DVar.CKind)
  4943. << getOpenMPClauseName(OMPC_copyprivate);
  4944. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4945. continue;
  4946. }
  4947. // OpenMP [2.11.4.2, Restrictions, p.1]
  4948. // All list items that appear in a copyprivate clause must be either
  4949. // threadprivate or private in the enclosing context.
  4950. if (DVar.CKind == OMPC_unknown) {
  4951. DVar = DSAStack->getImplicitDSA(VD, false);
  4952. if (DVar.CKind == OMPC_shared) {
  4953. Diag(ELoc, diag::err_omp_required_access)
  4954. << getOpenMPClauseName(OMPC_copyprivate)
  4955. << "threadprivate or private in the enclosing context";
  4956. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  4957. continue;
  4958. }
  4959. }
  4960. }
  4961. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  4962. // A variable of class type (or array thereof) that appears in a
  4963. // copyin clause requires an accessible, unambiguous copy assignment
  4964. // operator for the class type.
  4965. Type = Context.getBaseElementType(Type);
  4966. CXXRecordDecl *RD =
  4967. getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  4968. // FIXME This code must be replaced by actual assignment of the
  4969. // threadprivate variable.
  4970. if (RD) {
  4971. CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
  4972. DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
  4973. if (MD) {
  4974. if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
  4975. MD->isDeleted()) {
  4976. Diag(ELoc, diag::err_omp_required_method)
  4977. << getOpenMPClauseName(OMPC_copyprivate) << 2;
  4978. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  4979. VarDecl::DeclarationOnly;
  4980. Diag(VD->getLocation(),
  4981. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  4982. << VD;
  4983. Diag(RD->getLocation(), diag::note_previous_decl) << RD;
  4984. continue;
  4985. }
  4986. MarkFunctionReferenced(ELoc, MD);
  4987. DiagnoseUseOfDecl(MD, ELoc);
  4988. }
  4989. }
  4990. // No need to mark vars as copyprivate, they are already threadprivate or
  4991. // implicitly private.
  4992. Vars.push_back(DE);
  4993. }
  4994. if (Vars.empty())
  4995. return nullptr;
  4996. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  4997. }
  4998. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  4999. SourceLocation StartLoc,
  5000. SourceLocation LParenLoc,
  5001. SourceLocation EndLoc) {
  5002. if (VarList.empty())
  5003. return nullptr;
  5004. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  5005. }