Expr.cpp 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118
  1. //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Expr class and subclasses.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/Expr.h"
  13. #include "clang/AST/APValue.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/ComputeDependence.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/DependenceFlags.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/IgnoreExpr.h"
  24. #include "clang/AST/Mangle.h"
  25. #include "clang/AST/RecordLayout.h"
  26. #include "clang/AST/StmtVisitor.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/CharInfo.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/Lexer.h"
  32. #include "clang/Lex/LiteralSupport.h"
  33. #include "clang/Lex/Preprocessor.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/Format.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm>
  38. #include <cstring>
  39. #include <optional>
  40. using namespace clang;
  41. const Expr *Expr::getBestDynamicClassTypeExpr() const {
  42. const Expr *E = this;
  43. while (true) {
  44. E = E->IgnoreParenBaseCasts();
  45. // Follow the RHS of a comma operator.
  46. if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  47. if (BO->getOpcode() == BO_Comma) {
  48. E = BO->getRHS();
  49. continue;
  50. }
  51. }
  52. // Step into initializer for materialized temporaries.
  53. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  54. E = MTE->getSubExpr();
  55. continue;
  56. }
  57. break;
  58. }
  59. return E;
  60. }
  61. const CXXRecordDecl *Expr::getBestDynamicClassType() const {
  62. const Expr *E = getBestDynamicClassTypeExpr();
  63. QualType DerivedType = E->getType();
  64. if (const PointerType *PTy = DerivedType->getAs<PointerType>())
  65. DerivedType = PTy->getPointeeType();
  66. if (DerivedType->isDependentType())
  67. return nullptr;
  68. const RecordType *Ty = DerivedType->castAs<RecordType>();
  69. Decl *D = Ty->getDecl();
  70. return cast<CXXRecordDecl>(D);
  71. }
  72. const Expr *Expr::skipRValueSubobjectAdjustments(
  73. SmallVectorImpl<const Expr *> &CommaLHSs,
  74. SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
  75. const Expr *E = this;
  76. while (true) {
  77. E = E->IgnoreParens();
  78. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  79. if ((CE->getCastKind() == CK_DerivedToBase ||
  80. CE->getCastKind() == CK_UncheckedDerivedToBase) &&
  81. E->getType()->isRecordType()) {
  82. E = CE->getSubExpr();
  83. auto *Derived =
  84. cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
  85. Adjustments.push_back(SubobjectAdjustment(CE, Derived));
  86. continue;
  87. }
  88. if (CE->getCastKind() == CK_NoOp) {
  89. E = CE->getSubExpr();
  90. continue;
  91. }
  92. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  93. if (!ME->isArrow()) {
  94. assert(ME->getBase()->getType()->isRecordType());
  95. if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  96. if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
  97. E = ME->getBase();
  98. Adjustments.push_back(SubobjectAdjustment(Field));
  99. continue;
  100. }
  101. }
  102. }
  103. } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  104. if (BO->getOpcode() == BO_PtrMemD) {
  105. assert(BO->getRHS()->isPRValue());
  106. E = BO->getLHS();
  107. const MemberPointerType *MPT =
  108. BO->getRHS()->getType()->getAs<MemberPointerType>();
  109. Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
  110. continue;
  111. }
  112. if (BO->getOpcode() == BO_Comma) {
  113. CommaLHSs.push_back(BO->getLHS());
  114. E = BO->getRHS();
  115. continue;
  116. }
  117. }
  118. // Nothing changed.
  119. break;
  120. }
  121. return E;
  122. }
  123. bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
  124. const Expr *E = IgnoreParens();
  125. // If this value has _Bool type, it is obvious 0/1.
  126. if (E->getType()->isBooleanType()) return true;
  127. // If this is a non-scalar-integer type, we don't care enough to try.
  128. if (!E->getType()->isIntegralOrEnumerationType()) return false;
  129. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  130. switch (UO->getOpcode()) {
  131. case UO_Plus:
  132. return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
  133. case UO_LNot:
  134. return true;
  135. default:
  136. return false;
  137. }
  138. }
  139. // Only look through implicit casts. If the user writes
  140. // '(int) (a && b)' treat it as an arbitrary int.
  141. // FIXME: Should we look through any cast expression in !Semantic mode?
  142. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
  143. return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
  144. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  145. switch (BO->getOpcode()) {
  146. default: return false;
  147. case BO_LT: // Relational operators.
  148. case BO_GT:
  149. case BO_LE:
  150. case BO_GE:
  151. case BO_EQ: // Equality operators.
  152. case BO_NE:
  153. case BO_LAnd: // AND operator.
  154. case BO_LOr: // Logical OR operator.
  155. return true;
  156. case BO_And: // Bitwise AND operator.
  157. case BO_Xor: // Bitwise XOR operator.
  158. case BO_Or: // Bitwise OR operator.
  159. // Handle things like (x==2)|(y==12).
  160. return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
  161. BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
  162. case BO_Comma:
  163. case BO_Assign:
  164. return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
  165. }
  166. }
  167. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
  168. return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
  169. CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
  170. if (isa<ObjCBoolLiteralExpr>(E))
  171. return true;
  172. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  173. return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
  174. if (const FieldDecl *FD = E->getSourceBitField())
  175. if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
  176. !FD->getBitWidth()->isValueDependent() &&
  177. FD->getBitWidthValue(FD->getASTContext()) == 1)
  178. return true;
  179. return false;
  180. }
  181. bool Expr::isFlexibleArrayMemberLike(
  182. ASTContext &Context,
  183. LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
  184. bool IgnoreTemplateOrMacroSubstitution) const {
  185. // For compatibility with existing code, we treat arrays of length 0 or
  186. // 1 as flexible array members.
  187. const auto *CAT = Context.getAsConstantArrayType(getType());
  188. if (CAT) {
  189. llvm::APInt Size = CAT->getSize();
  190. using FAMKind = LangOptions::StrictFlexArraysLevelKind;
  191. if (StrictFlexArraysLevel == FAMKind::IncompleteOnly)
  192. return false;
  193. // GCC extension, only allowed to represent a FAM.
  194. if (Size == 0)
  195. return true;
  196. if (StrictFlexArraysLevel == FAMKind::ZeroOrIncomplete && Size.uge(1))
  197. return false;
  198. if (StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete && Size.uge(2))
  199. return false;
  200. } else if (!Context.getAsIncompleteArrayType(getType()))
  201. return false;
  202. const Expr *E = IgnoreParens();
  203. const NamedDecl *ND = nullptr;
  204. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  205. ND = DRE->getDecl();
  206. else if (const auto *ME = dyn_cast<MemberExpr>(E))
  207. ND = ME->getMemberDecl();
  208. else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  209. return IRE->getDecl()->getNextIvar() == nullptr;
  210. if (!ND)
  211. return false;
  212. // A flexible array member must be the last member in the class.
  213. // FIXME: If the base type of the member expr is not FD->getParent(),
  214. // this should not be treated as a flexible array member access.
  215. if (const auto *FD = dyn_cast<FieldDecl>(ND)) {
  216. // GCC treats an array memeber of a union as an FAM if the size is one or
  217. // zero.
  218. if (CAT) {
  219. llvm::APInt Size = CAT->getSize();
  220. if (FD->getParent()->isUnion() && (Size.isZero() || Size.isOne()))
  221. return true;
  222. }
  223. // Don't consider sizes resulting from macro expansions or template argument
  224. // substitution to form C89 tail-padded arrays.
  225. if (IgnoreTemplateOrMacroSubstitution) {
  226. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  227. while (TInfo) {
  228. TypeLoc TL = TInfo->getTypeLoc();
  229. // Look through typedefs.
  230. if (TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
  231. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  232. TInfo = TDL->getTypeSourceInfo();
  233. continue;
  234. }
  235. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  236. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  237. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  238. return false;
  239. }
  240. break;
  241. }
  242. }
  243. RecordDecl::field_iterator FI(
  244. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  245. return ++FI == FD->getParent()->field_end();
  246. }
  247. return false;
  248. }
  249. const ValueDecl *
  250. Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
  251. Expr::EvalResult Eval;
  252. if (EvaluateAsConstantExpr(Eval, Context)) {
  253. APValue &Value = Eval.Val;
  254. if (Value.isMemberPointer())
  255. return Value.getMemberPointerDecl();
  256. if (Value.isLValue() && Value.getLValueOffset().isZero())
  257. return Value.getLValueBase().dyn_cast<const ValueDecl *>();
  258. }
  259. return nullptr;
  260. }
  261. // Amusing macro metaprogramming hack: check whether a class provides
  262. // a more specific implementation of getExprLoc().
  263. //
  264. // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
  265. namespace {
  266. /// This implementation is used when a class provides a custom
  267. /// implementation of getExprLoc.
  268. template <class E, class T>
  269. SourceLocation getExprLocImpl(const Expr *expr,
  270. SourceLocation (T::*v)() const) {
  271. return static_cast<const E*>(expr)->getExprLoc();
  272. }
  273. /// This implementation is used when a class doesn't provide
  274. /// a custom implementation of getExprLoc. Overload resolution
  275. /// should pick it over the implementation above because it's
  276. /// more specialized according to function template partial ordering.
  277. template <class E>
  278. SourceLocation getExprLocImpl(const Expr *expr,
  279. SourceLocation (Expr::*v)() const) {
  280. return static_cast<const E *>(expr)->getBeginLoc();
  281. }
  282. }
  283. SourceLocation Expr::getExprLoc() const {
  284. switch (getStmtClass()) {
  285. case Stmt::NoStmtClass: llvm_unreachable("statement without class");
  286. #define ABSTRACT_STMT(type)
  287. #define STMT(type, base) \
  288. case Stmt::type##Class: break;
  289. #define EXPR(type, base) \
  290. case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
  291. #include "clang/AST/StmtNodes.inc"
  292. }
  293. llvm_unreachable("unknown expression kind");
  294. }
  295. //===----------------------------------------------------------------------===//
  296. // Primary Expressions.
  297. //===----------------------------------------------------------------------===//
  298. static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
  299. assert((Kind == ConstantExpr::RSK_APValue ||
  300. Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
  301. "Invalid StorageKind Value");
  302. (void)Kind;
  303. }
  304. ConstantExpr::ResultStorageKind
  305. ConstantExpr::getStorageKind(const APValue &Value) {
  306. switch (Value.getKind()) {
  307. case APValue::None:
  308. case APValue::Indeterminate:
  309. return ConstantExpr::RSK_None;
  310. case APValue::Int:
  311. if (!Value.getInt().needsCleanup())
  312. return ConstantExpr::RSK_Int64;
  313. [[fallthrough]];
  314. default:
  315. return ConstantExpr::RSK_APValue;
  316. }
  317. }
  318. ConstantExpr::ResultStorageKind
  319. ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
  320. if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
  321. return ConstantExpr::RSK_Int64;
  322. return ConstantExpr::RSK_APValue;
  323. }
  324. ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
  325. bool IsImmediateInvocation)
  326. : FullExpr(ConstantExprClass, SubExpr) {
  327. ConstantExprBits.ResultKind = StorageKind;
  328. ConstantExprBits.APValueKind = APValue::None;
  329. ConstantExprBits.IsUnsigned = false;
  330. ConstantExprBits.BitWidth = 0;
  331. ConstantExprBits.HasCleanup = false;
  332. ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
  333. if (StorageKind == ConstantExpr::RSK_APValue)
  334. ::new (getTrailingObjects<APValue>()) APValue();
  335. }
  336. ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
  337. ResultStorageKind StorageKind,
  338. bool IsImmediateInvocation) {
  339. assert(!isa<ConstantExpr>(E));
  340. AssertResultStorageKind(StorageKind);
  341. unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
  342. StorageKind == ConstantExpr::RSK_APValue,
  343. StorageKind == ConstantExpr::RSK_Int64);
  344. void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
  345. return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
  346. }
  347. ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
  348. const APValue &Result) {
  349. ResultStorageKind StorageKind = getStorageKind(Result);
  350. ConstantExpr *Self = Create(Context, E, StorageKind);
  351. Self->SetResult(Result, Context);
  352. return Self;
  353. }
  354. ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
  355. : FullExpr(ConstantExprClass, Empty) {
  356. ConstantExprBits.ResultKind = StorageKind;
  357. if (StorageKind == ConstantExpr::RSK_APValue)
  358. ::new (getTrailingObjects<APValue>()) APValue();
  359. }
  360. ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
  361. ResultStorageKind StorageKind) {
  362. AssertResultStorageKind(StorageKind);
  363. unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
  364. StorageKind == ConstantExpr::RSK_APValue,
  365. StorageKind == ConstantExpr::RSK_Int64);
  366. void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
  367. return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
  368. }
  369. void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
  370. assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
  371. "Invalid storage for this value kind");
  372. ConstantExprBits.APValueKind = Value.getKind();
  373. switch (ConstantExprBits.ResultKind) {
  374. case RSK_None:
  375. return;
  376. case RSK_Int64:
  377. Int64Result() = *Value.getInt().getRawData();
  378. ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
  379. ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
  380. return;
  381. case RSK_APValue:
  382. if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
  383. ConstantExprBits.HasCleanup = true;
  384. Context.addDestruction(&APValueResult());
  385. }
  386. APValueResult() = std::move(Value);
  387. return;
  388. }
  389. llvm_unreachable("Invalid ResultKind Bits");
  390. }
  391. llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
  392. switch (ConstantExprBits.ResultKind) {
  393. case ConstantExpr::RSK_APValue:
  394. return APValueResult().getInt();
  395. case ConstantExpr::RSK_Int64:
  396. return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
  397. ConstantExprBits.IsUnsigned);
  398. default:
  399. llvm_unreachable("invalid Accessor");
  400. }
  401. }
  402. APValue ConstantExpr::getAPValueResult() const {
  403. switch (ConstantExprBits.ResultKind) {
  404. case ConstantExpr::RSK_APValue:
  405. return APValueResult();
  406. case ConstantExpr::RSK_Int64:
  407. return APValue(
  408. llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
  409. ConstantExprBits.IsUnsigned));
  410. case ConstantExpr::RSK_None:
  411. if (ConstantExprBits.APValueKind == APValue::Indeterminate)
  412. return APValue::IndeterminateValue();
  413. return APValue();
  414. }
  415. llvm_unreachable("invalid ResultKind");
  416. }
  417. DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
  418. bool RefersToEnclosingVariableOrCapture, QualType T,
  419. ExprValueKind VK, SourceLocation L,
  420. const DeclarationNameLoc &LocInfo,
  421. NonOdrUseReason NOUR)
  422. : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
  423. DeclRefExprBits.HasQualifier = false;
  424. DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
  425. DeclRefExprBits.HasFoundDecl = false;
  426. DeclRefExprBits.HadMultipleCandidates = false;
  427. DeclRefExprBits.RefersToEnclosingVariableOrCapture =
  428. RefersToEnclosingVariableOrCapture;
  429. DeclRefExprBits.NonOdrUseReason = NOUR;
  430. DeclRefExprBits.Loc = L;
  431. setDependence(computeDependence(this, Ctx));
  432. }
  433. DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
  434. NestedNameSpecifierLoc QualifierLoc,
  435. SourceLocation TemplateKWLoc, ValueDecl *D,
  436. bool RefersToEnclosingVariableOrCapture,
  437. const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
  438. const TemplateArgumentListInfo *TemplateArgs,
  439. QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
  440. : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
  441. DNLoc(NameInfo.getInfo()) {
  442. DeclRefExprBits.Loc = NameInfo.getLoc();
  443. DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
  444. if (QualifierLoc)
  445. new (getTrailingObjects<NestedNameSpecifierLoc>())
  446. NestedNameSpecifierLoc(QualifierLoc);
  447. DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
  448. if (FoundD)
  449. *getTrailingObjects<NamedDecl *>() = FoundD;
  450. DeclRefExprBits.HasTemplateKWAndArgsInfo
  451. = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
  452. DeclRefExprBits.RefersToEnclosingVariableOrCapture =
  453. RefersToEnclosingVariableOrCapture;
  454. DeclRefExprBits.NonOdrUseReason = NOUR;
  455. if (TemplateArgs) {
  456. auto Deps = TemplateArgumentDependence::None;
  457. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
  458. TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
  459. Deps);
  460. assert(!(Deps & TemplateArgumentDependence::Dependent) &&
  461. "built a DeclRefExpr with dependent template args");
  462. } else if (TemplateKWLoc.isValid()) {
  463. getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
  464. TemplateKWLoc);
  465. }
  466. DeclRefExprBits.HadMultipleCandidates = 0;
  467. setDependence(computeDependence(this, Ctx));
  468. }
  469. DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
  470. NestedNameSpecifierLoc QualifierLoc,
  471. SourceLocation TemplateKWLoc, ValueDecl *D,
  472. bool RefersToEnclosingVariableOrCapture,
  473. SourceLocation NameLoc, QualType T,
  474. ExprValueKind VK, NamedDecl *FoundD,
  475. const TemplateArgumentListInfo *TemplateArgs,
  476. NonOdrUseReason NOUR) {
  477. return Create(Context, QualifierLoc, TemplateKWLoc, D,
  478. RefersToEnclosingVariableOrCapture,
  479. DeclarationNameInfo(D->getDeclName(), NameLoc),
  480. T, VK, FoundD, TemplateArgs, NOUR);
  481. }
  482. DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
  483. NestedNameSpecifierLoc QualifierLoc,
  484. SourceLocation TemplateKWLoc, ValueDecl *D,
  485. bool RefersToEnclosingVariableOrCapture,
  486. const DeclarationNameInfo &NameInfo,
  487. QualType T, ExprValueKind VK,
  488. NamedDecl *FoundD,
  489. const TemplateArgumentListInfo *TemplateArgs,
  490. NonOdrUseReason NOUR) {
  491. // Filter out cases where the found Decl is the same as the value refenenced.
  492. if (D == FoundD)
  493. FoundD = nullptr;
  494. bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
  495. std::size_t Size =
  496. totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
  497. ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
  498. QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
  499. HasTemplateKWAndArgsInfo ? 1 : 0,
  500. TemplateArgs ? TemplateArgs->size() : 0);
  501. void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
  502. return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
  503. RefersToEnclosingVariableOrCapture, NameInfo,
  504. FoundD, TemplateArgs, T, VK, NOUR);
  505. }
  506. DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
  507. bool HasQualifier,
  508. bool HasFoundDecl,
  509. bool HasTemplateKWAndArgsInfo,
  510. unsigned NumTemplateArgs) {
  511. assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
  512. std::size_t Size =
  513. totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
  514. ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
  515. HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
  516. NumTemplateArgs);
  517. void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
  518. return new (Mem) DeclRefExpr(EmptyShell());
  519. }
  520. void DeclRefExpr::setDecl(ValueDecl *NewD) {
  521. D = NewD;
  522. if (getType()->isUndeducedType())
  523. setType(NewD->getType());
  524. setDependence(computeDependence(this, NewD->getASTContext()));
  525. }
  526. SourceLocation DeclRefExpr::getBeginLoc() const {
  527. if (hasQualifier())
  528. return getQualifierLoc().getBeginLoc();
  529. return getNameInfo().getBeginLoc();
  530. }
  531. SourceLocation DeclRefExpr::getEndLoc() const {
  532. if (hasExplicitTemplateArgs())
  533. return getRAngleLoc();
  534. return getNameInfo().getEndLoc();
  535. }
  536. SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
  537. SourceLocation LParen,
  538. SourceLocation RParen,
  539. QualType ResultTy,
  540. TypeSourceInfo *TSI)
  541. : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
  542. OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
  543. setTypeSourceInfo(TSI);
  544. setDependence(computeDependence(this));
  545. }
  546. SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
  547. QualType ResultTy)
  548. : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
  549. SYCLUniqueStableNameExpr *
  550. SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
  551. SourceLocation LParen, SourceLocation RParen,
  552. TypeSourceInfo *TSI) {
  553. QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
  554. return new (Ctx)
  555. SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
  556. }
  557. SYCLUniqueStableNameExpr *
  558. SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
  559. QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
  560. return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
  561. }
  562. std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
  563. return SYCLUniqueStableNameExpr::ComputeName(Context,
  564. getTypeSourceInfo()->getType());
  565. }
  566. std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
  567. QualType Ty) {
  568. auto MangleCallback = [](ASTContext &Ctx,
  569. const NamedDecl *ND) -> std::optional<unsigned> {
  570. if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
  571. return RD->getDeviceLambdaManglingNumber();
  572. return std::nullopt;
  573. };
  574. std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
  575. Context, Context.getDiagnostics(), MangleCallback)};
  576. std::string Buffer;
  577. Buffer.reserve(128);
  578. llvm::raw_string_ostream Out(Buffer);
  579. Ctx->mangleTypeName(Ty, Out);
  580. return Out.str();
  581. }
  582. PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
  583. StringLiteral *SL)
  584. : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
  585. PredefinedExprBits.Kind = IK;
  586. assert((getIdentKind() == IK) &&
  587. "IdentKind do not fit in PredefinedExprBitfields!");
  588. bool HasFunctionName = SL != nullptr;
  589. PredefinedExprBits.HasFunctionName = HasFunctionName;
  590. PredefinedExprBits.Loc = L;
  591. if (HasFunctionName)
  592. setFunctionName(SL);
  593. setDependence(computeDependence(this));
  594. }
  595. PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
  596. : Expr(PredefinedExprClass, Empty) {
  597. PredefinedExprBits.HasFunctionName = HasFunctionName;
  598. }
  599. PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
  600. QualType FNTy, IdentKind IK,
  601. StringLiteral *SL) {
  602. bool HasFunctionName = SL != nullptr;
  603. void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
  604. alignof(PredefinedExpr));
  605. return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
  606. }
  607. PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
  608. bool HasFunctionName) {
  609. void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
  610. alignof(PredefinedExpr));
  611. return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
  612. }
  613. StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
  614. switch (IK) {
  615. case Func:
  616. return "__func__";
  617. case Function:
  618. return "__FUNCTION__";
  619. case FuncDName:
  620. return "__FUNCDNAME__";
  621. case LFunction:
  622. return "L__FUNCTION__";
  623. case PrettyFunction:
  624. return "__PRETTY_FUNCTION__";
  625. case FuncSig:
  626. return "__FUNCSIG__";
  627. case LFuncSig:
  628. return "L__FUNCSIG__";
  629. case PrettyFunctionNoVirtual:
  630. break;
  631. }
  632. llvm_unreachable("Unknown ident kind for PredefinedExpr");
  633. }
  634. // FIXME: Maybe this should use DeclPrinter with a special "print predefined
  635. // expr" policy instead.
  636. std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
  637. ASTContext &Context = CurrentDecl->getASTContext();
  638. if (IK == PredefinedExpr::FuncDName) {
  639. if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
  640. std::unique_ptr<MangleContext> MC;
  641. MC.reset(Context.createMangleContext());
  642. if (MC->shouldMangleDeclName(ND)) {
  643. SmallString<256> Buffer;
  644. llvm::raw_svector_ostream Out(Buffer);
  645. GlobalDecl GD;
  646. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
  647. GD = GlobalDecl(CD, Ctor_Base);
  648. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
  649. GD = GlobalDecl(DD, Dtor_Base);
  650. else if (ND->hasAttr<CUDAGlobalAttr>())
  651. GD = GlobalDecl(cast<FunctionDecl>(ND));
  652. else
  653. GD = GlobalDecl(ND);
  654. MC->mangleName(GD, Out);
  655. if (!Buffer.empty() && Buffer.front() == '\01')
  656. return std::string(Buffer.substr(1));
  657. return std::string(Buffer.str());
  658. }
  659. return std::string(ND->getIdentifier()->getName());
  660. }
  661. return "";
  662. }
  663. if (isa<BlockDecl>(CurrentDecl)) {
  664. // For blocks we only emit something if it is enclosed in a function
  665. // For top-level block we'd like to include the name of variable, but we
  666. // don't have it at this point.
  667. auto DC = CurrentDecl->getDeclContext();
  668. if (DC->isFileContext())
  669. return "";
  670. SmallString<256> Buffer;
  671. llvm::raw_svector_ostream Out(Buffer);
  672. if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
  673. // For nested blocks, propagate up to the parent.
  674. Out << ComputeName(IK, DCBlock);
  675. else if (auto *DCDecl = dyn_cast<Decl>(DC))
  676. Out << ComputeName(IK, DCDecl) << "_block_invoke";
  677. return std::string(Out.str());
  678. }
  679. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
  680. if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
  681. IK != FuncSig && IK != LFuncSig)
  682. return FD->getNameAsString();
  683. SmallString<256> Name;
  684. llvm::raw_svector_ostream Out(Name);
  685. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  686. if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
  687. Out << "virtual ";
  688. if (MD->isStatic())
  689. Out << "static ";
  690. }
  691. PrintingPolicy Policy(Context.getLangOpts());
  692. std::string Proto;
  693. llvm::raw_string_ostream POut(Proto);
  694. const FunctionDecl *Decl = FD;
  695. if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
  696. Decl = Pattern;
  697. const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
  698. const FunctionProtoType *FT = nullptr;
  699. if (FD->hasWrittenPrototype())
  700. FT = dyn_cast<FunctionProtoType>(AFT);
  701. if (IK == FuncSig || IK == LFuncSig) {
  702. switch (AFT->getCallConv()) {
  703. case CC_C: POut << "__cdecl "; break;
  704. case CC_X86StdCall: POut << "__stdcall "; break;
  705. case CC_X86FastCall: POut << "__fastcall "; break;
  706. case CC_X86ThisCall: POut << "__thiscall "; break;
  707. case CC_X86VectorCall: POut << "__vectorcall "; break;
  708. case CC_X86RegCall: POut << "__regcall "; break;
  709. // Only bother printing the conventions that MSVC knows about.
  710. default: break;
  711. }
  712. }
  713. FD->printQualifiedName(POut, Policy);
  714. POut << "(";
  715. if (FT) {
  716. for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
  717. if (i) POut << ", ";
  718. POut << Decl->getParamDecl(i)->getType().stream(Policy);
  719. }
  720. if (FT->isVariadic()) {
  721. if (FD->getNumParams()) POut << ", ";
  722. POut << "...";
  723. } else if ((IK == FuncSig || IK == LFuncSig ||
  724. !Context.getLangOpts().CPlusPlus) &&
  725. !Decl->getNumParams()) {
  726. POut << "void";
  727. }
  728. }
  729. POut << ")";
  730. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  731. assert(FT && "We must have a written prototype in this case.");
  732. if (FT->isConst())
  733. POut << " const";
  734. if (FT->isVolatile())
  735. POut << " volatile";
  736. RefQualifierKind Ref = MD->getRefQualifier();
  737. if (Ref == RQ_LValue)
  738. POut << " &";
  739. else if (Ref == RQ_RValue)
  740. POut << " &&";
  741. }
  742. typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
  743. SpecsTy Specs;
  744. const DeclContext *Ctx = FD->getDeclContext();
  745. while (Ctx && isa<NamedDecl>(Ctx)) {
  746. const ClassTemplateSpecializationDecl *Spec
  747. = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
  748. if (Spec && !Spec->isExplicitSpecialization())
  749. Specs.push_back(Spec);
  750. Ctx = Ctx->getParent();
  751. }
  752. std::string TemplateParams;
  753. llvm::raw_string_ostream TOut(TemplateParams);
  754. for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
  755. const TemplateParameterList *Params =
  756. D->getSpecializedTemplate()->getTemplateParameters();
  757. const TemplateArgumentList &Args = D->getTemplateArgs();
  758. assert(Params->size() == Args.size());
  759. for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
  760. StringRef Param = Params->getParam(i)->getName();
  761. if (Param.empty()) continue;
  762. TOut << Param << " = ";
  763. Args.get(i).print(Policy, TOut,
  764. TemplateParameterList::shouldIncludeTypeForArgument(
  765. Policy, Params, i));
  766. TOut << ", ";
  767. }
  768. }
  769. FunctionTemplateSpecializationInfo *FSI
  770. = FD->getTemplateSpecializationInfo();
  771. if (FSI && !FSI->isExplicitSpecialization()) {
  772. const TemplateParameterList* Params
  773. = FSI->getTemplate()->getTemplateParameters();
  774. const TemplateArgumentList* Args = FSI->TemplateArguments;
  775. assert(Params->size() == Args->size());
  776. for (unsigned i = 0, e = Params->size(); i != e; ++i) {
  777. StringRef Param = Params->getParam(i)->getName();
  778. if (Param.empty()) continue;
  779. TOut << Param << " = ";
  780. Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
  781. TOut << ", ";
  782. }
  783. }
  784. TOut.flush();
  785. if (!TemplateParams.empty()) {
  786. // remove the trailing comma and space
  787. TemplateParams.resize(TemplateParams.size() - 2);
  788. POut << " [" << TemplateParams << "]";
  789. }
  790. POut.flush();
  791. // Print "auto" for all deduced return types. This includes C++1y return
  792. // type deduction and lambdas. For trailing return types resolve the
  793. // decltype expression. Otherwise print the real type when this is
  794. // not a constructor or destructor.
  795. if (isa<CXXMethodDecl>(FD) &&
  796. cast<CXXMethodDecl>(FD)->getParent()->isLambda())
  797. Proto = "auto " + Proto;
  798. else if (FT && FT->getReturnType()->getAs<DecltypeType>())
  799. FT->getReturnType()
  800. ->getAs<DecltypeType>()
  801. ->getUnderlyingType()
  802. .getAsStringInternal(Proto, Policy);
  803. else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
  804. AFT->getReturnType().getAsStringInternal(Proto, Policy);
  805. Out << Proto;
  806. return std::string(Name);
  807. }
  808. if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
  809. for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
  810. // Skip to its enclosing function or method, but not its enclosing
  811. // CapturedDecl.
  812. if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
  813. const Decl *D = Decl::castFromDeclContext(DC);
  814. return ComputeName(IK, D);
  815. }
  816. llvm_unreachable("CapturedDecl not inside a function or method");
  817. }
  818. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
  819. SmallString<256> Name;
  820. llvm::raw_svector_ostream Out(Name);
  821. Out << (MD->isInstanceMethod() ? '-' : '+');
  822. Out << '[';
  823. // For incorrect code, there might not be an ObjCInterfaceDecl. Do
  824. // a null check to avoid a crash.
  825. if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
  826. Out << *ID;
  827. if (const ObjCCategoryImplDecl *CID =
  828. dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
  829. Out << '(' << *CID << ')';
  830. Out << ' ';
  831. MD->getSelector().print(Out);
  832. Out << ']';
  833. return std::string(Name);
  834. }
  835. if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
  836. // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
  837. return "top level";
  838. }
  839. return "";
  840. }
  841. void APNumericStorage::setIntValue(const ASTContext &C,
  842. const llvm::APInt &Val) {
  843. if (hasAllocation())
  844. C.Deallocate(pVal);
  845. BitWidth = Val.getBitWidth();
  846. unsigned NumWords = Val.getNumWords();
  847. const uint64_t* Words = Val.getRawData();
  848. if (NumWords > 1) {
  849. pVal = new (C) uint64_t[NumWords];
  850. std::copy(Words, Words + NumWords, pVal);
  851. } else if (NumWords == 1)
  852. VAL = Words[0];
  853. else
  854. VAL = 0;
  855. }
  856. IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
  857. QualType type, SourceLocation l)
  858. : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
  859. assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
  860. assert(V.getBitWidth() == C.getIntWidth(type) &&
  861. "Integer type is not the correct size for constant.");
  862. setValue(C, V);
  863. setDependence(ExprDependence::None);
  864. }
  865. IntegerLiteral *
  866. IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
  867. QualType type, SourceLocation l) {
  868. return new (C) IntegerLiteral(C, V, type, l);
  869. }
  870. IntegerLiteral *
  871. IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
  872. return new (C) IntegerLiteral(Empty);
  873. }
  874. FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
  875. QualType type, SourceLocation l,
  876. unsigned Scale)
  877. : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
  878. Scale(Scale) {
  879. assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
  880. assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
  881. "Fixed point type is not the correct size for constant.");
  882. setValue(C, V);
  883. setDependence(ExprDependence::None);
  884. }
  885. FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
  886. const llvm::APInt &V,
  887. QualType type,
  888. SourceLocation l,
  889. unsigned Scale) {
  890. return new (C) FixedPointLiteral(C, V, type, l, Scale);
  891. }
  892. FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
  893. EmptyShell Empty) {
  894. return new (C) FixedPointLiteral(Empty);
  895. }
  896. std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
  897. // Currently the longest decimal number that can be printed is the max for an
  898. // unsigned long _Accum: 4294967295.99999999976716935634613037109375
  899. // which is 43 characters.
  900. SmallString<64> S;
  901. FixedPointValueToString(
  902. S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
  903. return std::string(S.str());
  904. }
  905. void CharacterLiteral::print(unsigned Val, CharacterKind Kind,
  906. raw_ostream &OS) {
  907. switch (Kind) {
  908. case CharacterLiteral::Ascii:
  909. break; // no prefix.
  910. case CharacterLiteral::Wide:
  911. OS << 'L';
  912. break;
  913. case CharacterLiteral::UTF8:
  914. OS << "u8";
  915. break;
  916. case CharacterLiteral::UTF16:
  917. OS << 'u';
  918. break;
  919. case CharacterLiteral::UTF32:
  920. OS << 'U';
  921. break;
  922. }
  923. StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
  924. if (!Escaped.empty()) {
  925. OS << "'" << Escaped << "'";
  926. } else {
  927. // A character literal might be sign-extended, which
  928. // would result in an invalid \U escape sequence.
  929. // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
  930. // are not correctly handled.
  931. if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteral::Ascii)
  932. Val &= 0xFFu;
  933. if (Val < 256 && isPrintable((unsigned char)Val))
  934. OS << "'" << (char)Val << "'";
  935. else if (Val < 256)
  936. OS << "'\\x" << llvm::format("%02x", Val) << "'";
  937. else if (Val <= 0xFFFF)
  938. OS << "'\\u" << llvm::format("%04x", Val) << "'";
  939. else
  940. OS << "'\\U" << llvm::format("%08x", Val) << "'";
  941. }
  942. }
  943. FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
  944. bool isexact, QualType Type, SourceLocation L)
  945. : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
  946. setSemantics(V.getSemantics());
  947. FloatingLiteralBits.IsExact = isexact;
  948. setValue(C, V);
  949. setDependence(ExprDependence::None);
  950. }
  951. FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
  952. : Expr(FloatingLiteralClass, Empty) {
  953. setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
  954. FloatingLiteralBits.IsExact = false;
  955. }
  956. FloatingLiteral *
  957. FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
  958. bool isexact, QualType Type, SourceLocation L) {
  959. return new (C) FloatingLiteral(C, V, isexact, Type, L);
  960. }
  961. FloatingLiteral *
  962. FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
  963. return new (C) FloatingLiteral(C, Empty);
  964. }
  965. /// getValueAsApproximateDouble - This returns the value as an inaccurate
  966. /// double. Note that this may cause loss of precision, but is useful for
  967. /// debugging dumps, etc.
  968. double FloatingLiteral::getValueAsApproximateDouble() const {
  969. llvm::APFloat V = getValue();
  970. bool ignored;
  971. V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
  972. &ignored);
  973. return V.convertToDouble();
  974. }
  975. unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
  976. StringKind SK) {
  977. unsigned CharByteWidth = 0;
  978. switch (SK) {
  979. case Ordinary:
  980. case UTF8:
  981. CharByteWidth = Target.getCharWidth();
  982. break;
  983. case Wide:
  984. CharByteWidth = Target.getWCharWidth();
  985. break;
  986. case UTF16:
  987. CharByteWidth = Target.getChar16Width();
  988. break;
  989. case UTF32:
  990. CharByteWidth = Target.getChar32Width();
  991. break;
  992. }
  993. assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
  994. CharByteWidth /= 8;
  995. assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
  996. "The only supported character byte widths are 1,2 and 4!");
  997. return CharByteWidth;
  998. }
  999. StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
  1000. StringKind Kind, bool Pascal, QualType Ty,
  1001. const SourceLocation *Loc,
  1002. unsigned NumConcatenated)
  1003. : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
  1004. assert(Ctx.getAsConstantArrayType(Ty) &&
  1005. "StringLiteral must be of constant array type!");
  1006. unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
  1007. unsigned ByteLength = Str.size();
  1008. assert((ByteLength % CharByteWidth == 0) &&
  1009. "The size of the data must be a multiple of CharByteWidth!");
  1010. // Avoid the expensive division. The compiler should be able to figure it
  1011. // out by itself. However as of clang 7, even with the appropriate
  1012. // llvm_unreachable added just here, it is not able to do so.
  1013. unsigned Length;
  1014. switch (CharByteWidth) {
  1015. case 1:
  1016. Length = ByteLength;
  1017. break;
  1018. case 2:
  1019. Length = ByteLength / 2;
  1020. break;
  1021. case 4:
  1022. Length = ByteLength / 4;
  1023. break;
  1024. default:
  1025. llvm_unreachable("Unsupported character width!");
  1026. }
  1027. StringLiteralBits.Kind = Kind;
  1028. StringLiteralBits.CharByteWidth = CharByteWidth;
  1029. StringLiteralBits.IsPascal = Pascal;
  1030. StringLiteralBits.NumConcatenated = NumConcatenated;
  1031. *getTrailingObjects<unsigned>() = Length;
  1032. // Initialize the trailing array of SourceLocation.
  1033. // This is safe since SourceLocation is POD-like.
  1034. std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
  1035. NumConcatenated * sizeof(SourceLocation));
  1036. // Initialize the trailing array of char holding the string data.
  1037. std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
  1038. setDependence(ExprDependence::None);
  1039. }
  1040. StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
  1041. unsigned Length, unsigned CharByteWidth)
  1042. : Expr(StringLiteralClass, Empty) {
  1043. StringLiteralBits.CharByteWidth = CharByteWidth;
  1044. StringLiteralBits.NumConcatenated = NumConcatenated;
  1045. *getTrailingObjects<unsigned>() = Length;
  1046. }
  1047. StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
  1048. StringKind Kind, bool Pascal, QualType Ty,
  1049. const SourceLocation *Loc,
  1050. unsigned NumConcatenated) {
  1051. void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
  1052. 1, NumConcatenated, Str.size()),
  1053. alignof(StringLiteral));
  1054. return new (Mem)
  1055. StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
  1056. }
  1057. StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
  1058. unsigned NumConcatenated,
  1059. unsigned Length,
  1060. unsigned CharByteWidth) {
  1061. void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
  1062. 1, NumConcatenated, Length * CharByteWidth),
  1063. alignof(StringLiteral));
  1064. return new (Mem)
  1065. StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
  1066. }
  1067. void StringLiteral::outputString(raw_ostream &OS) const {
  1068. switch (getKind()) {
  1069. case Ordinary:
  1070. break; // no prefix.
  1071. case Wide: OS << 'L'; break;
  1072. case UTF8: OS << "u8"; break;
  1073. case UTF16: OS << 'u'; break;
  1074. case UTF32: OS << 'U'; break;
  1075. }
  1076. OS << '"';
  1077. static const char Hex[] = "0123456789ABCDEF";
  1078. unsigned LastSlashX = getLength();
  1079. for (unsigned I = 0, N = getLength(); I != N; ++I) {
  1080. uint32_t Char = getCodeUnit(I);
  1081. StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
  1082. if (Escaped.empty()) {
  1083. // FIXME: Convert UTF-8 back to codepoints before rendering.
  1084. // Convert UTF-16 surrogate pairs back to codepoints before rendering.
  1085. // Leave invalid surrogates alone; we'll use \x for those.
  1086. if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
  1087. Char <= 0xdbff) {
  1088. uint32_t Trail = getCodeUnit(I + 1);
  1089. if (Trail >= 0xdc00 && Trail <= 0xdfff) {
  1090. Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
  1091. ++I;
  1092. }
  1093. }
  1094. if (Char > 0xff) {
  1095. // If this is a wide string, output characters over 0xff using \x
  1096. // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
  1097. // codepoint: use \x escapes for invalid codepoints.
  1098. if (getKind() == Wide ||
  1099. (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
  1100. // FIXME: Is this the best way to print wchar_t?
  1101. OS << "\\x";
  1102. int Shift = 28;
  1103. while ((Char >> Shift) == 0)
  1104. Shift -= 4;
  1105. for (/**/; Shift >= 0; Shift -= 4)
  1106. OS << Hex[(Char >> Shift) & 15];
  1107. LastSlashX = I;
  1108. continue;
  1109. }
  1110. if (Char > 0xffff)
  1111. OS << "\\U00"
  1112. << Hex[(Char >> 20) & 15]
  1113. << Hex[(Char >> 16) & 15];
  1114. else
  1115. OS << "\\u";
  1116. OS << Hex[(Char >> 12) & 15]
  1117. << Hex[(Char >> 8) & 15]
  1118. << Hex[(Char >> 4) & 15]
  1119. << Hex[(Char >> 0) & 15];
  1120. continue;
  1121. }
  1122. // If we used \x... for the previous character, and this character is a
  1123. // hexadecimal digit, prevent it being slurped as part of the \x.
  1124. if (LastSlashX + 1 == I) {
  1125. switch (Char) {
  1126. case '0': case '1': case '2': case '3': case '4':
  1127. case '5': case '6': case '7': case '8': case '9':
  1128. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  1129. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  1130. OS << "\"\"";
  1131. }
  1132. }
  1133. assert(Char <= 0xff &&
  1134. "Characters above 0xff should already have been handled.");
  1135. if (isPrintable(Char))
  1136. OS << (char)Char;
  1137. else // Output anything hard as an octal escape.
  1138. OS << '\\'
  1139. << (char)('0' + ((Char >> 6) & 7))
  1140. << (char)('0' + ((Char >> 3) & 7))
  1141. << (char)('0' + ((Char >> 0) & 7));
  1142. } else {
  1143. // Handle some common non-printable cases to make dumps prettier.
  1144. OS << Escaped;
  1145. }
  1146. }
  1147. OS << '"';
  1148. }
  1149. /// getLocationOfByte - Return a source location that points to the specified
  1150. /// byte of this string literal.
  1151. ///
  1152. /// Strings are amazingly complex. They can be formed from multiple tokens and
  1153. /// can have escape sequences in them in addition to the usual trigraph and
  1154. /// escaped newline business. This routine handles this complexity.
  1155. ///
  1156. /// The *StartToken sets the first token to be searched in this function and
  1157. /// the *StartTokenByteOffset is the byte offset of the first token. Before
  1158. /// returning, it updates the *StartToken to the TokNo of the token being found
  1159. /// and sets *StartTokenByteOffset to the byte offset of the token in the
  1160. /// string.
  1161. /// Using these two parameters can reduce the time complexity from O(n^2) to
  1162. /// O(n) if one wants to get the location of byte for all the tokens in a
  1163. /// string.
  1164. ///
  1165. SourceLocation
  1166. StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
  1167. const LangOptions &Features,
  1168. const TargetInfo &Target, unsigned *StartToken,
  1169. unsigned *StartTokenByteOffset) const {
  1170. assert((getKind() == StringLiteral::Ordinary ||
  1171. getKind() == StringLiteral::UTF8) &&
  1172. "Only narrow string literals are currently supported");
  1173. // Loop over all of the tokens in this string until we find the one that
  1174. // contains the byte we're looking for.
  1175. unsigned TokNo = 0;
  1176. unsigned StringOffset = 0;
  1177. if (StartToken)
  1178. TokNo = *StartToken;
  1179. if (StartTokenByteOffset) {
  1180. StringOffset = *StartTokenByteOffset;
  1181. ByteNo -= StringOffset;
  1182. }
  1183. while (true) {
  1184. assert(TokNo < getNumConcatenated() && "Invalid byte number!");
  1185. SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
  1186. // Get the spelling of the string so that we can get the data that makes up
  1187. // the string literal, not the identifier for the macro it is potentially
  1188. // expanded through.
  1189. SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
  1190. // Re-lex the token to get its length and original spelling.
  1191. std::pair<FileID, unsigned> LocInfo =
  1192. SM.getDecomposedLoc(StrTokSpellingLoc);
  1193. bool Invalid = false;
  1194. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  1195. if (Invalid) {
  1196. if (StartTokenByteOffset != nullptr)
  1197. *StartTokenByteOffset = StringOffset;
  1198. if (StartToken != nullptr)
  1199. *StartToken = TokNo;
  1200. return StrTokSpellingLoc;
  1201. }
  1202. const char *StrData = Buffer.data()+LocInfo.second;
  1203. // Create a lexer starting at the beginning of this token.
  1204. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
  1205. Buffer.begin(), StrData, Buffer.end());
  1206. Token TheTok;
  1207. TheLexer.LexFromRawLexer(TheTok);
  1208. // Use the StringLiteralParser to compute the length of the string in bytes.
  1209. StringLiteralParser SLP(TheTok, SM, Features, Target);
  1210. unsigned TokNumBytes = SLP.GetStringLength();
  1211. // If the byte is in this token, return the location of the byte.
  1212. if (ByteNo < TokNumBytes ||
  1213. (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
  1214. unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
  1215. // Now that we know the offset of the token in the spelling, use the
  1216. // preprocessor to get the offset in the original source.
  1217. if (StartTokenByteOffset != nullptr)
  1218. *StartTokenByteOffset = StringOffset;
  1219. if (StartToken != nullptr)
  1220. *StartToken = TokNo;
  1221. return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
  1222. }
  1223. // Move to the next string token.
  1224. StringOffset += TokNumBytes;
  1225. ++TokNo;
  1226. ByteNo -= TokNumBytes;
  1227. }
  1228. }
  1229. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  1230. /// corresponds to, e.g. "sizeof" or "[pre]++".
  1231. StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
  1232. switch (Op) {
  1233. #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
  1234. #include "clang/AST/OperationKinds.def"
  1235. }
  1236. llvm_unreachable("Unknown unary operator");
  1237. }
  1238. UnaryOperatorKind
  1239. UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
  1240. switch (OO) {
  1241. default: llvm_unreachable("No unary operator for overloaded function");
  1242. case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
  1243. case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
  1244. case OO_Amp: return UO_AddrOf;
  1245. case OO_Star: return UO_Deref;
  1246. case OO_Plus: return UO_Plus;
  1247. case OO_Minus: return UO_Minus;
  1248. case OO_Tilde: return UO_Not;
  1249. case OO_Exclaim: return UO_LNot;
  1250. case OO_Coawait: return UO_Coawait;
  1251. }
  1252. }
  1253. OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
  1254. switch (Opc) {
  1255. case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
  1256. case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
  1257. case UO_AddrOf: return OO_Amp;
  1258. case UO_Deref: return OO_Star;
  1259. case UO_Plus: return OO_Plus;
  1260. case UO_Minus: return OO_Minus;
  1261. case UO_Not: return OO_Tilde;
  1262. case UO_LNot: return OO_Exclaim;
  1263. case UO_Coawait: return OO_Coawait;
  1264. default: return OO_None;
  1265. }
  1266. }
  1267. //===----------------------------------------------------------------------===//
  1268. // Postfix Operators.
  1269. //===----------------------------------------------------------------------===//
  1270. CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
  1271. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  1272. SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
  1273. unsigned MinNumArgs, ADLCallKind UsesADL)
  1274. : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
  1275. NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
  1276. unsigned NumPreArgs = PreArgs.size();
  1277. CallExprBits.NumPreArgs = NumPreArgs;
  1278. assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
  1279. unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
  1280. CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
  1281. assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
  1282. "OffsetToTrailingObjects overflow!");
  1283. CallExprBits.UsesADL = static_cast<bool>(UsesADL);
  1284. setCallee(Fn);
  1285. for (unsigned I = 0; I != NumPreArgs; ++I)
  1286. setPreArg(I, PreArgs[I]);
  1287. for (unsigned I = 0; I != Args.size(); ++I)
  1288. setArg(I, Args[I]);
  1289. for (unsigned I = Args.size(); I != NumArgs; ++I)
  1290. setArg(I, nullptr);
  1291. this->computeDependence();
  1292. CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
  1293. if (hasStoredFPFeatures())
  1294. setStoredFPFeatures(FPFeatures);
  1295. }
  1296. CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
  1297. bool HasFPFeatures, EmptyShell Empty)
  1298. : Expr(SC, Empty), NumArgs(NumArgs) {
  1299. CallExprBits.NumPreArgs = NumPreArgs;
  1300. assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
  1301. unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
  1302. CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
  1303. assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
  1304. "OffsetToTrailingObjects overflow!");
  1305. CallExprBits.HasFPFeatures = HasFPFeatures;
  1306. }
  1307. CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
  1308. ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
  1309. SourceLocation RParenLoc,
  1310. FPOptionsOverride FPFeatures, unsigned MinNumArgs,
  1311. ADLCallKind UsesADL) {
  1312. unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
  1313. unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
  1314. /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
  1315. void *Mem =
  1316. Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
  1317. return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
  1318. RParenLoc, FPFeatures, MinNumArgs, UsesADL);
  1319. }
  1320. CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
  1321. ExprValueKind VK, SourceLocation RParenLoc,
  1322. ADLCallKind UsesADL) {
  1323. assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
  1324. "Misaligned memory in CallExpr::CreateTemporary!");
  1325. return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
  1326. VK, RParenLoc, FPOptionsOverride(),
  1327. /*MinNumArgs=*/0, UsesADL);
  1328. }
  1329. CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
  1330. bool HasFPFeatures, EmptyShell Empty) {
  1331. unsigned SizeOfTrailingObjects =
  1332. CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
  1333. void *Mem =
  1334. Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
  1335. return new (Mem)
  1336. CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
  1337. }
  1338. unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
  1339. switch (SC) {
  1340. case CallExprClass:
  1341. return sizeof(CallExpr);
  1342. case CXXOperatorCallExprClass:
  1343. return sizeof(CXXOperatorCallExpr);
  1344. case CXXMemberCallExprClass:
  1345. return sizeof(CXXMemberCallExpr);
  1346. case UserDefinedLiteralClass:
  1347. return sizeof(UserDefinedLiteral);
  1348. case CUDAKernelCallExprClass:
  1349. return sizeof(CUDAKernelCallExpr);
  1350. default:
  1351. llvm_unreachable("unexpected class deriving from CallExpr!");
  1352. }
  1353. }
  1354. Decl *Expr::getReferencedDeclOfCallee() {
  1355. Expr *CEE = IgnoreParenImpCasts();
  1356. while (SubstNonTypeTemplateParmExpr *NTTP =
  1357. dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
  1358. CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
  1359. }
  1360. // If we're calling a dereference, look at the pointer instead.
  1361. while (true) {
  1362. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
  1363. if (BO->isPtrMemOp()) {
  1364. CEE = BO->getRHS()->IgnoreParenImpCasts();
  1365. continue;
  1366. }
  1367. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
  1368. if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
  1369. UO->getOpcode() == UO_Plus) {
  1370. CEE = UO->getSubExpr()->IgnoreParenImpCasts();
  1371. continue;
  1372. }
  1373. }
  1374. break;
  1375. }
  1376. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
  1377. return DRE->getDecl();
  1378. if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
  1379. return ME->getMemberDecl();
  1380. if (auto *BE = dyn_cast<BlockExpr>(CEE))
  1381. return BE->getBlockDecl();
  1382. return nullptr;
  1383. }
  1384. /// If this is a call to a builtin, return the builtin ID. If not, return 0.
  1385. unsigned CallExpr::getBuiltinCallee() const {
  1386. auto *FDecl = getDirectCallee();
  1387. return FDecl ? FDecl->getBuiltinID() : 0;
  1388. }
  1389. bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
  1390. if (unsigned BI = getBuiltinCallee())
  1391. return Ctx.BuiltinInfo.isUnevaluated(BI);
  1392. return false;
  1393. }
  1394. QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
  1395. const Expr *Callee = getCallee();
  1396. QualType CalleeType = Callee->getType();
  1397. if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
  1398. CalleeType = FnTypePtr->getPointeeType();
  1399. } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
  1400. CalleeType = BPT->getPointeeType();
  1401. } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
  1402. if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
  1403. return Ctx.VoidTy;
  1404. if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
  1405. return Ctx.DependentTy;
  1406. // This should never be overloaded and so should never return null.
  1407. CalleeType = Expr::findBoundMemberType(Callee);
  1408. assert(!CalleeType.isNull());
  1409. } else if (CalleeType->isDependentType() ||
  1410. CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
  1411. return Ctx.DependentTy;
  1412. }
  1413. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  1414. return FnType->getReturnType();
  1415. }
  1416. const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
  1417. // If the return type is a struct, union, or enum that is marked nodiscard,
  1418. // then return the return type attribute.
  1419. if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
  1420. if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
  1421. return A;
  1422. for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
  1423. TD = TD->desugar()->getAs<TypedefType>())
  1424. if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
  1425. return A;
  1426. // Otherwise, see if the callee is marked nodiscard and return that attribute
  1427. // instead.
  1428. const Decl *D = getCalleeDecl();
  1429. return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
  1430. }
  1431. SourceLocation CallExpr::getBeginLoc() const {
  1432. if (isa<CXXOperatorCallExpr>(this))
  1433. return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
  1434. SourceLocation begin = getCallee()->getBeginLoc();
  1435. if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
  1436. begin = getArg(0)->getBeginLoc();
  1437. return begin;
  1438. }
  1439. SourceLocation CallExpr::getEndLoc() const {
  1440. if (isa<CXXOperatorCallExpr>(this))
  1441. return cast<CXXOperatorCallExpr>(this)->getEndLoc();
  1442. SourceLocation end = getRParenLoc();
  1443. if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
  1444. end = getArg(getNumArgs() - 1)->getEndLoc();
  1445. return end;
  1446. }
  1447. OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
  1448. SourceLocation OperatorLoc,
  1449. TypeSourceInfo *tsi,
  1450. ArrayRef<OffsetOfNode> comps,
  1451. ArrayRef<Expr*> exprs,
  1452. SourceLocation RParenLoc) {
  1453. void *Mem = C.Allocate(
  1454. totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
  1455. return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
  1456. RParenLoc);
  1457. }
  1458. OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
  1459. unsigned numComps, unsigned numExprs) {
  1460. void *Mem =
  1461. C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
  1462. return new (Mem) OffsetOfExpr(numComps, numExprs);
  1463. }
  1464. OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
  1465. SourceLocation OperatorLoc, TypeSourceInfo *tsi,
  1466. ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
  1467. SourceLocation RParenLoc)
  1468. : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
  1469. OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
  1470. NumComps(comps.size()), NumExprs(exprs.size()) {
  1471. for (unsigned i = 0; i != comps.size(); ++i)
  1472. setComponent(i, comps[i]);
  1473. for (unsigned i = 0; i != exprs.size(); ++i)
  1474. setIndexExpr(i, exprs[i]);
  1475. setDependence(computeDependence(this));
  1476. }
  1477. IdentifierInfo *OffsetOfNode::getFieldName() const {
  1478. assert(getKind() == Field || getKind() == Identifier);
  1479. if (getKind() == Field)
  1480. return getField()->getIdentifier();
  1481. return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
  1482. }
  1483. UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
  1484. UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
  1485. SourceLocation op, SourceLocation rp)
  1486. : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
  1487. OpLoc(op), RParenLoc(rp) {
  1488. assert(ExprKind <= UETT_Last && "invalid enum value!");
  1489. UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
  1490. assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
  1491. "UnaryExprOrTypeTraitExprBits.Kind overflow!");
  1492. UnaryExprOrTypeTraitExprBits.IsType = false;
  1493. Argument.Ex = E;
  1494. setDependence(computeDependence(this));
  1495. }
  1496. MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
  1497. ValueDecl *MemberDecl,
  1498. const DeclarationNameInfo &NameInfo, QualType T,
  1499. ExprValueKind VK, ExprObjectKind OK,
  1500. NonOdrUseReason NOUR)
  1501. : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
  1502. MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
  1503. assert(!NameInfo.getName() ||
  1504. MemberDecl->getDeclName() == NameInfo.getName());
  1505. MemberExprBits.IsArrow = IsArrow;
  1506. MemberExprBits.HasQualifierOrFoundDecl = false;
  1507. MemberExprBits.HasTemplateKWAndArgsInfo = false;
  1508. MemberExprBits.HadMultipleCandidates = false;
  1509. MemberExprBits.NonOdrUseReason = NOUR;
  1510. MemberExprBits.OperatorLoc = OperatorLoc;
  1511. setDependence(computeDependence(this));
  1512. }
  1513. MemberExpr *MemberExpr::Create(
  1514. const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
  1515. NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
  1516. ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
  1517. DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
  1518. QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
  1519. bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
  1520. FoundDecl.getAccess() != MemberDecl->getAccess();
  1521. bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
  1522. std::size_t Size =
  1523. totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
  1524. TemplateArgumentLoc>(
  1525. HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
  1526. TemplateArgs ? TemplateArgs->size() : 0);
  1527. void *Mem = C.Allocate(Size, alignof(MemberExpr));
  1528. MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
  1529. NameInfo, T, VK, OK, NOUR);
  1530. // FIXME: remove remaining dependence computation to computeDependence().
  1531. auto Deps = E->getDependence();
  1532. if (HasQualOrFound) {
  1533. // FIXME: Wrong. We should be looking at the member declaration we found.
  1534. if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
  1535. Deps |= ExprDependence::TypeValueInstantiation;
  1536. else if (QualifierLoc &&
  1537. QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
  1538. Deps |= ExprDependence::Instantiation;
  1539. E->MemberExprBits.HasQualifierOrFoundDecl = true;
  1540. MemberExprNameQualifier *NQ =
  1541. E->getTrailingObjects<MemberExprNameQualifier>();
  1542. NQ->QualifierLoc = QualifierLoc;
  1543. NQ->FoundDecl = FoundDecl;
  1544. }
  1545. E->MemberExprBits.HasTemplateKWAndArgsInfo =
  1546. TemplateArgs || TemplateKWLoc.isValid();
  1547. if (TemplateArgs) {
  1548. auto TemplateArgDeps = TemplateArgumentDependence::None;
  1549. E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
  1550. TemplateKWLoc, *TemplateArgs,
  1551. E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
  1552. if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
  1553. Deps |= ExprDependence::Instantiation;
  1554. } else if (TemplateKWLoc.isValid()) {
  1555. E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
  1556. TemplateKWLoc);
  1557. }
  1558. E->setDependence(Deps);
  1559. return E;
  1560. }
  1561. MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
  1562. bool HasQualifier, bool HasFoundDecl,
  1563. bool HasTemplateKWAndArgsInfo,
  1564. unsigned NumTemplateArgs) {
  1565. assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
  1566. "template args but no template arg info?");
  1567. bool HasQualOrFound = HasQualifier || HasFoundDecl;
  1568. std::size_t Size =
  1569. totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
  1570. TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
  1571. HasTemplateKWAndArgsInfo ? 1 : 0,
  1572. NumTemplateArgs);
  1573. void *Mem = Context.Allocate(Size, alignof(MemberExpr));
  1574. return new (Mem) MemberExpr(EmptyShell());
  1575. }
  1576. void MemberExpr::setMemberDecl(ValueDecl *NewD) {
  1577. MemberDecl = NewD;
  1578. if (getType()->isUndeducedType())
  1579. setType(NewD->getType());
  1580. setDependence(computeDependence(this));
  1581. }
  1582. SourceLocation MemberExpr::getBeginLoc() const {
  1583. if (isImplicitAccess()) {
  1584. if (hasQualifier())
  1585. return getQualifierLoc().getBeginLoc();
  1586. return MemberLoc;
  1587. }
  1588. // FIXME: We don't want this to happen. Rather, we should be able to
  1589. // detect all kinds of implicit accesses more cleanly.
  1590. SourceLocation BaseStartLoc = getBase()->getBeginLoc();
  1591. if (BaseStartLoc.isValid())
  1592. return BaseStartLoc;
  1593. return MemberLoc;
  1594. }
  1595. SourceLocation MemberExpr::getEndLoc() const {
  1596. SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
  1597. if (hasExplicitTemplateArgs())
  1598. EndLoc = getRAngleLoc();
  1599. else if (EndLoc.isInvalid())
  1600. EndLoc = getBase()->getEndLoc();
  1601. return EndLoc;
  1602. }
  1603. bool CastExpr::CastConsistency() const {
  1604. switch (getCastKind()) {
  1605. case CK_DerivedToBase:
  1606. case CK_UncheckedDerivedToBase:
  1607. case CK_DerivedToBaseMemberPointer:
  1608. case CK_BaseToDerived:
  1609. case CK_BaseToDerivedMemberPointer:
  1610. assert(!path_empty() && "Cast kind should have a base path!");
  1611. break;
  1612. case CK_CPointerToObjCPointerCast:
  1613. assert(getType()->isObjCObjectPointerType());
  1614. assert(getSubExpr()->getType()->isPointerType());
  1615. goto CheckNoBasePath;
  1616. case CK_BlockPointerToObjCPointerCast:
  1617. assert(getType()->isObjCObjectPointerType());
  1618. assert(getSubExpr()->getType()->isBlockPointerType());
  1619. goto CheckNoBasePath;
  1620. case CK_ReinterpretMemberPointer:
  1621. assert(getType()->isMemberPointerType());
  1622. assert(getSubExpr()->getType()->isMemberPointerType());
  1623. goto CheckNoBasePath;
  1624. case CK_BitCast:
  1625. // Arbitrary casts to C pointer types count as bitcasts.
  1626. // Otherwise, we should only have block and ObjC pointer casts
  1627. // here if they stay within the type kind.
  1628. if (!getType()->isPointerType()) {
  1629. assert(getType()->isObjCObjectPointerType() ==
  1630. getSubExpr()->getType()->isObjCObjectPointerType());
  1631. assert(getType()->isBlockPointerType() ==
  1632. getSubExpr()->getType()->isBlockPointerType());
  1633. }
  1634. goto CheckNoBasePath;
  1635. case CK_AnyPointerToBlockPointerCast:
  1636. assert(getType()->isBlockPointerType());
  1637. assert(getSubExpr()->getType()->isAnyPointerType() &&
  1638. !getSubExpr()->getType()->isBlockPointerType());
  1639. goto CheckNoBasePath;
  1640. case CK_CopyAndAutoreleaseBlockObject:
  1641. assert(getType()->isBlockPointerType());
  1642. assert(getSubExpr()->getType()->isBlockPointerType());
  1643. goto CheckNoBasePath;
  1644. case CK_FunctionToPointerDecay:
  1645. assert(getType()->isPointerType());
  1646. assert(getSubExpr()->getType()->isFunctionType());
  1647. goto CheckNoBasePath;
  1648. case CK_AddressSpaceConversion: {
  1649. auto Ty = getType();
  1650. auto SETy = getSubExpr()->getType();
  1651. assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
  1652. if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
  1653. Ty = Ty->getPointeeType();
  1654. SETy = SETy->getPointeeType();
  1655. }
  1656. assert((Ty->isDependentType() || SETy->isDependentType()) ||
  1657. (!Ty.isNull() && !SETy.isNull() &&
  1658. Ty.getAddressSpace() != SETy.getAddressSpace()));
  1659. goto CheckNoBasePath;
  1660. }
  1661. // These should not have an inheritance path.
  1662. case CK_Dynamic:
  1663. case CK_ToUnion:
  1664. case CK_ArrayToPointerDecay:
  1665. case CK_NullToMemberPointer:
  1666. case CK_NullToPointer:
  1667. case CK_ConstructorConversion:
  1668. case CK_IntegralToPointer:
  1669. case CK_PointerToIntegral:
  1670. case CK_ToVoid:
  1671. case CK_VectorSplat:
  1672. case CK_IntegralCast:
  1673. case CK_BooleanToSignedIntegral:
  1674. case CK_IntegralToFloating:
  1675. case CK_FloatingToIntegral:
  1676. case CK_FloatingCast:
  1677. case CK_ObjCObjectLValueCast:
  1678. case CK_FloatingRealToComplex:
  1679. case CK_FloatingComplexToReal:
  1680. case CK_FloatingComplexCast:
  1681. case CK_FloatingComplexToIntegralComplex:
  1682. case CK_IntegralRealToComplex:
  1683. case CK_IntegralComplexToReal:
  1684. case CK_IntegralComplexCast:
  1685. case CK_IntegralComplexToFloatingComplex:
  1686. case CK_ARCProduceObject:
  1687. case CK_ARCConsumeObject:
  1688. case CK_ARCReclaimReturnedObject:
  1689. case CK_ARCExtendBlockObject:
  1690. case CK_ZeroToOCLOpaqueType:
  1691. case CK_IntToOCLSampler:
  1692. case CK_FloatingToFixedPoint:
  1693. case CK_FixedPointToFloating:
  1694. case CK_FixedPointCast:
  1695. case CK_FixedPointToIntegral:
  1696. case CK_IntegralToFixedPoint:
  1697. case CK_MatrixCast:
  1698. assert(!getType()->isBooleanType() && "unheralded conversion to bool");
  1699. goto CheckNoBasePath;
  1700. case CK_Dependent:
  1701. case CK_LValueToRValue:
  1702. case CK_NoOp:
  1703. case CK_AtomicToNonAtomic:
  1704. case CK_NonAtomicToAtomic:
  1705. case CK_PointerToBoolean:
  1706. case CK_IntegralToBoolean:
  1707. case CK_FloatingToBoolean:
  1708. case CK_MemberPointerToBoolean:
  1709. case CK_FloatingComplexToBoolean:
  1710. case CK_IntegralComplexToBoolean:
  1711. case CK_LValueBitCast: // -> bool&
  1712. case CK_LValueToRValueBitCast:
  1713. case CK_UserDefinedConversion: // operator bool()
  1714. case CK_BuiltinFnToFnPtr:
  1715. case CK_FixedPointToBoolean:
  1716. CheckNoBasePath:
  1717. assert(path_empty() && "Cast kind should not have a base path!");
  1718. break;
  1719. }
  1720. return true;
  1721. }
  1722. const char *CastExpr::getCastKindName(CastKind CK) {
  1723. switch (CK) {
  1724. #define CAST_OPERATION(Name) case CK_##Name: return #Name;
  1725. #include "clang/AST/OperationKinds.def"
  1726. }
  1727. llvm_unreachable("Unhandled cast kind!");
  1728. }
  1729. namespace {
  1730. // Skip over implicit nodes produced as part of semantic analysis.
  1731. // Designed for use with IgnoreExprNodes.
  1732. Expr *ignoreImplicitSemaNodes(Expr *E) {
  1733. if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
  1734. return Materialize->getSubExpr();
  1735. if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  1736. return Binder->getSubExpr();
  1737. if (auto *Full = dyn_cast<FullExpr>(E))
  1738. return Full->getSubExpr();
  1739. return E;
  1740. }
  1741. } // namespace
  1742. Expr *CastExpr::getSubExprAsWritten() {
  1743. const Expr *SubExpr = nullptr;
  1744. for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
  1745. SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
  1746. // Conversions by constructor and conversion functions have a
  1747. // subexpression describing the call; strip it off.
  1748. if (E->getCastKind() == CK_ConstructorConversion) {
  1749. SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
  1750. ignoreImplicitSemaNodes);
  1751. } else if (E->getCastKind() == CK_UserDefinedConversion) {
  1752. assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
  1753. "Unexpected SubExpr for CK_UserDefinedConversion.");
  1754. if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
  1755. SubExpr = MCE->getImplicitObjectArgument();
  1756. }
  1757. }
  1758. return const_cast<Expr *>(SubExpr);
  1759. }
  1760. NamedDecl *CastExpr::getConversionFunction() const {
  1761. const Expr *SubExpr = nullptr;
  1762. for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
  1763. SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
  1764. if (E->getCastKind() == CK_ConstructorConversion)
  1765. return cast<CXXConstructExpr>(SubExpr)->getConstructor();
  1766. if (E->getCastKind() == CK_UserDefinedConversion) {
  1767. if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
  1768. return MCE->getMethodDecl();
  1769. }
  1770. }
  1771. return nullptr;
  1772. }
  1773. CXXBaseSpecifier **CastExpr::path_buffer() {
  1774. switch (getStmtClass()) {
  1775. #define ABSTRACT_STMT(x)
  1776. #define CASTEXPR(Type, Base) \
  1777. case Stmt::Type##Class: \
  1778. return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
  1779. #define STMT(Type, Base)
  1780. #include "clang/AST/StmtNodes.inc"
  1781. default:
  1782. llvm_unreachable("non-cast expressions not possible here");
  1783. }
  1784. }
  1785. const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
  1786. QualType opType) {
  1787. auto RD = unionType->castAs<RecordType>()->getDecl();
  1788. return getTargetFieldForToUnionCast(RD, opType);
  1789. }
  1790. const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
  1791. QualType OpType) {
  1792. auto &Ctx = RD->getASTContext();
  1793. RecordDecl::field_iterator Field, FieldEnd;
  1794. for (Field = RD->field_begin(), FieldEnd = RD->field_end();
  1795. Field != FieldEnd; ++Field) {
  1796. if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
  1797. !Field->isUnnamedBitfield()) {
  1798. return *Field;
  1799. }
  1800. }
  1801. return nullptr;
  1802. }
  1803. FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
  1804. assert(hasStoredFPFeatures());
  1805. switch (getStmtClass()) {
  1806. case ImplicitCastExprClass:
  1807. return static_cast<ImplicitCastExpr *>(this)
  1808. ->getTrailingObjects<FPOptionsOverride>();
  1809. case CStyleCastExprClass:
  1810. return static_cast<CStyleCastExpr *>(this)
  1811. ->getTrailingObjects<FPOptionsOverride>();
  1812. case CXXFunctionalCastExprClass:
  1813. return static_cast<CXXFunctionalCastExpr *>(this)
  1814. ->getTrailingObjects<FPOptionsOverride>();
  1815. case CXXStaticCastExprClass:
  1816. return static_cast<CXXStaticCastExpr *>(this)
  1817. ->getTrailingObjects<FPOptionsOverride>();
  1818. default:
  1819. llvm_unreachable("Cast does not have FPFeatures");
  1820. }
  1821. }
  1822. ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
  1823. CastKind Kind, Expr *Operand,
  1824. const CXXCastPath *BasePath,
  1825. ExprValueKind VK,
  1826. FPOptionsOverride FPO) {
  1827. unsigned PathSize = (BasePath ? BasePath->size() : 0);
  1828. void *Buffer =
  1829. C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
  1830. PathSize, FPO.requiresTrailingStorage()));
  1831. // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
  1832. // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
  1833. assert((Kind != CK_LValueToRValue ||
  1834. !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
  1835. "invalid type for lvalue-to-rvalue conversion");
  1836. ImplicitCastExpr *E =
  1837. new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
  1838. if (PathSize)
  1839. std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
  1840. E->getTrailingObjects<CXXBaseSpecifier *>());
  1841. return E;
  1842. }
  1843. ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
  1844. unsigned PathSize,
  1845. bool HasFPFeatures) {
  1846. void *Buffer =
  1847. C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
  1848. PathSize, HasFPFeatures));
  1849. return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
  1850. }
  1851. CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
  1852. ExprValueKind VK, CastKind K, Expr *Op,
  1853. const CXXCastPath *BasePath,
  1854. FPOptionsOverride FPO,
  1855. TypeSourceInfo *WrittenTy,
  1856. SourceLocation L, SourceLocation R) {
  1857. unsigned PathSize = (BasePath ? BasePath->size() : 0);
  1858. void *Buffer =
  1859. C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
  1860. PathSize, FPO.requiresTrailingStorage()));
  1861. CStyleCastExpr *E =
  1862. new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
  1863. if (PathSize)
  1864. std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
  1865. E->getTrailingObjects<CXXBaseSpecifier *>());
  1866. return E;
  1867. }
  1868. CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
  1869. unsigned PathSize,
  1870. bool HasFPFeatures) {
  1871. void *Buffer =
  1872. C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
  1873. PathSize, HasFPFeatures));
  1874. return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
  1875. }
  1876. /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
  1877. /// corresponds to, e.g. "<<=".
  1878. StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
  1879. switch (Op) {
  1880. #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
  1881. #include "clang/AST/OperationKinds.def"
  1882. }
  1883. llvm_unreachable("Invalid OpCode!");
  1884. }
  1885. BinaryOperatorKind
  1886. BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
  1887. switch (OO) {
  1888. default: llvm_unreachable("Not an overloadable binary operator");
  1889. case OO_Plus: return BO_Add;
  1890. case OO_Minus: return BO_Sub;
  1891. case OO_Star: return BO_Mul;
  1892. case OO_Slash: return BO_Div;
  1893. case OO_Percent: return BO_Rem;
  1894. case OO_Caret: return BO_Xor;
  1895. case OO_Amp: return BO_And;
  1896. case OO_Pipe: return BO_Or;
  1897. case OO_Equal: return BO_Assign;
  1898. case OO_Spaceship: return BO_Cmp;
  1899. case OO_Less: return BO_LT;
  1900. case OO_Greater: return BO_GT;
  1901. case OO_PlusEqual: return BO_AddAssign;
  1902. case OO_MinusEqual: return BO_SubAssign;
  1903. case OO_StarEqual: return BO_MulAssign;
  1904. case OO_SlashEqual: return BO_DivAssign;
  1905. case OO_PercentEqual: return BO_RemAssign;
  1906. case OO_CaretEqual: return BO_XorAssign;
  1907. case OO_AmpEqual: return BO_AndAssign;
  1908. case OO_PipeEqual: return BO_OrAssign;
  1909. case OO_LessLess: return BO_Shl;
  1910. case OO_GreaterGreater: return BO_Shr;
  1911. case OO_LessLessEqual: return BO_ShlAssign;
  1912. case OO_GreaterGreaterEqual: return BO_ShrAssign;
  1913. case OO_EqualEqual: return BO_EQ;
  1914. case OO_ExclaimEqual: return BO_NE;
  1915. case OO_LessEqual: return BO_LE;
  1916. case OO_GreaterEqual: return BO_GE;
  1917. case OO_AmpAmp: return BO_LAnd;
  1918. case OO_PipePipe: return BO_LOr;
  1919. case OO_Comma: return BO_Comma;
  1920. case OO_ArrowStar: return BO_PtrMemI;
  1921. }
  1922. }
  1923. OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
  1924. static const OverloadedOperatorKind OverOps[] = {
  1925. /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
  1926. OO_Star, OO_Slash, OO_Percent,
  1927. OO_Plus, OO_Minus,
  1928. OO_LessLess, OO_GreaterGreater,
  1929. OO_Spaceship,
  1930. OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
  1931. OO_EqualEqual, OO_ExclaimEqual,
  1932. OO_Amp,
  1933. OO_Caret,
  1934. OO_Pipe,
  1935. OO_AmpAmp,
  1936. OO_PipePipe,
  1937. OO_Equal, OO_StarEqual,
  1938. OO_SlashEqual, OO_PercentEqual,
  1939. OO_PlusEqual, OO_MinusEqual,
  1940. OO_LessLessEqual, OO_GreaterGreaterEqual,
  1941. OO_AmpEqual, OO_CaretEqual,
  1942. OO_PipeEqual,
  1943. OO_Comma
  1944. };
  1945. return OverOps[Opc];
  1946. }
  1947. bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
  1948. Opcode Opc,
  1949. Expr *LHS, Expr *RHS) {
  1950. if (Opc != BO_Add)
  1951. return false;
  1952. // Check that we have one pointer and one integer operand.
  1953. Expr *PExp;
  1954. if (LHS->getType()->isPointerType()) {
  1955. if (!RHS->getType()->isIntegerType())
  1956. return false;
  1957. PExp = LHS;
  1958. } else if (RHS->getType()->isPointerType()) {
  1959. if (!LHS->getType()->isIntegerType())
  1960. return false;
  1961. PExp = RHS;
  1962. } else {
  1963. return false;
  1964. }
  1965. // Check that the pointer is a nullptr.
  1966. if (!PExp->IgnoreParenCasts()
  1967. ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
  1968. return false;
  1969. // Check that the pointee type is char-sized.
  1970. const PointerType *PTy = PExp->getType()->getAs<PointerType>();
  1971. if (!PTy || !PTy->getPointeeType()->isCharType())
  1972. return false;
  1973. return true;
  1974. }
  1975. SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
  1976. QualType ResultTy, SourceLocation BLoc,
  1977. SourceLocation RParenLoc,
  1978. DeclContext *ParentContext)
  1979. : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
  1980. BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
  1981. SourceLocExprBits.Kind = Kind;
  1982. setDependence(ExprDependence::None);
  1983. }
  1984. StringRef SourceLocExpr::getBuiltinStr() const {
  1985. switch (getIdentKind()) {
  1986. case File:
  1987. return "__builtin_FILE";
  1988. case Function:
  1989. return "__builtin_FUNCTION";
  1990. case Line:
  1991. return "__builtin_LINE";
  1992. case Column:
  1993. return "__builtin_COLUMN";
  1994. case SourceLocStruct:
  1995. return "__builtin_source_location";
  1996. }
  1997. llvm_unreachable("unexpected IdentKind!");
  1998. }
  1999. APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
  2000. const Expr *DefaultExpr) const {
  2001. SourceLocation Loc;
  2002. const DeclContext *Context;
  2003. std::tie(Loc,
  2004. Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
  2005. if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
  2006. return {DIE->getUsedLocation(), DIE->getUsedContext()};
  2007. if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
  2008. return {DAE->getUsedLocation(), DAE->getUsedContext()};
  2009. return {this->getLocation(), this->getParentContext()};
  2010. }();
  2011. PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
  2012. Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
  2013. auto MakeStringLiteral = [&](StringRef Tmp) {
  2014. using LValuePathEntry = APValue::LValuePathEntry;
  2015. StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
  2016. // Decay the string to a pointer to the first character.
  2017. LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
  2018. return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
  2019. };
  2020. switch (getIdentKind()) {
  2021. case SourceLocExpr::File: {
  2022. SmallString<256> Path(PLoc.getFilename());
  2023. clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
  2024. Ctx.getTargetInfo());
  2025. return MakeStringLiteral(Path);
  2026. }
  2027. case SourceLocExpr::Function: {
  2028. const auto *CurDecl = dyn_cast<Decl>(Context);
  2029. return MakeStringLiteral(
  2030. CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
  2031. : std::string(""));
  2032. }
  2033. case SourceLocExpr::Line:
  2034. case SourceLocExpr::Column: {
  2035. llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
  2036. /*isUnsigned=*/true);
  2037. IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
  2038. : PLoc.getColumn();
  2039. return APValue(IntVal);
  2040. }
  2041. case SourceLocExpr::SourceLocStruct: {
  2042. // Fill in a std::source_location::__impl structure, by creating an
  2043. // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
  2044. // that.
  2045. const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
  2046. assert(ImplDecl);
  2047. // Construct an APValue for the __impl struct, and get or create a Decl
  2048. // corresponding to that. Note that we've already verified that the shape of
  2049. // the ImplDecl type is as expected.
  2050. APValue Value(APValue::UninitStruct(), 0, 4);
  2051. for (FieldDecl *F : ImplDecl->fields()) {
  2052. StringRef Name = F->getName();
  2053. if (Name == "_M_file_name") {
  2054. SmallString<256> Path(PLoc.getFilename());
  2055. clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
  2056. Ctx.getTargetInfo());
  2057. Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
  2058. } else if (Name == "_M_function_name") {
  2059. // Note: this emits the PrettyFunction name -- different than what
  2060. // __builtin_FUNCTION() above returns!
  2061. const auto *CurDecl = dyn_cast<Decl>(Context);
  2062. Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
  2063. CurDecl && !isa<TranslationUnitDecl>(CurDecl)
  2064. ? StringRef(PredefinedExpr::ComputeName(
  2065. PredefinedExpr::PrettyFunction, CurDecl))
  2066. : "");
  2067. } else if (Name == "_M_line") {
  2068. QualType Ty = F->getType();
  2069. llvm::APSInt IntVal(Ctx.getIntWidth(Ty),
  2070. Ty->hasUnsignedIntegerRepresentation());
  2071. IntVal = PLoc.getLine();
  2072. Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
  2073. } else if (Name == "_M_column") {
  2074. QualType Ty = F->getType();
  2075. llvm::APSInt IntVal(Ctx.getIntWidth(Ty),
  2076. Ty->hasUnsignedIntegerRepresentation());
  2077. IntVal = PLoc.getColumn();
  2078. Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
  2079. }
  2080. }
  2081. UnnamedGlobalConstantDecl *GV =
  2082. Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
  2083. return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
  2084. false);
  2085. }
  2086. }
  2087. llvm_unreachable("unhandled case");
  2088. }
  2089. InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
  2090. ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
  2091. : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
  2092. InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
  2093. RBraceLoc(rbraceloc), AltForm(nullptr, true) {
  2094. sawArrayRangeDesignator(false);
  2095. InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
  2096. setDependence(computeDependence(this));
  2097. }
  2098. void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
  2099. if (NumInits > InitExprs.size())
  2100. InitExprs.reserve(C, NumInits);
  2101. }
  2102. void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
  2103. InitExprs.resize(C, NumInits, nullptr);
  2104. }
  2105. Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
  2106. if (Init >= InitExprs.size()) {
  2107. InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
  2108. setInit(Init, expr);
  2109. return nullptr;
  2110. }
  2111. Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
  2112. setInit(Init, expr);
  2113. return Result;
  2114. }
  2115. void InitListExpr::setArrayFiller(Expr *filler) {
  2116. assert(!hasArrayFiller() && "Filler already set!");
  2117. ArrayFillerOrUnionFieldInit = filler;
  2118. // Fill out any "holes" in the array due to designated initializers.
  2119. Expr **inits = getInits();
  2120. for (unsigned i = 0, e = getNumInits(); i != e; ++i)
  2121. if (inits[i] == nullptr)
  2122. inits[i] = filler;
  2123. }
  2124. bool InitListExpr::isStringLiteralInit() const {
  2125. if (getNumInits() != 1)
  2126. return false;
  2127. const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
  2128. if (!AT || !AT->getElementType()->isIntegerType())
  2129. return false;
  2130. // It is possible for getInit() to return null.
  2131. const Expr *Init = getInit(0);
  2132. if (!Init)
  2133. return false;
  2134. Init = Init->IgnoreParenImpCasts();
  2135. return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
  2136. }
  2137. bool InitListExpr::isTransparent() const {
  2138. assert(isSemanticForm() && "syntactic form never semantically transparent");
  2139. // A glvalue InitListExpr is always just sugar.
  2140. if (isGLValue()) {
  2141. assert(getNumInits() == 1 && "multiple inits in glvalue init list");
  2142. return true;
  2143. }
  2144. // Otherwise, we're sugar if and only if we have exactly one initializer that
  2145. // is of the same type.
  2146. if (getNumInits() != 1 || !getInit(0))
  2147. return false;
  2148. // Don't confuse aggregate initialization of a struct X { X &x; }; with a
  2149. // transparent struct copy.
  2150. if (!getInit(0)->isPRValue() && getType()->isRecordType())
  2151. return false;
  2152. return getType().getCanonicalType() ==
  2153. getInit(0)->getType().getCanonicalType();
  2154. }
  2155. bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
  2156. assert(isSyntacticForm() && "only test syntactic form as zero initializer");
  2157. if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
  2158. return false;
  2159. }
  2160. const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
  2161. return Lit && Lit->getValue() == 0;
  2162. }
  2163. SourceLocation InitListExpr::getBeginLoc() const {
  2164. if (InitListExpr *SyntacticForm = getSyntacticForm())
  2165. return SyntacticForm->getBeginLoc();
  2166. SourceLocation Beg = LBraceLoc;
  2167. if (Beg.isInvalid()) {
  2168. // Find the first non-null initializer.
  2169. for (InitExprsTy::const_iterator I = InitExprs.begin(),
  2170. E = InitExprs.end();
  2171. I != E; ++I) {
  2172. if (Stmt *S = *I) {
  2173. Beg = S->getBeginLoc();
  2174. break;
  2175. }
  2176. }
  2177. }
  2178. return Beg;
  2179. }
  2180. SourceLocation InitListExpr::getEndLoc() const {
  2181. if (InitListExpr *SyntacticForm = getSyntacticForm())
  2182. return SyntacticForm->getEndLoc();
  2183. SourceLocation End = RBraceLoc;
  2184. if (End.isInvalid()) {
  2185. // Find the first non-null initializer from the end.
  2186. for (Stmt *S : llvm::reverse(InitExprs)) {
  2187. if (S) {
  2188. End = S->getEndLoc();
  2189. break;
  2190. }
  2191. }
  2192. }
  2193. return End;
  2194. }
  2195. /// getFunctionType - Return the underlying function type for this block.
  2196. ///
  2197. const FunctionProtoType *BlockExpr::getFunctionType() const {
  2198. // The block pointer is never sugared, but the function type might be.
  2199. return cast<BlockPointerType>(getType())
  2200. ->getPointeeType()->castAs<FunctionProtoType>();
  2201. }
  2202. SourceLocation BlockExpr::getCaretLocation() const {
  2203. return TheBlock->getCaretLocation();
  2204. }
  2205. const Stmt *BlockExpr::getBody() const {
  2206. return TheBlock->getBody();
  2207. }
  2208. Stmt *BlockExpr::getBody() {
  2209. return TheBlock->getBody();
  2210. }
  2211. //===----------------------------------------------------------------------===//
  2212. // Generic Expression Routines
  2213. //===----------------------------------------------------------------------===//
  2214. bool Expr::isReadIfDiscardedInCPlusPlus11() const {
  2215. // In C++11, discarded-value expressions of a certain form are special,
  2216. // according to [expr]p10:
  2217. // The lvalue-to-rvalue conversion (4.1) is applied only if the
  2218. // expression is a glvalue of volatile-qualified type and it has
  2219. // one of the following forms:
  2220. if (!isGLValue() || !getType().isVolatileQualified())
  2221. return false;
  2222. const Expr *E = IgnoreParens();
  2223. // - id-expression (5.1.1),
  2224. if (isa<DeclRefExpr>(E))
  2225. return true;
  2226. // - subscripting (5.2.1),
  2227. if (isa<ArraySubscriptExpr>(E))
  2228. return true;
  2229. // - class member access (5.2.5),
  2230. if (isa<MemberExpr>(E))
  2231. return true;
  2232. // - indirection (5.3.1),
  2233. if (auto *UO = dyn_cast<UnaryOperator>(E))
  2234. if (UO->getOpcode() == UO_Deref)
  2235. return true;
  2236. if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  2237. // - pointer-to-member operation (5.5),
  2238. if (BO->isPtrMemOp())
  2239. return true;
  2240. // - comma expression (5.18) where the right operand is one of the above.
  2241. if (BO->getOpcode() == BO_Comma)
  2242. return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
  2243. }
  2244. // - conditional expression (5.16) where both the second and the third
  2245. // operands are one of the above, or
  2246. if (auto *CO = dyn_cast<ConditionalOperator>(E))
  2247. return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
  2248. CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
  2249. // The related edge case of "*x ?: *x".
  2250. if (auto *BCO =
  2251. dyn_cast<BinaryConditionalOperator>(E)) {
  2252. if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
  2253. return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
  2254. BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
  2255. }
  2256. // Objective-C++ extensions to the rule.
  2257. if (isa<ObjCIvarRefExpr>(E))
  2258. return true;
  2259. if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
  2260. if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
  2261. return true;
  2262. }
  2263. return false;
  2264. }
  2265. /// isUnusedResultAWarning - Return true if this immediate expression should
  2266. /// be warned about if the result is unused. If so, fill in Loc and Ranges
  2267. /// with location to warn on and the source range[s] to report with the
  2268. /// warning.
  2269. bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
  2270. SourceRange &R1, SourceRange &R2,
  2271. ASTContext &Ctx) const {
  2272. // Don't warn if the expr is type dependent. The type could end up
  2273. // instantiating to void.
  2274. if (isTypeDependent())
  2275. return false;
  2276. switch (getStmtClass()) {
  2277. default:
  2278. if (getType()->isVoidType())
  2279. return false;
  2280. WarnE = this;
  2281. Loc = getExprLoc();
  2282. R1 = getSourceRange();
  2283. return true;
  2284. case ParenExprClass:
  2285. return cast<ParenExpr>(this)->getSubExpr()->
  2286. isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2287. case GenericSelectionExprClass:
  2288. return cast<GenericSelectionExpr>(this)->getResultExpr()->
  2289. isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2290. case CoawaitExprClass:
  2291. case CoyieldExprClass:
  2292. return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
  2293. isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2294. case ChooseExprClass:
  2295. return cast<ChooseExpr>(this)->getChosenSubExpr()->
  2296. isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2297. case UnaryOperatorClass: {
  2298. const UnaryOperator *UO = cast<UnaryOperator>(this);
  2299. switch (UO->getOpcode()) {
  2300. case UO_Plus:
  2301. case UO_Minus:
  2302. case UO_AddrOf:
  2303. case UO_Not:
  2304. case UO_LNot:
  2305. case UO_Deref:
  2306. break;
  2307. case UO_Coawait:
  2308. // This is just the 'operator co_await' call inside the guts of a
  2309. // dependent co_await call.
  2310. case UO_PostInc:
  2311. case UO_PostDec:
  2312. case UO_PreInc:
  2313. case UO_PreDec: // ++/--
  2314. return false; // Not a warning.
  2315. case UO_Real:
  2316. case UO_Imag:
  2317. // accessing a piece of a volatile complex is a side-effect.
  2318. if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
  2319. .isVolatileQualified())
  2320. return false;
  2321. break;
  2322. case UO_Extension:
  2323. return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2324. }
  2325. WarnE = this;
  2326. Loc = UO->getOperatorLoc();
  2327. R1 = UO->getSubExpr()->getSourceRange();
  2328. return true;
  2329. }
  2330. case BinaryOperatorClass: {
  2331. const BinaryOperator *BO = cast<BinaryOperator>(this);
  2332. switch (BO->getOpcode()) {
  2333. default:
  2334. break;
  2335. // Consider the RHS of comma for side effects. LHS was checked by
  2336. // Sema::CheckCommaOperands.
  2337. case BO_Comma:
  2338. // ((foo = <blah>), 0) is an idiom for hiding the result (and
  2339. // lvalue-ness) of an assignment written in a macro.
  2340. if (IntegerLiteral *IE =
  2341. dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
  2342. if (IE->getValue() == 0)
  2343. return false;
  2344. return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2345. // Consider '||', '&&' to have side effects if the LHS or RHS does.
  2346. case BO_LAnd:
  2347. case BO_LOr:
  2348. if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
  2349. !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
  2350. return false;
  2351. break;
  2352. }
  2353. if (BO->isAssignmentOp())
  2354. return false;
  2355. WarnE = this;
  2356. Loc = BO->getOperatorLoc();
  2357. R1 = BO->getLHS()->getSourceRange();
  2358. R2 = BO->getRHS()->getSourceRange();
  2359. return true;
  2360. }
  2361. case CompoundAssignOperatorClass:
  2362. case VAArgExprClass:
  2363. case AtomicExprClass:
  2364. return false;
  2365. case ConditionalOperatorClass: {
  2366. // If only one of the LHS or RHS is a warning, the operator might
  2367. // be being used for control flow. Only warn if both the LHS and
  2368. // RHS are warnings.
  2369. const auto *Exp = cast<ConditionalOperator>(this);
  2370. return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
  2371. Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2372. }
  2373. case BinaryConditionalOperatorClass: {
  2374. const auto *Exp = cast<BinaryConditionalOperator>(this);
  2375. return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2376. }
  2377. case MemberExprClass:
  2378. WarnE = this;
  2379. Loc = cast<MemberExpr>(this)->getMemberLoc();
  2380. R1 = SourceRange(Loc, Loc);
  2381. R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
  2382. return true;
  2383. case ArraySubscriptExprClass:
  2384. WarnE = this;
  2385. Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
  2386. R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
  2387. R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
  2388. return true;
  2389. case CXXOperatorCallExprClass: {
  2390. // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
  2391. // overloads as there is no reasonable way to define these such that they
  2392. // have non-trivial, desirable side-effects. See the -Wunused-comparison
  2393. // warning: operators == and != are commonly typo'ed, and so warning on them
  2394. // provides additional value as well. If this list is updated,
  2395. // DiagnoseUnusedComparison should be as well.
  2396. const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
  2397. switch (Op->getOperator()) {
  2398. default:
  2399. break;
  2400. case OO_EqualEqual:
  2401. case OO_ExclaimEqual:
  2402. case OO_Less:
  2403. case OO_Greater:
  2404. case OO_GreaterEqual:
  2405. case OO_LessEqual:
  2406. if (Op->getCallReturnType(Ctx)->isReferenceType() ||
  2407. Op->getCallReturnType(Ctx)->isVoidType())
  2408. break;
  2409. WarnE = this;
  2410. Loc = Op->getOperatorLoc();
  2411. R1 = Op->getSourceRange();
  2412. return true;
  2413. }
  2414. // Fallthrough for generic call handling.
  2415. [[fallthrough]];
  2416. }
  2417. case CallExprClass:
  2418. case CXXMemberCallExprClass:
  2419. case UserDefinedLiteralClass: {
  2420. // If this is a direct call, get the callee.
  2421. const CallExpr *CE = cast<CallExpr>(this);
  2422. if (const Decl *FD = CE->getCalleeDecl()) {
  2423. // If the callee has attribute pure, const, or warn_unused_result, warn
  2424. // about it. void foo() { strlen("bar"); } should warn.
  2425. //
  2426. // Note: If new cases are added here, DiagnoseUnusedExprResult should be
  2427. // updated to match for QoI.
  2428. if (CE->hasUnusedResultAttr(Ctx) ||
  2429. FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
  2430. WarnE = this;
  2431. Loc = CE->getCallee()->getBeginLoc();
  2432. R1 = CE->getCallee()->getSourceRange();
  2433. if (unsigned NumArgs = CE->getNumArgs())
  2434. R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
  2435. CE->getArg(NumArgs - 1)->getEndLoc());
  2436. return true;
  2437. }
  2438. }
  2439. return false;
  2440. }
  2441. // If we don't know precisely what we're looking at, let's not warn.
  2442. case UnresolvedLookupExprClass:
  2443. case CXXUnresolvedConstructExprClass:
  2444. case RecoveryExprClass:
  2445. return false;
  2446. case CXXTemporaryObjectExprClass:
  2447. case CXXConstructExprClass: {
  2448. if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
  2449. const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
  2450. if (Type->hasAttr<WarnUnusedAttr>() ||
  2451. (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
  2452. WarnE = this;
  2453. Loc = getBeginLoc();
  2454. R1 = getSourceRange();
  2455. return true;
  2456. }
  2457. }
  2458. const auto *CE = cast<CXXConstructExpr>(this);
  2459. if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
  2460. const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
  2461. if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
  2462. WarnE = this;
  2463. Loc = getBeginLoc();
  2464. R1 = getSourceRange();
  2465. if (unsigned NumArgs = CE->getNumArgs())
  2466. R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
  2467. CE->getArg(NumArgs - 1)->getEndLoc());
  2468. return true;
  2469. }
  2470. }
  2471. return false;
  2472. }
  2473. case ObjCMessageExprClass: {
  2474. const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
  2475. if (Ctx.getLangOpts().ObjCAutoRefCount &&
  2476. ME->isInstanceMessage() &&
  2477. !ME->getType()->isVoidType() &&
  2478. ME->getMethodFamily() == OMF_init) {
  2479. WarnE = this;
  2480. Loc = getExprLoc();
  2481. R1 = ME->getSourceRange();
  2482. return true;
  2483. }
  2484. if (const ObjCMethodDecl *MD = ME->getMethodDecl())
  2485. if (MD->hasAttr<WarnUnusedResultAttr>()) {
  2486. WarnE = this;
  2487. Loc = getExprLoc();
  2488. return true;
  2489. }
  2490. return false;
  2491. }
  2492. case ObjCPropertyRefExprClass:
  2493. case ObjCSubscriptRefExprClass:
  2494. WarnE = this;
  2495. Loc = getExprLoc();
  2496. R1 = getSourceRange();
  2497. return true;
  2498. case PseudoObjectExprClass: {
  2499. const auto *POE = cast<PseudoObjectExpr>(this);
  2500. // For some syntactic forms, we should always warn.
  2501. if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
  2502. POE->getSyntacticForm())) {
  2503. WarnE = this;
  2504. Loc = getExprLoc();
  2505. R1 = getSourceRange();
  2506. return true;
  2507. }
  2508. // For others, we should never warn.
  2509. if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
  2510. if (BO->isAssignmentOp())
  2511. return false;
  2512. if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
  2513. if (UO->isIncrementDecrementOp())
  2514. return false;
  2515. // Otherwise, warn if the result expression would warn.
  2516. const Expr *Result = POE->getResultExpr();
  2517. return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2518. }
  2519. case StmtExprClass: {
  2520. // Statement exprs don't logically have side effects themselves, but are
  2521. // sometimes used in macros in ways that give them a type that is unused.
  2522. // For example ({ blah; foo(); }) will end up with a type if foo has a type.
  2523. // however, if the result of the stmt expr is dead, we don't want to emit a
  2524. // warning.
  2525. const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
  2526. if (!CS->body_empty()) {
  2527. if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
  2528. return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2529. if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
  2530. if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
  2531. return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2532. }
  2533. if (getType()->isVoidType())
  2534. return false;
  2535. WarnE = this;
  2536. Loc = cast<StmtExpr>(this)->getLParenLoc();
  2537. R1 = getSourceRange();
  2538. return true;
  2539. }
  2540. case CXXFunctionalCastExprClass:
  2541. case CStyleCastExprClass: {
  2542. // Ignore an explicit cast to void, except in C++98 if the operand is a
  2543. // volatile glvalue for which we would trigger an implicit read in any
  2544. // other language mode. (Such an implicit read always happens as part of
  2545. // the lvalue conversion in C, and happens in C++ for expressions of all
  2546. // forms where it seems likely the user intended to trigger a volatile
  2547. // load.)
  2548. const CastExpr *CE = cast<CastExpr>(this);
  2549. const Expr *SubE = CE->getSubExpr()->IgnoreParens();
  2550. if (CE->getCastKind() == CK_ToVoid) {
  2551. if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
  2552. SubE->isReadIfDiscardedInCPlusPlus11()) {
  2553. // Suppress the "unused value" warning for idiomatic usage of
  2554. // '(void)var;' used to suppress "unused variable" warnings.
  2555. if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
  2556. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  2557. if (!VD->isExternallyVisible())
  2558. return false;
  2559. // The lvalue-to-rvalue conversion would have no effect for an array.
  2560. // It's implausible that the programmer expected this to result in a
  2561. // volatile array load, so don't warn.
  2562. if (SubE->getType()->isArrayType())
  2563. return false;
  2564. return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2565. }
  2566. return false;
  2567. }
  2568. // If this is a cast to a constructor conversion, check the operand.
  2569. // Otherwise, the result of the cast is unused.
  2570. if (CE->getCastKind() == CK_ConstructorConversion)
  2571. return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2572. if (CE->getCastKind() == CK_Dependent)
  2573. return false;
  2574. WarnE = this;
  2575. if (const CXXFunctionalCastExpr *CXXCE =
  2576. dyn_cast<CXXFunctionalCastExpr>(this)) {
  2577. Loc = CXXCE->getBeginLoc();
  2578. R1 = CXXCE->getSubExpr()->getSourceRange();
  2579. } else {
  2580. const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
  2581. Loc = CStyleCE->getLParenLoc();
  2582. R1 = CStyleCE->getSubExpr()->getSourceRange();
  2583. }
  2584. return true;
  2585. }
  2586. case ImplicitCastExprClass: {
  2587. const CastExpr *ICE = cast<ImplicitCastExpr>(this);
  2588. // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
  2589. if (ICE->getCastKind() == CK_LValueToRValue &&
  2590. ICE->getSubExpr()->getType().isVolatileQualified())
  2591. return false;
  2592. return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2593. }
  2594. case CXXDefaultArgExprClass:
  2595. return (cast<CXXDefaultArgExpr>(this)
  2596. ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
  2597. case CXXDefaultInitExprClass:
  2598. return (cast<CXXDefaultInitExpr>(this)
  2599. ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
  2600. case CXXNewExprClass:
  2601. // FIXME: In theory, there might be new expressions that don't have side
  2602. // effects (e.g. a placement new with an uninitialized POD).
  2603. case CXXDeleteExprClass:
  2604. return false;
  2605. case MaterializeTemporaryExprClass:
  2606. return cast<MaterializeTemporaryExpr>(this)
  2607. ->getSubExpr()
  2608. ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2609. case CXXBindTemporaryExprClass:
  2610. return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
  2611. ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2612. case ExprWithCleanupsClass:
  2613. return cast<ExprWithCleanups>(this)->getSubExpr()
  2614. ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
  2615. }
  2616. }
  2617. /// isOBJCGCCandidate - Check if an expression is objc gc'able.
  2618. /// returns true, if it is; false otherwise.
  2619. bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
  2620. const Expr *E = IgnoreParens();
  2621. switch (E->getStmtClass()) {
  2622. default:
  2623. return false;
  2624. case ObjCIvarRefExprClass:
  2625. return true;
  2626. case Expr::UnaryOperatorClass:
  2627. return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
  2628. case ImplicitCastExprClass:
  2629. return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
  2630. case MaterializeTemporaryExprClass:
  2631. return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
  2632. Ctx);
  2633. case CStyleCastExprClass:
  2634. return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
  2635. case DeclRefExprClass: {
  2636. const Decl *D = cast<DeclRefExpr>(E)->getDecl();
  2637. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2638. if (VD->hasGlobalStorage())
  2639. return true;
  2640. QualType T = VD->getType();
  2641. // dereferencing to a pointer is always a gc'able candidate,
  2642. // unless it is __weak.
  2643. return T->isPointerType() &&
  2644. (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
  2645. }
  2646. return false;
  2647. }
  2648. case MemberExprClass: {
  2649. const MemberExpr *M = cast<MemberExpr>(E);
  2650. return M->getBase()->isOBJCGCCandidate(Ctx);
  2651. }
  2652. case ArraySubscriptExprClass:
  2653. return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
  2654. }
  2655. }
  2656. bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
  2657. if (isTypeDependent())
  2658. return false;
  2659. return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
  2660. }
  2661. QualType Expr::findBoundMemberType(const Expr *expr) {
  2662. assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
  2663. // Bound member expressions are always one of these possibilities:
  2664. // x->m x.m x->*y x.*y
  2665. // (possibly parenthesized)
  2666. expr = expr->IgnoreParens();
  2667. if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
  2668. assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
  2669. return mem->getMemberDecl()->getType();
  2670. }
  2671. if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
  2672. QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
  2673. ->getPointeeType();
  2674. assert(type->isFunctionType());
  2675. return type;
  2676. }
  2677. assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
  2678. return QualType();
  2679. }
  2680. Expr *Expr::IgnoreImpCasts() {
  2681. return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
  2682. }
  2683. Expr *Expr::IgnoreCasts() {
  2684. return IgnoreExprNodes(this, IgnoreCastsSingleStep);
  2685. }
  2686. Expr *Expr::IgnoreImplicit() {
  2687. return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
  2688. }
  2689. Expr *Expr::IgnoreImplicitAsWritten() {
  2690. return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
  2691. }
  2692. Expr *Expr::IgnoreParens() {
  2693. return IgnoreExprNodes(this, IgnoreParensSingleStep);
  2694. }
  2695. Expr *Expr::IgnoreParenImpCasts() {
  2696. return IgnoreExprNodes(this, IgnoreParensSingleStep,
  2697. IgnoreImplicitCastsExtraSingleStep);
  2698. }
  2699. Expr *Expr::IgnoreParenCasts() {
  2700. return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
  2701. }
  2702. Expr *Expr::IgnoreConversionOperatorSingleStep() {
  2703. if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
  2704. if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
  2705. return MCE->getImplicitObjectArgument();
  2706. }
  2707. return this;
  2708. }
  2709. Expr *Expr::IgnoreParenLValueCasts() {
  2710. return IgnoreExprNodes(this, IgnoreParensSingleStep,
  2711. IgnoreLValueCastsSingleStep);
  2712. }
  2713. Expr *Expr::IgnoreParenBaseCasts() {
  2714. return IgnoreExprNodes(this, IgnoreParensSingleStep,
  2715. IgnoreBaseCastsSingleStep);
  2716. }
  2717. Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
  2718. auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
  2719. if (auto *CE = dyn_cast<CastExpr>(E)) {
  2720. // We ignore integer <-> casts that are of the same width, ptr<->ptr and
  2721. // ptr<->int casts of the same width. We also ignore all identity casts.
  2722. Expr *SubExpr = CE->getSubExpr();
  2723. bool IsIdentityCast =
  2724. Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
  2725. bool IsSameWidthCast = (E->getType()->isPointerType() ||
  2726. E->getType()->isIntegralType(Ctx)) &&
  2727. (SubExpr->getType()->isPointerType() ||
  2728. SubExpr->getType()->isIntegralType(Ctx)) &&
  2729. (Ctx.getTypeSize(E->getType()) ==
  2730. Ctx.getTypeSize(SubExpr->getType()));
  2731. if (IsIdentityCast || IsSameWidthCast)
  2732. return SubExpr;
  2733. } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
  2734. return NTTP->getReplacement();
  2735. return E;
  2736. };
  2737. return IgnoreExprNodes(this, IgnoreParensSingleStep,
  2738. IgnoreNoopCastsSingleStep);
  2739. }
  2740. Expr *Expr::IgnoreUnlessSpelledInSource() {
  2741. auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
  2742. if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
  2743. auto *SE = Cast->getSubExpr();
  2744. if (SE->getSourceRange() == E->getSourceRange())
  2745. return SE;
  2746. }
  2747. if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
  2748. auto NumArgs = C->getNumArgs();
  2749. if (NumArgs == 1 ||
  2750. (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
  2751. Expr *A = C->getArg(0);
  2752. if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
  2753. return A;
  2754. }
  2755. }
  2756. return E;
  2757. };
  2758. auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
  2759. if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
  2760. Expr *ExprNode = C->getImplicitObjectArgument();
  2761. if (ExprNode->getSourceRange() == E->getSourceRange()) {
  2762. return ExprNode;
  2763. }
  2764. if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
  2765. if (PE->getSourceRange() == C->getSourceRange()) {
  2766. return cast<Expr>(PE);
  2767. }
  2768. }
  2769. ExprNode = ExprNode->IgnoreParenImpCasts();
  2770. if (ExprNode->getSourceRange() == E->getSourceRange())
  2771. return ExprNode;
  2772. }
  2773. return E;
  2774. };
  2775. return IgnoreExprNodes(
  2776. this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
  2777. IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
  2778. IgnoreImplicitMemberCallSingleStep);
  2779. }
  2780. bool Expr::isDefaultArgument() const {
  2781. const Expr *E = this;
  2782. if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
  2783. E = M->getSubExpr();
  2784. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  2785. E = ICE->getSubExprAsWritten();
  2786. return isa<CXXDefaultArgExpr>(E);
  2787. }
  2788. /// Skip over any no-op casts and any temporary-binding
  2789. /// expressions.
  2790. static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
  2791. if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
  2792. E = M->getSubExpr();
  2793. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2794. if (ICE->getCastKind() == CK_NoOp)
  2795. E = ICE->getSubExpr();
  2796. else
  2797. break;
  2798. }
  2799. while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
  2800. E = BE->getSubExpr();
  2801. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2802. if (ICE->getCastKind() == CK_NoOp)
  2803. E = ICE->getSubExpr();
  2804. else
  2805. break;
  2806. }
  2807. return E->IgnoreParens();
  2808. }
  2809. /// isTemporaryObject - Determines if this expression produces a
  2810. /// temporary of the given class type.
  2811. bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
  2812. if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
  2813. return false;
  2814. const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
  2815. // Temporaries are by definition pr-values of class type.
  2816. if (!E->Classify(C).isPRValue()) {
  2817. // In this context, property reference is a message call and is pr-value.
  2818. if (!isa<ObjCPropertyRefExpr>(E))
  2819. return false;
  2820. }
  2821. // Black-list a few cases which yield pr-values of class type that don't
  2822. // refer to temporaries of that type:
  2823. // - implicit derived-to-base conversions
  2824. if (isa<ImplicitCastExpr>(E)) {
  2825. switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
  2826. case CK_DerivedToBase:
  2827. case CK_UncheckedDerivedToBase:
  2828. return false;
  2829. default:
  2830. break;
  2831. }
  2832. }
  2833. // - member expressions (all)
  2834. if (isa<MemberExpr>(E))
  2835. return false;
  2836. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
  2837. if (BO->isPtrMemOp())
  2838. return false;
  2839. // - opaque values (all)
  2840. if (isa<OpaqueValueExpr>(E))
  2841. return false;
  2842. return true;
  2843. }
  2844. bool Expr::isImplicitCXXThis() const {
  2845. const Expr *E = this;
  2846. // Strip away parentheses and casts we don't care about.
  2847. while (true) {
  2848. if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
  2849. E = Paren->getSubExpr();
  2850. continue;
  2851. }
  2852. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2853. if (ICE->getCastKind() == CK_NoOp ||
  2854. ICE->getCastKind() == CK_LValueToRValue ||
  2855. ICE->getCastKind() == CK_DerivedToBase ||
  2856. ICE->getCastKind() == CK_UncheckedDerivedToBase) {
  2857. E = ICE->getSubExpr();
  2858. continue;
  2859. }
  2860. }
  2861. if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
  2862. if (UnOp->getOpcode() == UO_Extension) {
  2863. E = UnOp->getSubExpr();
  2864. continue;
  2865. }
  2866. }
  2867. if (const MaterializeTemporaryExpr *M
  2868. = dyn_cast<MaterializeTemporaryExpr>(E)) {
  2869. E = M->getSubExpr();
  2870. continue;
  2871. }
  2872. break;
  2873. }
  2874. if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
  2875. return This->isImplicit();
  2876. return false;
  2877. }
  2878. /// hasAnyTypeDependentArguments - Determines if any of the expressions
  2879. /// in Exprs is type-dependent.
  2880. bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
  2881. for (unsigned I = 0; I < Exprs.size(); ++I)
  2882. if (Exprs[I]->isTypeDependent())
  2883. return true;
  2884. return false;
  2885. }
  2886. bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
  2887. const Expr **Culprit) const {
  2888. assert(!isValueDependent() &&
  2889. "Expression evaluator can't be called on a dependent expression.");
  2890. // This function is attempting whether an expression is an initializer
  2891. // which can be evaluated at compile-time. It very closely parallels
  2892. // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
  2893. // will lead to unexpected results. Like ConstExprEmitter, it falls back
  2894. // to isEvaluatable most of the time.
  2895. //
  2896. // If we ever capture reference-binding directly in the AST, we can
  2897. // kill the second parameter.
  2898. if (IsForRef) {
  2899. EvalResult Result;
  2900. if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
  2901. return true;
  2902. if (Culprit)
  2903. *Culprit = this;
  2904. return false;
  2905. }
  2906. switch (getStmtClass()) {
  2907. default: break;
  2908. case Stmt::ExprWithCleanupsClass:
  2909. return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
  2910. Ctx, IsForRef, Culprit);
  2911. case StringLiteralClass:
  2912. case ObjCEncodeExprClass:
  2913. return true;
  2914. case CXXTemporaryObjectExprClass:
  2915. case CXXConstructExprClass: {
  2916. const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
  2917. if (CE->getConstructor()->isTrivial() &&
  2918. CE->getConstructor()->getParent()->hasTrivialDestructor()) {
  2919. // Trivial default constructor
  2920. if (!CE->getNumArgs()) return true;
  2921. // Trivial copy constructor
  2922. assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
  2923. return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
  2924. }
  2925. break;
  2926. }
  2927. case ConstantExprClass: {
  2928. // FIXME: We should be able to return "true" here, but it can lead to extra
  2929. // error messages. E.g. in Sema/array-init.c.
  2930. const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
  2931. return Exp->isConstantInitializer(Ctx, false, Culprit);
  2932. }
  2933. case CompoundLiteralExprClass: {
  2934. // This handles gcc's extension that allows global initializers like
  2935. // "struct x {int x;} x = (struct x) {};".
  2936. // FIXME: This accepts other cases it shouldn't!
  2937. const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
  2938. return Exp->isConstantInitializer(Ctx, false, Culprit);
  2939. }
  2940. case DesignatedInitUpdateExprClass: {
  2941. const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
  2942. return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
  2943. DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
  2944. }
  2945. case InitListExprClass: {
  2946. const InitListExpr *ILE = cast<InitListExpr>(this);
  2947. assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
  2948. if (ILE->getType()->isArrayType()) {
  2949. unsigned numInits = ILE->getNumInits();
  2950. for (unsigned i = 0; i < numInits; i++) {
  2951. if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
  2952. return false;
  2953. }
  2954. return true;
  2955. }
  2956. if (ILE->getType()->isRecordType()) {
  2957. unsigned ElementNo = 0;
  2958. RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
  2959. for (const auto *Field : RD->fields()) {
  2960. // If this is a union, skip all the fields that aren't being initialized.
  2961. if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
  2962. continue;
  2963. // Don't emit anonymous bitfields, they just affect layout.
  2964. if (Field->isUnnamedBitfield())
  2965. continue;
  2966. if (ElementNo < ILE->getNumInits()) {
  2967. const Expr *Elt = ILE->getInit(ElementNo++);
  2968. if (Field->isBitField()) {
  2969. // Bitfields have to evaluate to an integer.
  2970. EvalResult Result;
  2971. if (!Elt->EvaluateAsInt(Result, Ctx)) {
  2972. if (Culprit)
  2973. *Culprit = Elt;
  2974. return false;
  2975. }
  2976. } else {
  2977. bool RefType = Field->getType()->isReferenceType();
  2978. if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
  2979. return false;
  2980. }
  2981. }
  2982. }
  2983. return true;
  2984. }
  2985. break;
  2986. }
  2987. case ImplicitValueInitExprClass:
  2988. case NoInitExprClass:
  2989. return true;
  2990. case ParenExprClass:
  2991. return cast<ParenExpr>(this)->getSubExpr()
  2992. ->isConstantInitializer(Ctx, IsForRef, Culprit);
  2993. case GenericSelectionExprClass:
  2994. return cast<GenericSelectionExpr>(this)->getResultExpr()
  2995. ->isConstantInitializer(Ctx, IsForRef, Culprit);
  2996. case ChooseExprClass:
  2997. if (cast<ChooseExpr>(this)->isConditionDependent()) {
  2998. if (Culprit)
  2999. *Culprit = this;
  3000. return false;
  3001. }
  3002. return cast<ChooseExpr>(this)->getChosenSubExpr()
  3003. ->isConstantInitializer(Ctx, IsForRef, Culprit);
  3004. case UnaryOperatorClass: {
  3005. const UnaryOperator* Exp = cast<UnaryOperator>(this);
  3006. if (Exp->getOpcode() == UO_Extension)
  3007. return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
  3008. break;
  3009. }
  3010. case CXXFunctionalCastExprClass:
  3011. case CXXStaticCastExprClass:
  3012. case ImplicitCastExprClass:
  3013. case CStyleCastExprClass:
  3014. case ObjCBridgedCastExprClass:
  3015. case CXXDynamicCastExprClass:
  3016. case CXXReinterpretCastExprClass:
  3017. case CXXAddrspaceCastExprClass:
  3018. case CXXConstCastExprClass: {
  3019. const CastExpr *CE = cast<CastExpr>(this);
  3020. // Handle misc casts we want to ignore.
  3021. if (CE->getCastKind() == CK_NoOp ||
  3022. CE->getCastKind() == CK_LValueToRValue ||
  3023. CE->getCastKind() == CK_ToUnion ||
  3024. CE->getCastKind() == CK_ConstructorConversion ||
  3025. CE->getCastKind() == CK_NonAtomicToAtomic ||
  3026. CE->getCastKind() == CK_AtomicToNonAtomic ||
  3027. CE->getCastKind() == CK_IntToOCLSampler)
  3028. return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
  3029. break;
  3030. }
  3031. case MaterializeTemporaryExprClass:
  3032. return cast<MaterializeTemporaryExpr>(this)
  3033. ->getSubExpr()
  3034. ->isConstantInitializer(Ctx, false, Culprit);
  3035. case SubstNonTypeTemplateParmExprClass:
  3036. return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
  3037. ->isConstantInitializer(Ctx, false, Culprit);
  3038. case CXXDefaultArgExprClass:
  3039. return cast<CXXDefaultArgExpr>(this)->getExpr()
  3040. ->isConstantInitializer(Ctx, false, Culprit);
  3041. case CXXDefaultInitExprClass:
  3042. return cast<CXXDefaultInitExpr>(this)->getExpr()
  3043. ->isConstantInitializer(Ctx, false, Culprit);
  3044. }
  3045. // Allow certain forms of UB in constant initializers: signed integer
  3046. // overflow and floating-point division by zero. We'll give a warning on
  3047. // these, but they're common enough that we have to accept them.
  3048. if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
  3049. return true;
  3050. if (Culprit)
  3051. *Culprit = this;
  3052. return false;
  3053. }
  3054. bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
  3055. unsigned BuiltinID = getBuiltinCallee();
  3056. if (BuiltinID != Builtin::BI__assume &&
  3057. BuiltinID != Builtin::BI__builtin_assume)
  3058. return false;
  3059. const Expr* Arg = getArg(0);
  3060. bool ArgVal;
  3061. return !Arg->isValueDependent() &&
  3062. Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
  3063. }
  3064. bool CallExpr::isCallToStdMove() const {
  3065. return getBuiltinCallee() == Builtin::BImove;
  3066. }
  3067. namespace {
  3068. /// Look for any side effects within a Stmt.
  3069. class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
  3070. typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
  3071. const bool IncludePossibleEffects;
  3072. bool HasSideEffects;
  3073. public:
  3074. explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
  3075. : Inherited(Context),
  3076. IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
  3077. bool hasSideEffects() const { return HasSideEffects; }
  3078. void VisitDecl(const Decl *D) {
  3079. if (!D)
  3080. return;
  3081. // We assume the caller checks subexpressions (eg, the initializer, VLA
  3082. // bounds) for side-effects on our behalf.
  3083. if (auto *VD = dyn_cast<VarDecl>(D)) {
  3084. // Registering a destructor is a side-effect.
  3085. if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
  3086. VD->needsDestruction(Context))
  3087. HasSideEffects = true;
  3088. }
  3089. }
  3090. void VisitDeclStmt(const DeclStmt *DS) {
  3091. for (auto *D : DS->decls())
  3092. VisitDecl(D);
  3093. Inherited::VisitDeclStmt(DS);
  3094. }
  3095. void VisitExpr(const Expr *E) {
  3096. if (!HasSideEffects &&
  3097. E->HasSideEffects(Context, IncludePossibleEffects))
  3098. HasSideEffects = true;
  3099. }
  3100. };
  3101. }
  3102. bool Expr::HasSideEffects(const ASTContext &Ctx,
  3103. bool IncludePossibleEffects) const {
  3104. // In circumstances where we care about definite side effects instead of
  3105. // potential side effects, we want to ignore expressions that are part of a
  3106. // macro expansion as a potential side effect.
  3107. if (!IncludePossibleEffects && getExprLoc().isMacroID())
  3108. return false;
  3109. switch (getStmtClass()) {
  3110. case NoStmtClass:
  3111. #define ABSTRACT_STMT(Type)
  3112. #define STMT(Type, Base) case Type##Class:
  3113. #define EXPR(Type, Base)
  3114. #include "clang/AST/StmtNodes.inc"
  3115. llvm_unreachable("unexpected Expr kind");
  3116. case DependentScopeDeclRefExprClass:
  3117. case CXXUnresolvedConstructExprClass:
  3118. case CXXDependentScopeMemberExprClass:
  3119. case UnresolvedLookupExprClass:
  3120. case UnresolvedMemberExprClass:
  3121. case PackExpansionExprClass:
  3122. case SubstNonTypeTemplateParmPackExprClass:
  3123. case FunctionParmPackExprClass:
  3124. case TypoExprClass:
  3125. case RecoveryExprClass:
  3126. case CXXFoldExprClass:
  3127. // Make a conservative assumption for dependent nodes.
  3128. return IncludePossibleEffects;
  3129. case DeclRefExprClass:
  3130. case ObjCIvarRefExprClass:
  3131. case PredefinedExprClass:
  3132. case IntegerLiteralClass:
  3133. case FixedPointLiteralClass:
  3134. case FloatingLiteralClass:
  3135. case ImaginaryLiteralClass:
  3136. case StringLiteralClass:
  3137. case CharacterLiteralClass:
  3138. case OffsetOfExprClass:
  3139. case ImplicitValueInitExprClass:
  3140. case UnaryExprOrTypeTraitExprClass:
  3141. case AddrLabelExprClass:
  3142. case GNUNullExprClass:
  3143. case ArrayInitIndexExprClass:
  3144. case NoInitExprClass:
  3145. case CXXBoolLiteralExprClass:
  3146. case CXXNullPtrLiteralExprClass:
  3147. case CXXThisExprClass:
  3148. case CXXScalarValueInitExprClass:
  3149. case TypeTraitExprClass:
  3150. case ArrayTypeTraitExprClass:
  3151. case ExpressionTraitExprClass:
  3152. case CXXNoexceptExprClass:
  3153. case SizeOfPackExprClass:
  3154. case ObjCStringLiteralClass:
  3155. case ObjCEncodeExprClass:
  3156. case ObjCBoolLiteralExprClass:
  3157. case ObjCAvailabilityCheckExprClass:
  3158. case CXXUuidofExprClass:
  3159. case OpaqueValueExprClass:
  3160. case SourceLocExprClass:
  3161. case ConceptSpecializationExprClass:
  3162. case RequiresExprClass:
  3163. case SYCLUniqueStableNameExprClass:
  3164. // These never have a side-effect.
  3165. return false;
  3166. case ConstantExprClass:
  3167. // FIXME: Move this into the "return false;" block above.
  3168. return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
  3169. Ctx, IncludePossibleEffects);
  3170. case CallExprClass:
  3171. case CXXOperatorCallExprClass:
  3172. case CXXMemberCallExprClass:
  3173. case CUDAKernelCallExprClass:
  3174. case UserDefinedLiteralClass: {
  3175. // We don't know a call definitely has side effects, except for calls
  3176. // to pure/const functions that definitely don't.
  3177. // If the call itself is considered side-effect free, check the operands.
  3178. const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
  3179. bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
  3180. if (IsPure || !IncludePossibleEffects)
  3181. break;
  3182. return true;
  3183. }
  3184. case BlockExprClass:
  3185. case CXXBindTemporaryExprClass:
  3186. if (!IncludePossibleEffects)
  3187. break;
  3188. return true;
  3189. case MSPropertyRefExprClass:
  3190. case MSPropertySubscriptExprClass:
  3191. case CompoundAssignOperatorClass:
  3192. case VAArgExprClass:
  3193. case AtomicExprClass:
  3194. case CXXThrowExprClass:
  3195. case CXXNewExprClass:
  3196. case CXXDeleteExprClass:
  3197. case CoawaitExprClass:
  3198. case DependentCoawaitExprClass:
  3199. case CoyieldExprClass:
  3200. // These always have a side-effect.
  3201. return true;
  3202. case StmtExprClass: {
  3203. // StmtExprs have a side-effect if any substatement does.
  3204. SideEffectFinder Finder(Ctx, IncludePossibleEffects);
  3205. Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
  3206. return Finder.hasSideEffects();
  3207. }
  3208. case ExprWithCleanupsClass:
  3209. if (IncludePossibleEffects)
  3210. if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
  3211. return true;
  3212. break;
  3213. case ParenExprClass:
  3214. case ArraySubscriptExprClass:
  3215. case MatrixSubscriptExprClass:
  3216. case OMPArraySectionExprClass:
  3217. case OMPArrayShapingExprClass:
  3218. case OMPIteratorExprClass:
  3219. case MemberExprClass:
  3220. case ConditionalOperatorClass:
  3221. case BinaryConditionalOperatorClass:
  3222. case CompoundLiteralExprClass:
  3223. case ExtVectorElementExprClass:
  3224. case DesignatedInitExprClass:
  3225. case DesignatedInitUpdateExprClass:
  3226. case ArrayInitLoopExprClass:
  3227. case ParenListExprClass:
  3228. case CXXPseudoDestructorExprClass:
  3229. case CXXRewrittenBinaryOperatorClass:
  3230. case CXXStdInitializerListExprClass:
  3231. case SubstNonTypeTemplateParmExprClass:
  3232. case MaterializeTemporaryExprClass:
  3233. case ShuffleVectorExprClass:
  3234. case ConvertVectorExprClass:
  3235. case AsTypeExprClass:
  3236. case CXXParenListInitExprClass:
  3237. // These have a side-effect if any subexpression does.
  3238. break;
  3239. case UnaryOperatorClass:
  3240. if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
  3241. return true;
  3242. break;
  3243. case BinaryOperatorClass:
  3244. if (cast<BinaryOperator>(this)->isAssignmentOp())
  3245. return true;
  3246. break;
  3247. case InitListExprClass:
  3248. // FIXME: The children for an InitListExpr doesn't include the array filler.
  3249. if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
  3250. if (E->HasSideEffects(Ctx, IncludePossibleEffects))
  3251. return true;
  3252. break;
  3253. case GenericSelectionExprClass:
  3254. return cast<GenericSelectionExpr>(this)->getResultExpr()->
  3255. HasSideEffects(Ctx, IncludePossibleEffects);
  3256. case ChooseExprClass:
  3257. return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
  3258. Ctx, IncludePossibleEffects);
  3259. case CXXDefaultArgExprClass:
  3260. return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
  3261. Ctx, IncludePossibleEffects);
  3262. case CXXDefaultInitExprClass: {
  3263. const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
  3264. if (const Expr *E = FD->getInClassInitializer())
  3265. return E->HasSideEffects(Ctx, IncludePossibleEffects);
  3266. // If we've not yet parsed the initializer, assume it has side-effects.
  3267. return true;
  3268. }
  3269. case CXXDynamicCastExprClass: {
  3270. // A dynamic_cast expression has side-effects if it can throw.
  3271. const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
  3272. if (DCE->getTypeAsWritten()->isReferenceType() &&
  3273. DCE->getCastKind() == CK_Dynamic)
  3274. return true;
  3275. }
  3276. [[fallthrough]];
  3277. case ImplicitCastExprClass:
  3278. case CStyleCastExprClass:
  3279. case CXXStaticCastExprClass:
  3280. case CXXReinterpretCastExprClass:
  3281. case CXXConstCastExprClass:
  3282. case CXXAddrspaceCastExprClass:
  3283. case CXXFunctionalCastExprClass:
  3284. case BuiltinBitCastExprClass: {
  3285. // While volatile reads are side-effecting in both C and C++, we treat them
  3286. // as having possible (not definite) side-effects. This allows idiomatic
  3287. // code to behave without warning, such as sizeof(*v) for a volatile-
  3288. // qualified pointer.
  3289. if (!IncludePossibleEffects)
  3290. break;
  3291. const CastExpr *CE = cast<CastExpr>(this);
  3292. if (CE->getCastKind() == CK_LValueToRValue &&
  3293. CE->getSubExpr()->getType().isVolatileQualified())
  3294. return true;
  3295. break;
  3296. }
  3297. case CXXTypeidExprClass:
  3298. // typeid might throw if its subexpression is potentially-evaluated, so has
  3299. // side-effects in that case whether or not its subexpression does.
  3300. return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
  3301. case CXXConstructExprClass:
  3302. case CXXTemporaryObjectExprClass: {
  3303. const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
  3304. if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
  3305. return true;
  3306. // A trivial constructor does not add any side-effects of its own. Just look
  3307. // at its arguments.
  3308. break;
  3309. }
  3310. case CXXInheritedCtorInitExprClass: {
  3311. const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
  3312. if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
  3313. return true;
  3314. break;
  3315. }
  3316. case LambdaExprClass: {
  3317. const LambdaExpr *LE = cast<LambdaExpr>(this);
  3318. for (Expr *E : LE->capture_inits())
  3319. if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
  3320. return true;
  3321. return false;
  3322. }
  3323. case PseudoObjectExprClass: {
  3324. // Only look for side-effects in the semantic form, and look past
  3325. // OpaqueValueExpr bindings in that form.
  3326. const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
  3327. for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
  3328. E = PO->semantics_end();
  3329. I != E; ++I) {
  3330. const Expr *Subexpr = *I;
  3331. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
  3332. Subexpr = OVE->getSourceExpr();
  3333. if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
  3334. return true;
  3335. }
  3336. return false;
  3337. }
  3338. case ObjCBoxedExprClass:
  3339. case ObjCArrayLiteralClass:
  3340. case ObjCDictionaryLiteralClass:
  3341. case ObjCSelectorExprClass:
  3342. case ObjCProtocolExprClass:
  3343. case ObjCIsaExprClass:
  3344. case ObjCIndirectCopyRestoreExprClass:
  3345. case ObjCSubscriptRefExprClass:
  3346. case ObjCBridgedCastExprClass:
  3347. case ObjCMessageExprClass:
  3348. case ObjCPropertyRefExprClass:
  3349. // FIXME: Classify these cases better.
  3350. if (IncludePossibleEffects)
  3351. return true;
  3352. break;
  3353. }
  3354. // Recurse to children.
  3355. for (const Stmt *SubStmt : children())
  3356. if (SubStmt &&
  3357. cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
  3358. return true;
  3359. return false;
  3360. }
  3361. FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
  3362. if (auto Call = dyn_cast<CallExpr>(this))
  3363. return Call->getFPFeaturesInEffect(LO);
  3364. if (auto UO = dyn_cast<UnaryOperator>(this))
  3365. return UO->getFPFeaturesInEffect(LO);
  3366. if (auto BO = dyn_cast<BinaryOperator>(this))
  3367. return BO->getFPFeaturesInEffect(LO);
  3368. if (auto Cast = dyn_cast<CastExpr>(this))
  3369. return Cast->getFPFeaturesInEffect(LO);
  3370. return FPOptions::defaultWithoutTrailingStorage(LO);
  3371. }
  3372. namespace {
  3373. /// Look for a call to a non-trivial function within an expression.
  3374. class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
  3375. {
  3376. typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
  3377. bool NonTrivial;
  3378. public:
  3379. explicit NonTrivialCallFinder(const ASTContext &Context)
  3380. : Inherited(Context), NonTrivial(false) { }
  3381. bool hasNonTrivialCall() const { return NonTrivial; }
  3382. void VisitCallExpr(const CallExpr *E) {
  3383. if (const CXXMethodDecl *Method
  3384. = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
  3385. if (Method->isTrivial()) {
  3386. // Recurse to children of the call.
  3387. Inherited::VisitStmt(E);
  3388. return;
  3389. }
  3390. }
  3391. NonTrivial = true;
  3392. }
  3393. void VisitCXXConstructExpr(const CXXConstructExpr *E) {
  3394. if (E->getConstructor()->isTrivial()) {
  3395. // Recurse to children of the call.
  3396. Inherited::VisitStmt(E);
  3397. return;
  3398. }
  3399. NonTrivial = true;
  3400. }
  3401. void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
  3402. if (E->getTemporary()->getDestructor()->isTrivial()) {
  3403. Inherited::VisitStmt(E);
  3404. return;
  3405. }
  3406. NonTrivial = true;
  3407. }
  3408. };
  3409. }
  3410. bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
  3411. NonTrivialCallFinder Finder(Ctx);
  3412. Finder.Visit(this);
  3413. return Finder.hasNonTrivialCall();
  3414. }
  3415. /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
  3416. /// pointer constant or not, as well as the specific kind of constant detected.
  3417. /// Null pointer constants can be integer constant expressions with the
  3418. /// value zero, casts of zero to void*, nullptr (C++0X), or __null
  3419. /// (a GNU extension).
  3420. Expr::NullPointerConstantKind
  3421. Expr::isNullPointerConstant(ASTContext &Ctx,
  3422. NullPointerConstantValueDependence NPC) const {
  3423. if (isValueDependent() &&
  3424. (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
  3425. // Error-dependent expr should never be a null pointer.
  3426. if (containsErrors())
  3427. return NPCK_NotNull;
  3428. switch (NPC) {
  3429. case NPC_NeverValueDependent:
  3430. llvm_unreachable("Unexpected value dependent expression!");
  3431. case NPC_ValueDependentIsNull:
  3432. if (isTypeDependent() || getType()->isIntegralType(Ctx))
  3433. return NPCK_ZeroExpression;
  3434. else
  3435. return NPCK_NotNull;
  3436. case NPC_ValueDependentIsNotNull:
  3437. return NPCK_NotNull;
  3438. }
  3439. }
  3440. // Strip off a cast to void*, if it exists. Except in C++.
  3441. if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
  3442. if (!Ctx.getLangOpts().CPlusPlus) {
  3443. // Check that it is a cast to void*.
  3444. if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
  3445. QualType Pointee = PT->getPointeeType();
  3446. Qualifiers Qs = Pointee.getQualifiers();
  3447. // Only (void*)0 or equivalent are treated as nullptr. If pointee type
  3448. // has non-default address space it is not treated as nullptr.
  3449. // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
  3450. // since it cannot be assigned to a pointer to constant address space.
  3451. if (Ctx.getLangOpts().OpenCL &&
  3452. Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
  3453. Qs.removeAddressSpace();
  3454. if (Pointee->isVoidType() && Qs.empty() && // to void*
  3455. CE->getSubExpr()->getType()->isIntegerType()) // from int
  3456. return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
  3457. }
  3458. }
  3459. } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
  3460. // Ignore the ImplicitCastExpr type entirely.
  3461. return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
  3462. } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
  3463. // Accept ((void*)0) as a null pointer constant, as many other
  3464. // implementations do.
  3465. return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
  3466. } else if (const GenericSelectionExpr *GE =
  3467. dyn_cast<GenericSelectionExpr>(this)) {
  3468. if (GE->isResultDependent())
  3469. return NPCK_NotNull;
  3470. return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
  3471. } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
  3472. if (CE->isConditionDependent())
  3473. return NPCK_NotNull;
  3474. return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
  3475. } else if (const CXXDefaultArgExpr *DefaultArg
  3476. = dyn_cast<CXXDefaultArgExpr>(this)) {
  3477. // See through default argument expressions.
  3478. return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
  3479. } else if (const CXXDefaultInitExpr *DefaultInit
  3480. = dyn_cast<CXXDefaultInitExpr>(this)) {
  3481. // See through default initializer expressions.
  3482. return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
  3483. } else if (isa<GNUNullExpr>(this)) {
  3484. // The GNU __null extension is always a null pointer constant.
  3485. return NPCK_GNUNull;
  3486. } else if (const MaterializeTemporaryExpr *M
  3487. = dyn_cast<MaterializeTemporaryExpr>(this)) {
  3488. return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
  3489. } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
  3490. if (const Expr *Source = OVE->getSourceExpr())
  3491. return Source->isNullPointerConstant(Ctx, NPC);
  3492. }
  3493. // If the expression has no type information, it cannot be a null pointer
  3494. // constant.
  3495. if (getType().isNull())
  3496. return NPCK_NotNull;
  3497. // C++11/C2x nullptr_t is always a null pointer constant.
  3498. if (getType()->isNullPtrType())
  3499. return NPCK_CXX11_nullptr;
  3500. if (const RecordType *UT = getType()->getAsUnionType())
  3501. if (!Ctx.getLangOpts().CPlusPlus11 &&
  3502. UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
  3503. if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
  3504. const Expr *InitExpr = CLE->getInitializer();
  3505. if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
  3506. return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
  3507. }
  3508. // This expression must be an integer type.
  3509. if (!getType()->isIntegerType() ||
  3510. (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
  3511. return NPCK_NotNull;
  3512. if (Ctx.getLangOpts().CPlusPlus11) {
  3513. // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
  3514. // value zero or a prvalue of type std::nullptr_t.
  3515. // Microsoft mode permits C++98 rules reflecting MSVC behavior.
  3516. const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
  3517. if (Lit && !Lit->getValue())
  3518. return NPCK_ZeroLiteral;
  3519. if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
  3520. return NPCK_NotNull;
  3521. } else {
  3522. // If we have an integer constant expression, we need to *evaluate* it and
  3523. // test for the value 0.
  3524. if (!isIntegerConstantExpr(Ctx))
  3525. return NPCK_NotNull;
  3526. }
  3527. if (EvaluateKnownConstInt(Ctx) != 0)
  3528. return NPCK_NotNull;
  3529. if (isa<IntegerLiteral>(this))
  3530. return NPCK_ZeroLiteral;
  3531. return NPCK_ZeroExpression;
  3532. }
  3533. /// If this expression is an l-value for an Objective C
  3534. /// property, find the underlying property reference expression.
  3535. const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
  3536. const Expr *E = this;
  3537. while (true) {
  3538. assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
  3539. "expression is not a property reference");
  3540. E = E->IgnoreParenCasts();
  3541. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3542. if (BO->getOpcode() == BO_Comma) {
  3543. E = BO->getRHS();
  3544. continue;
  3545. }
  3546. }
  3547. break;
  3548. }
  3549. return cast<ObjCPropertyRefExpr>(E);
  3550. }
  3551. bool Expr::isObjCSelfExpr() const {
  3552. const Expr *E = IgnoreParenImpCasts();
  3553. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  3554. if (!DRE)
  3555. return false;
  3556. const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
  3557. if (!Param)
  3558. return false;
  3559. const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
  3560. if (!M)
  3561. return false;
  3562. return M->getSelfDecl() == Param;
  3563. }
  3564. FieldDecl *Expr::getSourceBitField() {
  3565. Expr *E = this->IgnoreParens();
  3566. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3567. if (ICE->getCastKind() == CK_LValueToRValue ||
  3568. (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
  3569. E = ICE->getSubExpr()->IgnoreParens();
  3570. else
  3571. break;
  3572. }
  3573. if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
  3574. if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
  3575. if (Field->isBitField())
  3576. return Field;
  3577. if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  3578. FieldDecl *Ivar = IvarRef->getDecl();
  3579. if (Ivar->isBitField())
  3580. return Ivar;
  3581. }
  3582. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
  3583. if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
  3584. if (Field->isBitField())
  3585. return Field;
  3586. if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
  3587. if (Expr *E = BD->getBinding())
  3588. return E->getSourceBitField();
  3589. }
  3590. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
  3591. if (BinOp->isAssignmentOp() && BinOp->getLHS())
  3592. return BinOp->getLHS()->getSourceBitField();
  3593. if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
  3594. return BinOp->getRHS()->getSourceBitField();
  3595. }
  3596. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
  3597. if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
  3598. return UnOp->getSubExpr()->getSourceBitField();
  3599. return nullptr;
  3600. }
  3601. bool Expr::refersToVectorElement() const {
  3602. // FIXME: Why do we not just look at the ObjectKind here?
  3603. const Expr *E = this->IgnoreParens();
  3604. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3605. if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
  3606. E = ICE->getSubExpr()->IgnoreParens();
  3607. else
  3608. break;
  3609. }
  3610. if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
  3611. return ASE->getBase()->getType()->isVectorType();
  3612. if (isa<ExtVectorElementExpr>(E))
  3613. return true;
  3614. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3615. if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
  3616. if (auto *E = BD->getBinding())
  3617. return E->refersToVectorElement();
  3618. return false;
  3619. }
  3620. bool Expr::refersToGlobalRegisterVar() const {
  3621. const Expr *E = this->IgnoreParenImpCasts();
  3622. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  3623. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3624. if (VD->getStorageClass() == SC_Register &&
  3625. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  3626. return true;
  3627. return false;
  3628. }
  3629. bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
  3630. E1 = E1->IgnoreParens();
  3631. E2 = E2->IgnoreParens();
  3632. if (E1->getStmtClass() != E2->getStmtClass())
  3633. return false;
  3634. switch (E1->getStmtClass()) {
  3635. default:
  3636. return false;
  3637. case CXXThisExprClass:
  3638. return true;
  3639. case DeclRefExprClass: {
  3640. // DeclRefExpr without an ImplicitCastExpr can happen for integral
  3641. // template parameters.
  3642. const auto *DRE1 = cast<DeclRefExpr>(E1);
  3643. const auto *DRE2 = cast<DeclRefExpr>(E2);
  3644. return DRE1->isPRValue() && DRE2->isPRValue() &&
  3645. DRE1->getDecl() == DRE2->getDecl();
  3646. }
  3647. case ImplicitCastExprClass: {
  3648. // Peel off implicit casts.
  3649. while (true) {
  3650. const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
  3651. const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
  3652. if (!ICE1 || !ICE2)
  3653. return false;
  3654. if (ICE1->getCastKind() != ICE2->getCastKind())
  3655. return false;
  3656. E1 = ICE1->getSubExpr()->IgnoreParens();
  3657. E2 = ICE2->getSubExpr()->IgnoreParens();
  3658. // The final cast must be one of these types.
  3659. if (ICE1->getCastKind() == CK_LValueToRValue ||
  3660. ICE1->getCastKind() == CK_ArrayToPointerDecay ||
  3661. ICE1->getCastKind() == CK_FunctionToPointerDecay) {
  3662. break;
  3663. }
  3664. }
  3665. const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
  3666. const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
  3667. if (DRE1 && DRE2)
  3668. return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
  3669. const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
  3670. const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
  3671. if (Ivar1 && Ivar2) {
  3672. return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
  3673. declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
  3674. }
  3675. const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
  3676. const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
  3677. if (Array1 && Array2) {
  3678. if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
  3679. return false;
  3680. auto Idx1 = Array1->getIdx();
  3681. auto Idx2 = Array2->getIdx();
  3682. const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
  3683. const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
  3684. if (Integer1 && Integer2) {
  3685. if (!llvm::APInt::isSameValue(Integer1->getValue(),
  3686. Integer2->getValue()))
  3687. return false;
  3688. } else {
  3689. if (!isSameComparisonOperand(Idx1, Idx2))
  3690. return false;
  3691. }
  3692. return true;
  3693. }
  3694. // Walk the MemberExpr chain.
  3695. while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
  3696. const auto *ME1 = cast<MemberExpr>(E1);
  3697. const auto *ME2 = cast<MemberExpr>(E2);
  3698. if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
  3699. return false;
  3700. if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
  3701. if (D->isStaticDataMember())
  3702. return true;
  3703. E1 = ME1->getBase()->IgnoreParenImpCasts();
  3704. E2 = ME2->getBase()->IgnoreParenImpCasts();
  3705. }
  3706. if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
  3707. return true;
  3708. // A static member variable can end the MemberExpr chain with either
  3709. // a MemberExpr or a DeclRefExpr.
  3710. auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
  3711. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3712. return DRE->getDecl();
  3713. if (const auto *ME = dyn_cast<MemberExpr>(E))
  3714. return ME->getMemberDecl();
  3715. return nullptr;
  3716. };
  3717. const ValueDecl *VD1 = getAnyDecl(E1);
  3718. const ValueDecl *VD2 = getAnyDecl(E2);
  3719. return declaresSameEntity(VD1, VD2);
  3720. }
  3721. }
  3722. }
  3723. /// isArrow - Return true if the base expression is a pointer to vector,
  3724. /// return false if the base expression is a vector.
  3725. bool ExtVectorElementExpr::isArrow() const {
  3726. return getBase()->getType()->isPointerType();
  3727. }
  3728. unsigned ExtVectorElementExpr::getNumElements() const {
  3729. if (const VectorType *VT = getType()->getAs<VectorType>())
  3730. return VT->getNumElements();
  3731. return 1;
  3732. }
  3733. /// containsDuplicateElements - Return true if any element access is repeated.
  3734. bool ExtVectorElementExpr::containsDuplicateElements() const {
  3735. // FIXME: Refactor this code to an accessor on the AST node which returns the
  3736. // "type" of component access, and share with code below and in Sema.
  3737. StringRef Comp = Accessor->getName();
  3738. // Halving swizzles do not contain duplicate elements.
  3739. if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
  3740. return false;
  3741. // Advance past s-char prefix on hex swizzles.
  3742. if (Comp[0] == 's' || Comp[0] == 'S')
  3743. Comp = Comp.substr(1);
  3744. for (unsigned i = 0, e = Comp.size(); i != e; ++i)
  3745. if (Comp.substr(i + 1).contains(Comp[i]))
  3746. return true;
  3747. return false;
  3748. }
  3749. /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
  3750. void ExtVectorElementExpr::getEncodedElementAccess(
  3751. SmallVectorImpl<uint32_t> &Elts) const {
  3752. StringRef Comp = Accessor->getName();
  3753. bool isNumericAccessor = false;
  3754. if (Comp[0] == 's' || Comp[0] == 'S') {
  3755. Comp = Comp.substr(1);
  3756. isNumericAccessor = true;
  3757. }
  3758. bool isHi = Comp == "hi";
  3759. bool isLo = Comp == "lo";
  3760. bool isEven = Comp == "even";
  3761. bool isOdd = Comp == "odd";
  3762. for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
  3763. uint64_t Index;
  3764. if (isHi)
  3765. Index = e + i;
  3766. else if (isLo)
  3767. Index = i;
  3768. else if (isEven)
  3769. Index = 2 * i;
  3770. else if (isOdd)
  3771. Index = 2 * i + 1;
  3772. else
  3773. Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
  3774. Elts.push_back(Index);
  3775. }
  3776. }
  3777. ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
  3778. QualType Type, SourceLocation BLoc,
  3779. SourceLocation RP)
  3780. : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
  3781. BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
  3782. SubExprs = new (C) Stmt*[args.size()];
  3783. for (unsigned i = 0; i != args.size(); i++)
  3784. SubExprs[i] = args[i];
  3785. setDependence(computeDependence(this));
  3786. }
  3787. void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
  3788. if (SubExprs) C.Deallocate(SubExprs);
  3789. this->NumExprs = Exprs.size();
  3790. SubExprs = new (C) Stmt*[NumExprs];
  3791. memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
  3792. }
  3793. GenericSelectionExpr::GenericSelectionExpr(
  3794. const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
  3795. ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
  3796. SourceLocation DefaultLoc, SourceLocation RParenLoc,
  3797. bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
  3798. : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
  3799. AssocExprs[ResultIndex]->getValueKind(),
  3800. AssocExprs[ResultIndex]->getObjectKind()),
  3801. NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
  3802. DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
  3803. assert(AssocTypes.size() == AssocExprs.size() &&
  3804. "Must have the same number of association expressions"
  3805. " and TypeSourceInfo!");
  3806. assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
  3807. GenericSelectionExprBits.GenericLoc = GenericLoc;
  3808. getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
  3809. std::copy(AssocExprs.begin(), AssocExprs.end(),
  3810. getTrailingObjects<Stmt *>() + AssocExprStartIndex);
  3811. std::copy(AssocTypes.begin(), AssocTypes.end(),
  3812. getTrailingObjects<TypeSourceInfo *>());
  3813. setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
  3814. }
  3815. GenericSelectionExpr::GenericSelectionExpr(
  3816. const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
  3817. ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
  3818. SourceLocation DefaultLoc, SourceLocation RParenLoc,
  3819. bool ContainsUnexpandedParameterPack)
  3820. : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
  3821. OK_Ordinary),
  3822. NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
  3823. DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
  3824. assert(AssocTypes.size() == AssocExprs.size() &&
  3825. "Must have the same number of association expressions"
  3826. " and TypeSourceInfo!");
  3827. GenericSelectionExprBits.GenericLoc = GenericLoc;
  3828. getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
  3829. std::copy(AssocExprs.begin(), AssocExprs.end(),
  3830. getTrailingObjects<Stmt *>() + AssocExprStartIndex);
  3831. std::copy(AssocTypes.begin(), AssocTypes.end(),
  3832. getTrailingObjects<TypeSourceInfo *>());
  3833. setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
  3834. }
  3835. GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
  3836. : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
  3837. GenericSelectionExpr *GenericSelectionExpr::Create(
  3838. const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
  3839. ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
  3840. SourceLocation DefaultLoc, SourceLocation RParenLoc,
  3841. bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
  3842. unsigned NumAssocs = AssocExprs.size();
  3843. void *Mem = Context.Allocate(
  3844. totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
  3845. alignof(GenericSelectionExpr));
  3846. return new (Mem) GenericSelectionExpr(
  3847. Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
  3848. RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
  3849. }
  3850. GenericSelectionExpr *GenericSelectionExpr::Create(
  3851. const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
  3852. ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
  3853. SourceLocation DefaultLoc, SourceLocation RParenLoc,
  3854. bool ContainsUnexpandedParameterPack) {
  3855. unsigned NumAssocs = AssocExprs.size();
  3856. void *Mem = Context.Allocate(
  3857. totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
  3858. alignof(GenericSelectionExpr));
  3859. return new (Mem) GenericSelectionExpr(
  3860. Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
  3861. RParenLoc, ContainsUnexpandedParameterPack);
  3862. }
  3863. GenericSelectionExpr *
  3864. GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
  3865. unsigned NumAssocs) {
  3866. void *Mem = Context.Allocate(
  3867. totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
  3868. alignof(GenericSelectionExpr));
  3869. return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
  3870. }
  3871. //===----------------------------------------------------------------------===//
  3872. // DesignatedInitExpr
  3873. //===----------------------------------------------------------------------===//
  3874. IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
  3875. assert(Kind == FieldDesignator && "Only valid on a field designator");
  3876. if (Field.NameOrField & 0x01)
  3877. return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01);
  3878. return getField()->getIdentifier();
  3879. }
  3880. DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
  3881. llvm::ArrayRef<Designator> Designators,
  3882. SourceLocation EqualOrColonLoc,
  3883. bool GNUSyntax,
  3884. ArrayRef<Expr *> IndexExprs, Expr *Init)
  3885. : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
  3886. Init->getObjectKind()),
  3887. EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
  3888. NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
  3889. this->Designators = new (C) Designator[NumDesignators];
  3890. // Record the initializer itself.
  3891. child_iterator Child = child_begin();
  3892. *Child++ = Init;
  3893. // Copy the designators and their subexpressions, computing
  3894. // value-dependence along the way.
  3895. unsigned IndexIdx = 0;
  3896. for (unsigned I = 0; I != NumDesignators; ++I) {
  3897. this->Designators[I] = Designators[I];
  3898. if (this->Designators[I].isArrayDesignator()) {
  3899. // Copy the index expressions into permanent storage.
  3900. *Child++ = IndexExprs[IndexIdx++];
  3901. } else if (this->Designators[I].isArrayRangeDesignator()) {
  3902. // Copy the start/end expressions into permanent storage.
  3903. *Child++ = IndexExprs[IndexIdx++];
  3904. *Child++ = IndexExprs[IndexIdx++];
  3905. }
  3906. }
  3907. assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
  3908. setDependence(computeDependence(this));
  3909. }
  3910. DesignatedInitExpr *
  3911. DesignatedInitExpr::Create(const ASTContext &C,
  3912. llvm::ArrayRef<Designator> Designators,
  3913. ArrayRef<Expr*> IndexExprs,
  3914. SourceLocation ColonOrEqualLoc,
  3915. bool UsesColonSyntax, Expr *Init) {
  3916. void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
  3917. alignof(DesignatedInitExpr));
  3918. return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
  3919. ColonOrEqualLoc, UsesColonSyntax,
  3920. IndexExprs, Init);
  3921. }
  3922. DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
  3923. unsigned NumIndexExprs) {
  3924. void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
  3925. alignof(DesignatedInitExpr));
  3926. return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
  3927. }
  3928. void DesignatedInitExpr::setDesignators(const ASTContext &C,
  3929. const Designator *Desigs,
  3930. unsigned NumDesigs) {
  3931. Designators = new (C) Designator[NumDesigs];
  3932. NumDesignators = NumDesigs;
  3933. for (unsigned I = 0; I != NumDesigs; ++I)
  3934. Designators[I] = Desigs[I];
  3935. }
  3936. SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
  3937. DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
  3938. if (size() == 1)
  3939. return DIE->getDesignator(0)->getSourceRange();
  3940. return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
  3941. DIE->getDesignator(size() - 1)->getEndLoc());
  3942. }
  3943. SourceLocation DesignatedInitExpr::getBeginLoc() const {
  3944. SourceLocation StartLoc;
  3945. auto *DIE = const_cast<DesignatedInitExpr *>(this);
  3946. Designator &First = *DIE->getDesignator(0);
  3947. if (First.isFieldDesignator())
  3948. StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc;
  3949. else
  3950. StartLoc = First.ArrayOrRange.LBracketLoc;
  3951. return StartLoc;
  3952. }
  3953. SourceLocation DesignatedInitExpr::getEndLoc() const {
  3954. return getInit()->getEndLoc();
  3955. }
  3956. Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
  3957. assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
  3958. return getSubExpr(D.ArrayOrRange.Index + 1);
  3959. }
  3960. Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
  3961. assert(D.Kind == Designator::ArrayRangeDesignator &&
  3962. "Requires array range designator");
  3963. return getSubExpr(D.ArrayOrRange.Index + 1);
  3964. }
  3965. Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
  3966. assert(D.Kind == Designator::ArrayRangeDesignator &&
  3967. "Requires array range designator");
  3968. return getSubExpr(D.ArrayOrRange.Index + 2);
  3969. }
  3970. /// Replaces the designator at index @p Idx with the series
  3971. /// of designators in [First, Last).
  3972. void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
  3973. const Designator *First,
  3974. const Designator *Last) {
  3975. unsigned NumNewDesignators = Last - First;
  3976. if (NumNewDesignators == 0) {
  3977. std::copy_backward(Designators + Idx + 1,
  3978. Designators + NumDesignators,
  3979. Designators + Idx);
  3980. --NumNewDesignators;
  3981. return;
  3982. }
  3983. if (NumNewDesignators == 1) {
  3984. Designators[Idx] = *First;
  3985. return;
  3986. }
  3987. Designator *NewDesignators
  3988. = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
  3989. std::copy(Designators, Designators + Idx, NewDesignators);
  3990. std::copy(First, Last, NewDesignators + Idx);
  3991. std::copy(Designators + Idx + 1, Designators + NumDesignators,
  3992. NewDesignators + Idx + NumNewDesignators);
  3993. Designators = NewDesignators;
  3994. NumDesignators = NumDesignators - 1 + NumNewDesignators;
  3995. }
  3996. DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
  3997. SourceLocation lBraceLoc,
  3998. Expr *baseExpr,
  3999. SourceLocation rBraceLoc)
  4000. : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
  4001. OK_Ordinary) {
  4002. BaseAndUpdaterExprs[0] = baseExpr;
  4003. InitListExpr *ILE =
  4004. new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);
  4005. ILE->setType(baseExpr->getType());
  4006. BaseAndUpdaterExprs[1] = ILE;
  4007. // FIXME: this is wrong, set it correctly.
  4008. setDependence(ExprDependence::None);
  4009. }
  4010. SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
  4011. return getBase()->getBeginLoc();
  4012. }
  4013. SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
  4014. return getBase()->getEndLoc();
  4015. }
  4016. ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
  4017. SourceLocation RParenLoc)
  4018. : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
  4019. LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
  4020. ParenListExprBits.NumExprs = Exprs.size();
  4021. for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
  4022. getTrailingObjects<Stmt *>()[I] = Exprs[I];
  4023. setDependence(computeDependence(this));
  4024. }
  4025. ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
  4026. : Expr(ParenListExprClass, Empty) {
  4027. ParenListExprBits.NumExprs = NumExprs;
  4028. }
  4029. ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
  4030. SourceLocation LParenLoc,
  4031. ArrayRef<Expr *> Exprs,
  4032. SourceLocation RParenLoc) {
  4033. void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
  4034. alignof(ParenListExpr));
  4035. return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
  4036. }
  4037. ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
  4038. unsigned NumExprs) {
  4039. void *Mem =
  4040. Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
  4041. return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
  4042. }
  4043. BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
  4044. Opcode opc, QualType ResTy, ExprValueKind VK,
  4045. ExprObjectKind OK, SourceLocation opLoc,
  4046. FPOptionsOverride FPFeatures)
  4047. : Expr(BinaryOperatorClass, ResTy, VK, OK) {
  4048. BinaryOperatorBits.Opc = opc;
  4049. assert(!isCompoundAssignmentOp() &&
  4050. "Use CompoundAssignOperator for compound assignments");
  4051. BinaryOperatorBits.OpLoc = opLoc;
  4052. SubExprs[LHS] = lhs;
  4053. SubExprs[RHS] = rhs;
  4054. BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4055. if (hasStoredFPFeatures())
  4056. setStoredFPFeatures(FPFeatures);
  4057. setDependence(computeDependence(this));
  4058. }
  4059. BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
  4060. Opcode opc, QualType ResTy, ExprValueKind VK,
  4061. ExprObjectKind OK, SourceLocation opLoc,
  4062. FPOptionsOverride FPFeatures, bool dead2)
  4063. : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
  4064. BinaryOperatorBits.Opc = opc;
  4065. assert(isCompoundAssignmentOp() &&
  4066. "Use CompoundAssignOperator for compound assignments");
  4067. BinaryOperatorBits.OpLoc = opLoc;
  4068. SubExprs[LHS] = lhs;
  4069. SubExprs[RHS] = rhs;
  4070. BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4071. if (hasStoredFPFeatures())
  4072. setStoredFPFeatures(FPFeatures);
  4073. setDependence(computeDependence(this));
  4074. }
  4075. BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
  4076. bool HasFPFeatures) {
  4077. unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
  4078. void *Mem =
  4079. C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
  4080. return new (Mem) BinaryOperator(EmptyShell());
  4081. }
  4082. BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
  4083. Expr *rhs, Opcode opc, QualType ResTy,
  4084. ExprValueKind VK, ExprObjectKind OK,
  4085. SourceLocation opLoc,
  4086. FPOptionsOverride FPFeatures) {
  4087. bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4088. unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
  4089. void *Mem =
  4090. C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
  4091. return new (Mem)
  4092. BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
  4093. }
  4094. CompoundAssignOperator *
  4095. CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
  4096. unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
  4097. void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
  4098. alignof(CompoundAssignOperator));
  4099. return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
  4100. }
  4101. CompoundAssignOperator *
  4102. CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
  4103. Opcode opc, QualType ResTy, ExprValueKind VK,
  4104. ExprObjectKind OK, SourceLocation opLoc,
  4105. FPOptionsOverride FPFeatures,
  4106. QualType CompLHSType, QualType CompResultType) {
  4107. bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4108. unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
  4109. void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
  4110. alignof(CompoundAssignOperator));
  4111. return new (Mem)
  4112. CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
  4113. CompLHSType, CompResultType);
  4114. }
  4115. UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
  4116. bool hasFPFeatures) {
  4117. void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
  4118. alignof(UnaryOperator));
  4119. return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
  4120. }
  4121. UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
  4122. QualType type, ExprValueKind VK, ExprObjectKind OK,
  4123. SourceLocation l, bool CanOverflow,
  4124. FPOptionsOverride FPFeatures)
  4125. : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
  4126. UnaryOperatorBits.Opc = opc;
  4127. UnaryOperatorBits.CanOverflow = CanOverflow;
  4128. UnaryOperatorBits.Loc = l;
  4129. UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4130. if (hasStoredFPFeatures())
  4131. setStoredFPFeatures(FPFeatures);
  4132. setDependence(computeDependence(this, Ctx));
  4133. }
  4134. UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
  4135. Opcode opc, QualType type,
  4136. ExprValueKind VK, ExprObjectKind OK,
  4137. SourceLocation l, bool CanOverflow,
  4138. FPOptionsOverride FPFeatures) {
  4139. bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
  4140. unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
  4141. void *Mem = C.Allocate(Size, alignof(UnaryOperator));
  4142. return new (Mem)
  4143. UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
  4144. }
  4145. const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
  4146. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
  4147. e = ewc->getSubExpr();
  4148. if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
  4149. e = m->getSubExpr();
  4150. e = cast<CXXConstructExpr>(e)->getArg(0);
  4151. while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
  4152. e = ice->getSubExpr();
  4153. return cast<OpaqueValueExpr>(e);
  4154. }
  4155. PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
  4156. EmptyShell sh,
  4157. unsigned numSemanticExprs) {
  4158. void *buffer =
  4159. Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
  4160. alignof(PseudoObjectExpr));
  4161. return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
  4162. }
  4163. PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
  4164. : Expr(PseudoObjectExprClass, shell) {
  4165. PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
  4166. }
  4167. PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
  4168. ArrayRef<Expr*> semantics,
  4169. unsigned resultIndex) {
  4170. assert(syntax && "no syntactic expression!");
  4171. assert(semantics.size() && "no semantic expressions!");
  4172. QualType type;
  4173. ExprValueKind VK;
  4174. if (resultIndex == NoResult) {
  4175. type = C.VoidTy;
  4176. VK = VK_PRValue;
  4177. } else {
  4178. assert(resultIndex < semantics.size());
  4179. type = semantics[resultIndex]->getType();
  4180. VK = semantics[resultIndex]->getValueKind();
  4181. assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
  4182. }
  4183. void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
  4184. alignof(PseudoObjectExpr));
  4185. return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
  4186. resultIndex);
  4187. }
  4188. PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
  4189. Expr *syntax, ArrayRef<Expr *> semantics,
  4190. unsigned resultIndex)
  4191. : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
  4192. PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
  4193. PseudoObjectExprBits.ResultIndex = resultIndex + 1;
  4194. for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
  4195. Expr *E = (i == 0 ? syntax : semantics[i-1]);
  4196. getSubExprsBuffer()[i] = E;
  4197. if (isa<OpaqueValueExpr>(E))
  4198. assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
  4199. "opaque-value semantic expressions for pseudo-object "
  4200. "operations must have sources");
  4201. }
  4202. setDependence(computeDependence(this));
  4203. }
  4204. //===----------------------------------------------------------------------===//
  4205. // Child Iterators for iterating over subexpressions/substatements
  4206. //===----------------------------------------------------------------------===//
  4207. // UnaryExprOrTypeTraitExpr
  4208. Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
  4209. const_child_range CCR =
  4210. const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
  4211. return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
  4212. }
  4213. Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
  4214. // If this is of a type and the type is a VLA type (and not a typedef), the
  4215. // size expression of the VLA needs to be treated as an executable expression.
  4216. // Why isn't this weirdness documented better in StmtIterator?
  4217. if (isArgumentType()) {
  4218. if (const VariableArrayType *T =
  4219. dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
  4220. return const_child_range(const_child_iterator(T), const_child_iterator());
  4221. return const_child_range(const_child_iterator(), const_child_iterator());
  4222. }
  4223. return const_child_range(&Argument.Ex, &Argument.Ex + 1);
  4224. }
  4225. AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
  4226. AtomicOp op, SourceLocation RP)
  4227. : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
  4228. NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
  4229. assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
  4230. for (unsigned i = 0; i != args.size(); i++)
  4231. SubExprs[i] = args[i];
  4232. setDependence(computeDependence(this));
  4233. }
  4234. unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
  4235. switch (Op) {
  4236. case AO__c11_atomic_init:
  4237. case AO__opencl_atomic_init:
  4238. case AO__c11_atomic_load:
  4239. case AO__atomic_load_n:
  4240. return 2;
  4241. case AO__opencl_atomic_load:
  4242. case AO__hip_atomic_load:
  4243. case AO__c11_atomic_store:
  4244. case AO__c11_atomic_exchange:
  4245. case AO__atomic_load:
  4246. case AO__atomic_store:
  4247. case AO__atomic_store_n:
  4248. case AO__atomic_exchange_n:
  4249. case AO__c11_atomic_fetch_add:
  4250. case AO__c11_atomic_fetch_sub:
  4251. case AO__c11_atomic_fetch_and:
  4252. case AO__c11_atomic_fetch_or:
  4253. case AO__c11_atomic_fetch_xor:
  4254. case AO__c11_atomic_fetch_nand:
  4255. case AO__c11_atomic_fetch_max:
  4256. case AO__c11_atomic_fetch_min:
  4257. case AO__atomic_fetch_add:
  4258. case AO__atomic_fetch_sub:
  4259. case AO__atomic_fetch_and:
  4260. case AO__atomic_fetch_or:
  4261. case AO__atomic_fetch_xor:
  4262. case AO__atomic_fetch_nand:
  4263. case AO__atomic_add_fetch:
  4264. case AO__atomic_sub_fetch:
  4265. case AO__atomic_and_fetch:
  4266. case AO__atomic_or_fetch:
  4267. case AO__atomic_xor_fetch:
  4268. case AO__atomic_nand_fetch:
  4269. case AO__atomic_min_fetch:
  4270. case AO__atomic_max_fetch:
  4271. case AO__atomic_fetch_min:
  4272. case AO__atomic_fetch_max:
  4273. return 3;
  4274. case AO__hip_atomic_exchange:
  4275. case AO__hip_atomic_fetch_add:
  4276. case AO__hip_atomic_fetch_and:
  4277. case AO__hip_atomic_fetch_or:
  4278. case AO__hip_atomic_fetch_xor:
  4279. case AO__hip_atomic_fetch_min:
  4280. case AO__hip_atomic_fetch_max:
  4281. case AO__opencl_atomic_store:
  4282. case AO__hip_atomic_store:
  4283. case AO__opencl_atomic_exchange:
  4284. case AO__opencl_atomic_fetch_add:
  4285. case AO__opencl_atomic_fetch_sub:
  4286. case AO__opencl_atomic_fetch_and:
  4287. case AO__opencl_atomic_fetch_or:
  4288. case AO__opencl_atomic_fetch_xor:
  4289. case AO__opencl_atomic_fetch_min:
  4290. case AO__opencl_atomic_fetch_max:
  4291. case AO__atomic_exchange:
  4292. return 4;
  4293. case AO__c11_atomic_compare_exchange_strong:
  4294. case AO__c11_atomic_compare_exchange_weak:
  4295. return 5;
  4296. case AO__hip_atomic_compare_exchange_strong:
  4297. case AO__opencl_atomic_compare_exchange_strong:
  4298. case AO__opencl_atomic_compare_exchange_weak:
  4299. case AO__hip_atomic_compare_exchange_weak:
  4300. case AO__atomic_compare_exchange:
  4301. case AO__atomic_compare_exchange_n:
  4302. return 6;
  4303. }
  4304. llvm_unreachable("unknown atomic op");
  4305. }
  4306. QualType AtomicExpr::getValueType() const {
  4307. auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
  4308. if (auto AT = T->getAs<AtomicType>())
  4309. return AT->getValueType();
  4310. return T;
  4311. }
  4312. QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
  4313. unsigned ArraySectionCount = 0;
  4314. while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
  4315. Base = OASE->getBase();
  4316. ++ArraySectionCount;
  4317. }
  4318. while (auto *ASE =
  4319. dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
  4320. Base = ASE->getBase();
  4321. ++ArraySectionCount;
  4322. }
  4323. Base = Base->IgnoreParenImpCasts();
  4324. auto OriginalTy = Base->getType();
  4325. if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
  4326. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  4327. OriginalTy = PVD->getOriginalType().getNonReferenceType();
  4328. for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
  4329. if (OriginalTy->isAnyPointerType())
  4330. OriginalTy = OriginalTy->getPointeeType();
  4331. else {
  4332. assert (OriginalTy->isArrayType());
  4333. OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
  4334. }
  4335. }
  4336. return OriginalTy;
  4337. }
  4338. RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
  4339. SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
  4340. : Expr(RecoveryExprClass, T.getNonReferenceType(),
  4341. T->isDependentType() ? VK_LValue : getValueKindForType(T),
  4342. OK_Ordinary),
  4343. BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
  4344. assert(!T.isNull());
  4345. assert(!llvm::is_contained(SubExprs, nullptr));
  4346. llvm::copy(SubExprs, getTrailingObjects<Expr *>());
  4347. setDependence(computeDependence(this));
  4348. }
  4349. RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
  4350. SourceLocation BeginLoc,
  4351. SourceLocation EndLoc,
  4352. ArrayRef<Expr *> SubExprs) {
  4353. void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
  4354. alignof(RecoveryExpr));
  4355. return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
  4356. }
  4357. RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
  4358. void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
  4359. alignof(RecoveryExpr));
  4360. return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
  4361. }
  4362. void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
  4363. assert(
  4364. NumDims == Dims.size() &&
  4365. "Preallocated number of dimensions is different from the provided one.");
  4366. llvm::copy(Dims, getTrailingObjects<Expr *>());
  4367. }
  4368. void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
  4369. assert(
  4370. NumDims == BR.size() &&
  4371. "Preallocated number of dimensions is different from the provided one.");
  4372. llvm::copy(BR, getTrailingObjects<SourceRange>());
  4373. }
  4374. OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
  4375. SourceLocation L, SourceLocation R,
  4376. ArrayRef<Expr *> Dims)
  4377. : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
  4378. RPLoc(R), NumDims(Dims.size()) {
  4379. setBase(Op);
  4380. setDimensions(Dims);
  4381. setDependence(computeDependence(this));
  4382. }
  4383. OMPArrayShapingExpr *
  4384. OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
  4385. SourceLocation L, SourceLocation R,
  4386. ArrayRef<Expr *> Dims,
  4387. ArrayRef<SourceRange> BracketRanges) {
  4388. assert(Dims.size() == BracketRanges.size() &&
  4389. "Different number of dimensions and brackets ranges.");
  4390. void *Mem = Context.Allocate(
  4391. totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
  4392. alignof(OMPArrayShapingExpr));
  4393. auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
  4394. E->setBracketsRanges(BracketRanges);
  4395. return E;
  4396. }
  4397. OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
  4398. unsigned NumDims) {
  4399. void *Mem = Context.Allocate(
  4400. totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
  4401. alignof(OMPArrayShapingExpr));
  4402. return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
  4403. }
  4404. void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
  4405. assert(I < NumIterators &&
  4406. "Idx is greater or equal the number of iterators definitions.");
  4407. getTrailingObjects<Decl *>()[I] = D;
  4408. }
  4409. void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
  4410. assert(I < NumIterators &&
  4411. "Idx is greater or equal the number of iterators definitions.");
  4412. getTrailingObjects<
  4413. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4414. static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
  4415. }
  4416. void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
  4417. SourceLocation ColonLoc, Expr *End,
  4418. SourceLocation SecondColonLoc,
  4419. Expr *Step) {
  4420. assert(I < NumIterators &&
  4421. "Idx is greater or equal the number of iterators definitions.");
  4422. getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
  4423. static_cast<int>(RangeExprOffset::Begin)] =
  4424. Begin;
  4425. getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
  4426. static_cast<int>(RangeExprOffset::End)] = End;
  4427. getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
  4428. static_cast<int>(RangeExprOffset::Step)] = Step;
  4429. getTrailingObjects<
  4430. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4431. static_cast<int>(RangeLocOffset::FirstColonLoc)] =
  4432. ColonLoc;
  4433. getTrailingObjects<
  4434. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4435. static_cast<int>(RangeLocOffset::SecondColonLoc)] =
  4436. SecondColonLoc;
  4437. }
  4438. Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
  4439. return getTrailingObjects<Decl *>()[I];
  4440. }
  4441. OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
  4442. IteratorRange Res;
  4443. Res.Begin =
  4444. getTrailingObjects<Expr *>()[I * static_cast<int>(
  4445. RangeExprOffset::Total) +
  4446. static_cast<int>(RangeExprOffset::Begin)];
  4447. Res.End =
  4448. getTrailingObjects<Expr *>()[I * static_cast<int>(
  4449. RangeExprOffset::Total) +
  4450. static_cast<int>(RangeExprOffset::End)];
  4451. Res.Step =
  4452. getTrailingObjects<Expr *>()[I * static_cast<int>(
  4453. RangeExprOffset::Total) +
  4454. static_cast<int>(RangeExprOffset::Step)];
  4455. return Res;
  4456. }
  4457. SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
  4458. return getTrailingObjects<
  4459. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4460. static_cast<int>(RangeLocOffset::AssignLoc)];
  4461. }
  4462. SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
  4463. return getTrailingObjects<
  4464. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4465. static_cast<int>(RangeLocOffset::FirstColonLoc)];
  4466. }
  4467. SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
  4468. return getTrailingObjects<
  4469. SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
  4470. static_cast<int>(RangeLocOffset::SecondColonLoc)];
  4471. }
  4472. void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
  4473. getTrailingObjects<OMPIteratorHelperData>()[I] = D;
  4474. }
  4475. OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
  4476. return getTrailingObjects<OMPIteratorHelperData>()[I];
  4477. }
  4478. const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
  4479. return getTrailingObjects<OMPIteratorHelperData>()[I];
  4480. }
  4481. OMPIteratorExpr::OMPIteratorExpr(
  4482. QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
  4483. SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
  4484. ArrayRef<OMPIteratorHelperData> Helpers)
  4485. : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
  4486. IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
  4487. NumIterators(Data.size()) {
  4488. for (unsigned I = 0, E = Data.size(); I < E; ++I) {
  4489. const IteratorDefinition &D = Data[I];
  4490. setIteratorDeclaration(I, D.IteratorDecl);
  4491. setAssignmentLoc(I, D.AssignmentLoc);
  4492. setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
  4493. D.SecondColonLoc, D.Range.Step);
  4494. setHelper(I, Helpers[I]);
  4495. }
  4496. setDependence(computeDependence(this));
  4497. }
  4498. OMPIteratorExpr *
  4499. OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
  4500. SourceLocation IteratorKwLoc, SourceLocation L,
  4501. SourceLocation R,
  4502. ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
  4503. ArrayRef<OMPIteratorHelperData> Helpers) {
  4504. assert(Data.size() == Helpers.size() &&
  4505. "Data and helpers must have the same size.");
  4506. void *Mem = Context.Allocate(
  4507. totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
  4508. Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
  4509. Data.size() * static_cast<int>(RangeLocOffset::Total),
  4510. Helpers.size()),
  4511. alignof(OMPIteratorExpr));
  4512. return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
  4513. }
  4514. OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
  4515. unsigned NumIterators) {
  4516. void *Mem = Context.Allocate(
  4517. totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
  4518. NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
  4519. NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
  4520. alignof(OMPIteratorExpr));
  4521. return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
  4522. }