Expr.cpp 178 KB

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