Type.cpp 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155
  1. //===- Type.cpp - Type representation and manipulation --------------------===//
  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 type-related functionality.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/Type.h"
  13. #include "Linkage.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclBase.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/NestedNameSpecifier.h"
  24. #include "clang/AST/NonTrivialTypeVisitor.h"
  25. #include "clang/AST/PrettyPrinter.h"
  26. #include "clang/AST/TemplateBase.h"
  27. #include "clang/AST/TemplateName.h"
  28. #include "clang/AST/TypeVisitor.h"
  29. #include "clang/Basic/AddressSpaces.h"
  30. #include "clang/Basic/ExceptionSpecificationType.h"
  31. #include "clang/Basic/IdentifierTable.h"
  32. #include "clang/Basic/LLVM.h"
  33. #include "clang/Basic/LangOptions.h"
  34. #include "clang/Basic/Linkage.h"
  35. #include "clang/Basic/Specifiers.h"
  36. #include "clang/Basic/TargetCXXABI.h"
  37. #include "clang/Basic/TargetInfo.h"
  38. #include "clang/Basic/Visibility.h"
  39. #include "llvm/ADT/APInt.h"
  40. #include "llvm/ADT/APSInt.h"
  41. #include "llvm/ADT/ArrayRef.h"
  42. #include "llvm/ADT/FoldingSet.h"
  43. #include "llvm/ADT/None.h"
  44. #include "llvm/ADT/SmallVector.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/MathExtras.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstdint>
  51. #include <cstring>
  52. #include <type_traits>
  53. using namespace clang;
  54. bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
  55. return (*this != Other) &&
  56. // CVR qualifiers superset
  57. (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
  58. // ObjC GC qualifiers superset
  59. ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
  60. (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
  61. // Address space superset.
  62. ((getAddressSpace() == Other.getAddressSpace()) ||
  63. (hasAddressSpace()&& !Other.hasAddressSpace())) &&
  64. // Lifetime qualifier superset.
  65. ((getObjCLifetime() == Other.getObjCLifetime()) ||
  66. (hasObjCLifetime() && !Other.hasObjCLifetime()));
  67. }
  68. const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
  69. const Type* ty = getTypePtr();
  70. NamedDecl *ND = nullptr;
  71. if (ty->isPointerType() || ty->isReferenceType())
  72. return ty->getPointeeType().getBaseTypeIdentifier();
  73. else if (ty->isRecordType())
  74. ND = ty->castAs<RecordType>()->getDecl();
  75. else if (ty->isEnumeralType())
  76. ND = ty->castAs<EnumType>()->getDecl();
  77. else if (ty->getTypeClass() == Type::Typedef)
  78. ND = ty->castAs<TypedefType>()->getDecl();
  79. else if (ty->isArrayType())
  80. return ty->castAsArrayTypeUnsafe()->
  81. getElementType().getBaseTypeIdentifier();
  82. if (ND)
  83. return ND->getIdentifier();
  84. return nullptr;
  85. }
  86. bool QualType::mayBeDynamicClass() const {
  87. const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
  88. return ClassDecl && ClassDecl->mayBeDynamicClass();
  89. }
  90. bool QualType::mayBeNotDynamicClass() const {
  91. const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
  92. return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
  93. }
  94. bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
  95. if (T.isConstQualified())
  96. return true;
  97. if (const ArrayType *AT = Ctx.getAsArrayType(T))
  98. return AT->getElementType().isConstant(Ctx);
  99. return T.getAddressSpace() == LangAS::opencl_constant;
  100. }
  101. // C++ [temp.dep.type]p1:
  102. // A type is dependent if it is...
  103. // - an array type constructed from any dependent type or whose
  104. // size is specified by a constant expression that is
  105. // value-dependent,
  106. ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
  107. ArraySizeModifier sm, unsigned tq, const Expr *sz)
  108. // Note, we need to check for DependentSizedArrayType explicitly here
  109. // because we use a DependentSizedArrayType with no size expression as the
  110. // type of a dependent array of unknown bound with a dependent braced
  111. // initializer:
  112. //
  113. // template<int ...N> int arr[] = {N...};
  114. : Type(tc, can,
  115. et->isDependentType() || (sz && sz->isValueDependent()) ||
  116. tc == DependentSizedArray,
  117. et->isInstantiationDependentType() ||
  118. (sz && sz->isInstantiationDependent()) ||
  119. tc == DependentSizedArray,
  120. (tc == VariableArray || et->isVariablyModifiedType()),
  121. et->containsUnexpandedParameterPack() ||
  122. (sz && sz->containsUnexpandedParameterPack())),
  123. ElementType(et) {
  124. ArrayTypeBits.IndexTypeQuals = tq;
  125. ArrayTypeBits.SizeModifier = sm;
  126. }
  127. unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
  128. QualType ElementType,
  129. const llvm::APInt &NumElements) {
  130. uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
  131. // Fast path the common cases so we can avoid the conservative computation
  132. // below, which in common cases allocates "large" APSInt values, which are
  133. // slow.
  134. // If the element size is a power of 2, we can directly compute the additional
  135. // number of addressing bits beyond those required for the element count.
  136. if (llvm::isPowerOf2_64(ElementSize)) {
  137. return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
  138. }
  139. // If both the element count and element size fit in 32-bits, we can do the
  140. // computation directly in 64-bits.
  141. if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
  142. (NumElements.getZExtValue() >> 32) == 0) {
  143. uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
  144. return 64 - llvm::countLeadingZeros(TotalSize);
  145. }
  146. // Otherwise, use APSInt to handle arbitrary sized values.
  147. llvm::APSInt SizeExtended(NumElements, true);
  148. unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
  149. SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
  150. SizeExtended.getBitWidth()) * 2);
  151. llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
  152. TotalSize *= SizeExtended;
  153. return TotalSize.getActiveBits();
  154. }
  155. unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
  156. unsigned Bits = Context.getTypeSize(Context.getSizeType());
  157. // Limit the number of bits in size_t so that maximal bit size fits 64 bit
  158. // integer (see PR8256). We can do this as currently there is no hardware
  159. // that supports full 64-bit virtual space.
  160. if (Bits > 61)
  161. Bits = 61;
  162. return Bits;
  163. }
  164. void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
  165. const ASTContext &Context, QualType ET,
  166. const llvm::APInt &ArraySize,
  167. const Expr *SizeExpr, ArraySizeModifier SizeMod,
  168. unsigned TypeQuals) {
  169. ID.AddPointer(ET.getAsOpaquePtr());
  170. ID.AddInteger(ArraySize.getZExtValue());
  171. ID.AddInteger(SizeMod);
  172. ID.AddInteger(TypeQuals);
  173. ID.AddBoolean(SizeExpr != 0);
  174. if (SizeExpr)
  175. SizeExpr->Profile(ID, Context, true);
  176. }
  177. DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
  178. QualType et, QualType can,
  179. Expr *e, ArraySizeModifier sm,
  180. unsigned tq,
  181. SourceRange brackets)
  182. : ArrayType(DependentSizedArray, et, can, sm, tq, e),
  183. Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
  184. void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
  185. const ASTContext &Context,
  186. QualType ET,
  187. ArraySizeModifier SizeMod,
  188. unsigned TypeQuals,
  189. Expr *E) {
  190. ID.AddPointer(ET.getAsOpaquePtr());
  191. ID.AddInteger(SizeMod);
  192. ID.AddInteger(TypeQuals);
  193. E->Profile(ID, Context, true);
  194. }
  195. DependentVectorType::DependentVectorType(
  196. const ASTContext &Context, QualType ElementType, QualType CanonType,
  197. Expr *SizeExpr, SourceLocation Loc, VectorType::VectorKind VecKind)
  198. : Type(DependentVector, CanonType, /*Dependent=*/true,
  199. /*InstantiationDependent=*/true,
  200. ElementType->isVariablyModifiedType(),
  201. ElementType->containsUnexpandedParameterPack() ||
  202. (SizeExpr && SizeExpr->containsUnexpandedParameterPack())),
  203. Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
  204. VectorTypeBits.VecKind = VecKind;
  205. }
  206. void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
  207. const ASTContext &Context,
  208. QualType ElementType, const Expr *SizeExpr,
  209. VectorType::VectorKind VecKind) {
  210. ID.AddPointer(ElementType.getAsOpaquePtr());
  211. ID.AddInteger(VecKind);
  212. SizeExpr->Profile(ID, Context, true);
  213. }
  214. DependentSizedExtVectorType::DependentSizedExtVectorType(const
  215. ASTContext &Context,
  216. QualType ElementType,
  217. QualType can,
  218. Expr *SizeExpr,
  219. SourceLocation loc)
  220. : Type(DependentSizedExtVector, can, /*Dependent=*/true,
  221. /*InstantiationDependent=*/true,
  222. ElementType->isVariablyModifiedType(),
  223. (ElementType->containsUnexpandedParameterPack() ||
  224. (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
  225. Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
  226. loc(loc) {}
  227. void
  228. DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
  229. const ASTContext &Context,
  230. QualType ElementType, Expr *SizeExpr) {
  231. ID.AddPointer(ElementType.getAsOpaquePtr());
  232. SizeExpr->Profile(ID, Context, true);
  233. }
  234. DependentAddressSpaceType::DependentAddressSpaceType(
  235. const ASTContext &Context, QualType PointeeType, QualType can,
  236. Expr *AddrSpaceExpr, SourceLocation loc)
  237. : Type(DependentAddressSpace, can, /*Dependent=*/true,
  238. /*InstantiationDependent=*/true,
  239. PointeeType->isVariablyModifiedType(),
  240. (PointeeType->containsUnexpandedParameterPack() ||
  241. (AddrSpaceExpr &&
  242. AddrSpaceExpr->containsUnexpandedParameterPack()))),
  243. Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
  244. loc(loc) {}
  245. void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
  246. const ASTContext &Context,
  247. QualType PointeeType,
  248. Expr *AddrSpaceExpr) {
  249. ID.AddPointer(PointeeType.getAsOpaquePtr());
  250. AddrSpaceExpr->Profile(ID, Context, true);
  251. }
  252. VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
  253. VectorKind vecKind)
  254. : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
  255. VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
  256. QualType canonType, VectorKind vecKind)
  257. : Type(tc, canonType, vecType->isDependentType(),
  258. vecType->isInstantiationDependentType(),
  259. vecType->isVariablyModifiedType(),
  260. vecType->containsUnexpandedParameterPack()),
  261. ElementType(vecType) {
  262. VectorTypeBits.VecKind = vecKind;
  263. VectorTypeBits.NumElements = nElements;
  264. }
  265. /// getArrayElementTypeNoTypeQual - If this is an array type, return the
  266. /// element type of the array, potentially with type qualifiers missing.
  267. /// This method should never be used when type qualifiers are meaningful.
  268. const Type *Type::getArrayElementTypeNoTypeQual() const {
  269. // If this is directly an array type, return it.
  270. if (const auto *ATy = dyn_cast<ArrayType>(this))
  271. return ATy->getElementType().getTypePtr();
  272. // If the canonical form of this type isn't the right kind, reject it.
  273. if (!isa<ArrayType>(CanonicalType))
  274. return nullptr;
  275. // If this is a typedef for an array type, strip the typedef off without
  276. // losing all typedef information.
  277. return cast<ArrayType>(getUnqualifiedDesugaredType())
  278. ->getElementType().getTypePtr();
  279. }
  280. /// getDesugaredType - Return the specified type with any "sugar" removed from
  281. /// the type. This takes off typedefs, typeof's etc. If the outer level of
  282. /// the type is already concrete, it returns it unmodified. This is similar
  283. /// to getting the canonical type, but it doesn't remove *all* typedefs. For
  284. /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
  285. /// concrete.
  286. QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
  287. SplitQualType split = getSplitDesugaredType(T);
  288. return Context.getQualifiedType(split.Ty, split.Quals);
  289. }
  290. QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
  291. const ASTContext &Context) {
  292. SplitQualType split = type.split();
  293. QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
  294. return Context.getQualifiedType(desugar, split.Quals);
  295. }
  296. // Check that no type class is polymorphic. LLVM style RTTI should be used
  297. // instead. If absolutely needed an exception can still be added here by
  298. // defining the appropriate macro (but please don't do this).
  299. #define TYPE(CLASS, BASE) \
  300. static_assert(!std::is_polymorphic<CLASS##Type>::value, \
  301. #CLASS "Type should not be polymorphic!");
  302. #include "clang/AST/TypeNodes.inc"
  303. // Check that no type class has a non-trival destructor. Types are
  304. // allocated with the BumpPtrAllocator from ASTContext and therefore
  305. // their destructor is not executed.
  306. //
  307. // FIXME: ConstantArrayType is not trivially destructible because of its
  308. // APInt member. It should be replaced in favor of ASTContext allocation.
  309. #define TYPE(CLASS, BASE) \
  310. static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
  311. std::is_same<CLASS##Type, ConstantArrayType>::value, \
  312. #CLASS "Type should be trivially destructible!");
  313. #include "clang/AST/TypeNodes.inc"
  314. QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
  315. switch (getTypeClass()) {
  316. #define ABSTRACT_TYPE(Class, Parent)
  317. #define TYPE(Class, Parent) \
  318. case Type::Class: { \
  319. const auto *ty = cast<Class##Type>(this); \
  320. if (!ty->isSugared()) return QualType(ty, 0); \
  321. return ty->desugar(); \
  322. }
  323. #include "clang/AST/TypeNodes.inc"
  324. }
  325. llvm_unreachable("bad type kind!");
  326. }
  327. SplitQualType QualType::getSplitDesugaredType(QualType T) {
  328. QualifierCollector Qs;
  329. QualType Cur = T;
  330. while (true) {
  331. const Type *CurTy = Qs.strip(Cur);
  332. switch (CurTy->getTypeClass()) {
  333. #define ABSTRACT_TYPE(Class, Parent)
  334. #define TYPE(Class, Parent) \
  335. case Type::Class: { \
  336. const auto *Ty = cast<Class##Type>(CurTy); \
  337. if (!Ty->isSugared()) \
  338. return SplitQualType(Ty, Qs); \
  339. Cur = Ty->desugar(); \
  340. break; \
  341. }
  342. #include "clang/AST/TypeNodes.inc"
  343. }
  344. }
  345. }
  346. SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
  347. SplitQualType split = type.split();
  348. // All the qualifiers we've seen so far.
  349. Qualifiers quals = split.Quals;
  350. // The last type node we saw with any nodes inside it.
  351. const Type *lastTypeWithQuals = split.Ty;
  352. while (true) {
  353. QualType next;
  354. // Do a single-step desugar, aborting the loop if the type isn't
  355. // sugared.
  356. switch (split.Ty->getTypeClass()) {
  357. #define ABSTRACT_TYPE(Class, Parent)
  358. #define TYPE(Class, Parent) \
  359. case Type::Class: { \
  360. const auto *ty = cast<Class##Type>(split.Ty); \
  361. if (!ty->isSugared()) goto done; \
  362. next = ty->desugar(); \
  363. break; \
  364. }
  365. #include "clang/AST/TypeNodes.inc"
  366. }
  367. // Otherwise, split the underlying type. If that yields qualifiers,
  368. // update the information.
  369. split = next.split();
  370. if (!split.Quals.empty()) {
  371. lastTypeWithQuals = split.Ty;
  372. quals.addConsistentQualifiers(split.Quals);
  373. }
  374. }
  375. done:
  376. return SplitQualType(lastTypeWithQuals, quals);
  377. }
  378. QualType QualType::IgnoreParens(QualType T) {
  379. // FIXME: this seems inherently un-qualifiers-safe.
  380. while (const auto *PT = T->getAs<ParenType>())
  381. T = PT->getInnerType();
  382. return T;
  383. }
  384. /// This will check for a T (which should be a Type which can act as
  385. /// sugar, such as a TypedefType) by removing any existing sugar until it
  386. /// reaches a T or a non-sugared type.
  387. template<typename T> static const T *getAsSugar(const Type *Cur) {
  388. while (true) {
  389. if (const auto *Sugar = dyn_cast<T>(Cur))
  390. return Sugar;
  391. switch (Cur->getTypeClass()) {
  392. #define ABSTRACT_TYPE(Class, Parent)
  393. #define TYPE(Class, Parent) \
  394. case Type::Class: { \
  395. const auto *Ty = cast<Class##Type>(Cur); \
  396. if (!Ty->isSugared()) return 0; \
  397. Cur = Ty->desugar().getTypePtr(); \
  398. break; \
  399. }
  400. #include "clang/AST/TypeNodes.inc"
  401. }
  402. }
  403. }
  404. template <> const TypedefType *Type::getAs() const {
  405. return getAsSugar<TypedefType>(this);
  406. }
  407. template <> const TemplateSpecializationType *Type::getAs() const {
  408. return getAsSugar<TemplateSpecializationType>(this);
  409. }
  410. template <> const AttributedType *Type::getAs() const {
  411. return getAsSugar<AttributedType>(this);
  412. }
  413. /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
  414. /// sugar off the given type. This should produce an object of the
  415. /// same dynamic type as the canonical type.
  416. const Type *Type::getUnqualifiedDesugaredType() const {
  417. const Type *Cur = this;
  418. while (true) {
  419. switch (Cur->getTypeClass()) {
  420. #define ABSTRACT_TYPE(Class, Parent)
  421. #define TYPE(Class, Parent) \
  422. case Class: { \
  423. const auto *Ty = cast<Class##Type>(Cur); \
  424. if (!Ty->isSugared()) return Cur; \
  425. Cur = Ty->desugar().getTypePtr(); \
  426. break; \
  427. }
  428. #include "clang/AST/TypeNodes.inc"
  429. }
  430. }
  431. }
  432. bool Type::isClassType() const {
  433. if (const auto *RT = getAs<RecordType>())
  434. return RT->getDecl()->isClass();
  435. return false;
  436. }
  437. bool Type::isStructureType() const {
  438. if (const auto *RT = getAs<RecordType>())
  439. return RT->getDecl()->isStruct();
  440. return false;
  441. }
  442. bool Type::isObjCBoxableRecordType() const {
  443. if (const auto *RT = getAs<RecordType>())
  444. return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
  445. return false;
  446. }
  447. bool Type::isInterfaceType() const {
  448. if (const auto *RT = getAs<RecordType>())
  449. return RT->getDecl()->isInterface();
  450. return false;
  451. }
  452. bool Type::isStructureOrClassType() const {
  453. if (const auto *RT = getAs<RecordType>()) {
  454. RecordDecl *RD = RT->getDecl();
  455. return RD->isStruct() || RD->isClass() || RD->isInterface();
  456. }
  457. return false;
  458. }
  459. bool Type::isVoidPointerType() const {
  460. if (const auto *PT = getAs<PointerType>())
  461. return PT->getPointeeType()->isVoidType();
  462. return false;
  463. }
  464. bool Type::isUnionType() const {
  465. if (const auto *RT = getAs<RecordType>())
  466. return RT->getDecl()->isUnion();
  467. return false;
  468. }
  469. bool Type::isComplexType() const {
  470. if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
  471. return CT->getElementType()->isFloatingType();
  472. return false;
  473. }
  474. bool Type::isComplexIntegerType() const {
  475. // Check for GCC complex integer extension.
  476. return getAsComplexIntegerType();
  477. }
  478. bool Type::isScopedEnumeralType() const {
  479. if (const auto *ET = getAs<EnumType>())
  480. return ET->getDecl()->isScoped();
  481. return false;
  482. }
  483. const ComplexType *Type::getAsComplexIntegerType() const {
  484. if (const auto *Complex = getAs<ComplexType>())
  485. if (Complex->getElementType()->isIntegerType())
  486. return Complex;
  487. return nullptr;
  488. }
  489. QualType Type::getPointeeType() const {
  490. if (const auto *PT = getAs<PointerType>())
  491. return PT->getPointeeType();
  492. if (const auto *OPT = getAs<ObjCObjectPointerType>())
  493. return OPT->getPointeeType();
  494. if (const auto *BPT = getAs<BlockPointerType>())
  495. return BPT->getPointeeType();
  496. if (const auto *RT = getAs<ReferenceType>())
  497. return RT->getPointeeType();
  498. if (const auto *MPT = getAs<MemberPointerType>())
  499. return MPT->getPointeeType();
  500. if (const auto *DT = getAs<DecayedType>())
  501. return DT->getPointeeType();
  502. return {};
  503. }
  504. const RecordType *Type::getAsStructureType() const {
  505. // If this is directly a structure type, return it.
  506. if (const auto *RT = dyn_cast<RecordType>(this)) {
  507. if (RT->getDecl()->isStruct())
  508. return RT;
  509. }
  510. // If the canonical form of this type isn't the right kind, reject it.
  511. if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
  512. if (!RT->getDecl()->isStruct())
  513. return nullptr;
  514. // If this is a typedef for a structure type, strip the typedef off without
  515. // losing all typedef information.
  516. return cast<RecordType>(getUnqualifiedDesugaredType());
  517. }
  518. return nullptr;
  519. }
  520. const RecordType *Type::getAsUnionType() const {
  521. // If this is directly a union type, return it.
  522. if (const auto *RT = dyn_cast<RecordType>(this)) {
  523. if (RT->getDecl()->isUnion())
  524. return RT;
  525. }
  526. // If the canonical form of this type isn't the right kind, reject it.
  527. if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
  528. if (!RT->getDecl()->isUnion())
  529. return nullptr;
  530. // If this is a typedef for a union type, strip the typedef off without
  531. // losing all typedef information.
  532. return cast<RecordType>(getUnqualifiedDesugaredType());
  533. }
  534. return nullptr;
  535. }
  536. bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
  537. const ObjCObjectType *&bound) const {
  538. bound = nullptr;
  539. const auto *OPT = getAs<ObjCObjectPointerType>();
  540. if (!OPT)
  541. return false;
  542. // Easy case: id.
  543. if (OPT->isObjCIdType())
  544. return true;
  545. // If it's not a __kindof type, reject it now.
  546. if (!OPT->isKindOfType())
  547. return false;
  548. // If it's Class or qualified Class, it's not an object type.
  549. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
  550. return false;
  551. // Figure out the type bound for the __kindof type.
  552. bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
  553. ->getAs<ObjCObjectType>();
  554. return true;
  555. }
  556. bool Type::isObjCClassOrClassKindOfType() const {
  557. const auto *OPT = getAs<ObjCObjectPointerType>();
  558. if (!OPT)
  559. return false;
  560. // Easy case: Class.
  561. if (OPT->isObjCClassType())
  562. return true;
  563. // If it's not a __kindof type, reject it now.
  564. if (!OPT->isKindOfType())
  565. return false;
  566. // If it's Class or qualified Class, it's a class __kindof type.
  567. return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
  568. }
  569. ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D,
  570. QualType can,
  571. ArrayRef<ObjCProtocolDecl *> protocols)
  572. : Type(ObjCTypeParam, can, can->isDependentType(),
  573. can->isInstantiationDependentType(),
  574. can->isVariablyModifiedType(),
  575. /*ContainsUnexpandedParameterPack=*/false),
  576. OTPDecl(const_cast<ObjCTypeParamDecl*>(D)) {
  577. initialize(protocols);
  578. }
  579. ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
  580. ArrayRef<QualType> typeArgs,
  581. ArrayRef<ObjCProtocolDecl *> protocols,
  582. bool isKindOf)
  583. : Type(ObjCObject, Canonical, Base->isDependentType(),
  584. Base->isInstantiationDependentType(),
  585. Base->isVariablyModifiedType(),
  586. Base->containsUnexpandedParameterPack()),
  587. BaseType(Base) {
  588. ObjCObjectTypeBits.IsKindOf = isKindOf;
  589. ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
  590. assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
  591. "bitfield overflow in type argument count");
  592. if (!typeArgs.empty())
  593. memcpy(getTypeArgStorage(), typeArgs.data(),
  594. typeArgs.size() * sizeof(QualType));
  595. for (auto typeArg : typeArgs) {
  596. if (typeArg->isDependentType())
  597. setDependent();
  598. else if (typeArg->isInstantiationDependentType())
  599. setInstantiationDependent();
  600. if (typeArg->containsUnexpandedParameterPack())
  601. setContainsUnexpandedParameterPack();
  602. }
  603. // Initialize the protocol qualifiers. The protocol storage is known
  604. // after we set number of type arguments.
  605. initialize(protocols);
  606. }
  607. bool ObjCObjectType::isSpecialized() const {
  608. // If we have type arguments written here, the type is specialized.
  609. if (ObjCObjectTypeBits.NumTypeArgs > 0)
  610. return true;
  611. // Otherwise, check whether the base type is specialized.
  612. if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  613. // Terminate when we reach an interface type.
  614. if (isa<ObjCInterfaceType>(objcObject))
  615. return false;
  616. return objcObject->isSpecialized();
  617. }
  618. // Not specialized.
  619. return false;
  620. }
  621. ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
  622. // We have type arguments written on this type.
  623. if (isSpecializedAsWritten())
  624. return getTypeArgsAsWritten();
  625. // Look at the base type, which might have type arguments.
  626. if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  627. // Terminate when we reach an interface type.
  628. if (isa<ObjCInterfaceType>(objcObject))
  629. return {};
  630. return objcObject->getTypeArgs();
  631. }
  632. // No type arguments.
  633. return {};
  634. }
  635. bool ObjCObjectType::isKindOfType() const {
  636. if (isKindOfTypeAsWritten())
  637. return true;
  638. // Look at the base type, which might have type arguments.
  639. if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  640. // Terminate when we reach an interface type.
  641. if (isa<ObjCInterfaceType>(objcObject))
  642. return false;
  643. return objcObject->isKindOfType();
  644. }
  645. // Not a "__kindof" type.
  646. return false;
  647. }
  648. QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
  649. const ASTContext &ctx) const {
  650. if (!isKindOfType() && qual_empty())
  651. return QualType(this, 0);
  652. // Recursively strip __kindof.
  653. SplitQualType splitBaseType = getBaseType().split();
  654. QualType baseType(splitBaseType.Ty, 0);
  655. if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
  656. baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
  657. return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
  658. splitBaseType.Quals),
  659. getTypeArgsAsWritten(),
  660. /*protocols=*/{},
  661. /*isKindOf=*/false);
  662. }
  663. const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
  664. const ASTContext &ctx) const {
  665. if (!isKindOfType() && qual_empty())
  666. return this;
  667. QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
  668. return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
  669. }
  670. namespace {
  671. /// Visitor used to perform a simple type transformation that does not change
  672. /// the semantics of the type.
  673. template <typename Derived>
  674. struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
  675. ASTContext &Ctx;
  676. QualType recurse(QualType type) {
  677. // Split out the qualifiers from the type.
  678. SplitQualType splitType = type.split();
  679. // Visit the type itself.
  680. QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
  681. if (result.isNull())
  682. return result;
  683. // Reconstruct the transformed type by applying the local qualifiers
  684. // from the split type.
  685. return Ctx.getQualifiedType(result, splitType.Quals);
  686. }
  687. public:
  688. explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
  689. // None of the clients of this transformation can occur where
  690. // there are dependent types, so skip dependent types.
  691. #define TYPE(Class, Base)
  692. #define DEPENDENT_TYPE(Class, Base) \
  693. QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
  694. #include "clang/AST/TypeNodes.inc"
  695. #define TRIVIAL_TYPE_CLASS(Class) \
  696. QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
  697. #define SUGARED_TYPE_CLASS(Class) \
  698. QualType Visit##Class##Type(const Class##Type *T) { \
  699. if (!T->isSugared()) \
  700. return QualType(T, 0); \
  701. QualType desugaredType = recurse(T->desugar()); \
  702. if (desugaredType.isNull()) \
  703. return {}; \
  704. if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
  705. return QualType(T, 0); \
  706. return desugaredType; \
  707. }
  708. TRIVIAL_TYPE_CLASS(Builtin)
  709. QualType VisitComplexType(const ComplexType *T) {
  710. QualType elementType = recurse(T->getElementType());
  711. if (elementType.isNull())
  712. return {};
  713. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  714. return QualType(T, 0);
  715. return Ctx.getComplexType(elementType);
  716. }
  717. QualType VisitPointerType(const PointerType *T) {
  718. QualType pointeeType = recurse(T->getPointeeType());
  719. if (pointeeType.isNull())
  720. return {};
  721. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  722. return QualType(T, 0);
  723. return Ctx.getPointerType(pointeeType);
  724. }
  725. QualType VisitBlockPointerType(const BlockPointerType *T) {
  726. QualType pointeeType = recurse(T->getPointeeType());
  727. if (pointeeType.isNull())
  728. return {};
  729. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  730. return QualType(T, 0);
  731. return Ctx.getBlockPointerType(pointeeType);
  732. }
  733. QualType VisitLValueReferenceType(const LValueReferenceType *T) {
  734. QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
  735. if (pointeeType.isNull())
  736. return {};
  737. if (pointeeType.getAsOpaquePtr()
  738. == T->getPointeeTypeAsWritten().getAsOpaquePtr())
  739. return QualType(T, 0);
  740. return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
  741. }
  742. QualType VisitRValueReferenceType(const RValueReferenceType *T) {
  743. QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
  744. if (pointeeType.isNull())
  745. return {};
  746. if (pointeeType.getAsOpaquePtr()
  747. == T->getPointeeTypeAsWritten().getAsOpaquePtr())
  748. return QualType(T, 0);
  749. return Ctx.getRValueReferenceType(pointeeType);
  750. }
  751. QualType VisitMemberPointerType(const MemberPointerType *T) {
  752. QualType pointeeType = recurse(T->getPointeeType());
  753. if (pointeeType.isNull())
  754. return {};
  755. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  756. return QualType(T, 0);
  757. return Ctx.getMemberPointerType(pointeeType, T->getClass());
  758. }
  759. QualType VisitConstantArrayType(const ConstantArrayType *T) {
  760. QualType elementType = recurse(T->getElementType());
  761. if (elementType.isNull())
  762. return {};
  763. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  764. return QualType(T, 0);
  765. return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
  766. T->getSizeModifier(),
  767. T->getIndexTypeCVRQualifiers());
  768. }
  769. QualType VisitVariableArrayType(const VariableArrayType *T) {
  770. QualType elementType = recurse(T->getElementType());
  771. if (elementType.isNull())
  772. return {};
  773. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  774. return QualType(T, 0);
  775. return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
  776. T->getSizeModifier(),
  777. T->getIndexTypeCVRQualifiers(),
  778. T->getBracketsRange());
  779. }
  780. QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
  781. QualType elementType = recurse(T->getElementType());
  782. if (elementType.isNull())
  783. return {};
  784. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  785. return QualType(T, 0);
  786. return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
  787. T->getIndexTypeCVRQualifiers());
  788. }
  789. QualType VisitVectorType(const VectorType *T) {
  790. QualType elementType = recurse(T->getElementType());
  791. if (elementType.isNull())
  792. return {};
  793. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  794. return QualType(T, 0);
  795. return Ctx.getVectorType(elementType, T->getNumElements(),
  796. T->getVectorKind());
  797. }
  798. QualType VisitExtVectorType(const ExtVectorType *T) {
  799. QualType elementType = recurse(T->getElementType());
  800. if (elementType.isNull())
  801. return {};
  802. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  803. return QualType(T, 0);
  804. return Ctx.getExtVectorType(elementType, T->getNumElements());
  805. }
  806. QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  807. QualType returnType = recurse(T->getReturnType());
  808. if (returnType.isNull())
  809. return {};
  810. if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
  811. return QualType(T, 0);
  812. return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
  813. }
  814. QualType VisitFunctionProtoType(const FunctionProtoType *T) {
  815. QualType returnType = recurse(T->getReturnType());
  816. if (returnType.isNull())
  817. return {};
  818. // Transform parameter types.
  819. SmallVector<QualType, 4> paramTypes;
  820. bool paramChanged = false;
  821. for (auto paramType : T->getParamTypes()) {
  822. QualType newParamType = recurse(paramType);
  823. if (newParamType.isNull())
  824. return {};
  825. if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
  826. paramChanged = true;
  827. paramTypes.push_back(newParamType);
  828. }
  829. // Transform extended info.
  830. FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
  831. bool exceptionChanged = false;
  832. if (info.ExceptionSpec.Type == EST_Dynamic) {
  833. SmallVector<QualType, 4> exceptionTypes;
  834. for (auto exceptionType : info.ExceptionSpec.Exceptions) {
  835. QualType newExceptionType = recurse(exceptionType);
  836. if (newExceptionType.isNull())
  837. return {};
  838. if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
  839. exceptionChanged = true;
  840. exceptionTypes.push_back(newExceptionType);
  841. }
  842. if (exceptionChanged) {
  843. info.ExceptionSpec.Exceptions =
  844. llvm::makeArrayRef(exceptionTypes).copy(Ctx);
  845. }
  846. }
  847. if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
  848. !paramChanged && !exceptionChanged)
  849. return QualType(T, 0);
  850. return Ctx.getFunctionType(returnType, paramTypes, info);
  851. }
  852. QualType VisitParenType(const ParenType *T) {
  853. QualType innerType = recurse(T->getInnerType());
  854. if (innerType.isNull())
  855. return {};
  856. if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
  857. return QualType(T, 0);
  858. return Ctx.getParenType(innerType);
  859. }
  860. SUGARED_TYPE_CLASS(Typedef)
  861. SUGARED_TYPE_CLASS(ObjCTypeParam)
  862. SUGARED_TYPE_CLASS(MacroQualified)
  863. QualType VisitAdjustedType(const AdjustedType *T) {
  864. QualType originalType = recurse(T->getOriginalType());
  865. if (originalType.isNull())
  866. return {};
  867. QualType adjustedType = recurse(T->getAdjustedType());
  868. if (adjustedType.isNull())
  869. return {};
  870. if (originalType.getAsOpaquePtr()
  871. == T->getOriginalType().getAsOpaquePtr() &&
  872. adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
  873. return QualType(T, 0);
  874. return Ctx.getAdjustedType(originalType, adjustedType);
  875. }
  876. QualType VisitDecayedType(const DecayedType *T) {
  877. QualType originalType = recurse(T->getOriginalType());
  878. if (originalType.isNull())
  879. return {};
  880. if (originalType.getAsOpaquePtr()
  881. == T->getOriginalType().getAsOpaquePtr())
  882. return QualType(T, 0);
  883. return Ctx.getDecayedType(originalType);
  884. }
  885. SUGARED_TYPE_CLASS(TypeOfExpr)
  886. SUGARED_TYPE_CLASS(TypeOf)
  887. SUGARED_TYPE_CLASS(Decltype)
  888. SUGARED_TYPE_CLASS(UnaryTransform)
  889. TRIVIAL_TYPE_CLASS(Record)
  890. TRIVIAL_TYPE_CLASS(Enum)
  891. // FIXME: Non-trivial to implement, but important for C++
  892. SUGARED_TYPE_CLASS(Elaborated)
  893. QualType VisitAttributedType(const AttributedType *T) {
  894. QualType modifiedType = recurse(T->getModifiedType());
  895. if (modifiedType.isNull())
  896. return {};
  897. QualType equivalentType = recurse(T->getEquivalentType());
  898. if (equivalentType.isNull())
  899. return {};
  900. if (modifiedType.getAsOpaquePtr()
  901. == T->getModifiedType().getAsOpaquePtr() &&
  902. equivalentType.getAsOpaquePtr()
  903. == T->getEquivalentType().getAsOpaquePtr())
  904. return QualType(T, 0);
  905. return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
  906. equivalentType);
  907. }
  908. QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  909. QualType replacementType = recurse(T->getReplacementType());
  910. if (replacementType.isNull())
  911. return {};
  912. if (replacementType.getAsOpaquePtr()
  913. == T->getReplacementType().getAsOpaquePtr())
  914. return QualType(T, 0);
  915. return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
  916. replacementType);
  917. }
  918. // FIXME: Non-trivial to implement, but important for C++
  919. SUGARED_TYPE_CLASS(TemplateSpecialization)
  920. QualType VisitAutoType(const AutoType *T) {
  921. if (!T->isDeduced())
  922. return QualType(T, 0);
  923. QualType deducedType = recurse(T->getDeducedType());
  924. if (deducedType.isNull())
  925. return {};
  926. if (deducedType.getAsOpaquePtr()
  927. == T->getDeducedType().getAsOpaquePtr())
  928. return QualType(T, 0);
  929. return Ctx.getAutoType(deducedType, T->getKeyword(),
  930. T->isDependentType());
  931. }
  932. // FIXME: Non-trivial to implement, but important for C++
  933. SUGARED_TYPE_CLASS(PackExpansion)
  934. QualType VisitObjCObjectType(const ObjCObjectType *T) {
  935. QualType baseType = recurse(T->getBaseType());
  936. if (baseType.isNull())
  937. return {};
  938. // Transform type arguments.
  939. bool typeArgChanged = false;
  940. SmallVector<QualType, 4> typeArgs;
  941. for (auto typeArg : T->getTypeArgsAsWritten()) {
  942. QualType newTypeArg = recurse(typeArg);
  943. if (newTypeArg.isNull())
  944. return {};
  945. if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
  946. typeArgChanged = true;
  947. typeArgs.push_back(newTypeArg);
  948. }
  949. if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
  950. !typeArgChanged)
  951. return QualType(T, 0);
  952. return Ctx.getObjCObjectType(baseType, typeArgs,
  953. llvm::makeArrayRef(T->qual_begin(),
  954. T->getNumProtocols()),
  955. T->isKindOfTypeAsWritten());
  956. }
  957. TRIVIAL_TYPE_CLASS(ObjCInterface)
  958. QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  959. QualType pointeeType = recurse(T->getPointeeType());
  960. if (pointeeType.isNull())
  961. return {};
  962. if (pointeeType.getAsOpaquePtr()
  963. == T->getPointeeType().getAsOpaquePtr())
  964. return QualType(T, 0);
  965. return Ctx.getObjCObjectPointerType(pointeeType);
  966. }
  967. QualType VisitAtomicType(const AtomicType *T) {
  968. QualType valueType = recurse(T->getValueType());
  969. if (valueType.isNull())
  970. return {};
  971. if (valueType.getAsOpaquePtr()
  972. == T->getValueType().getAsOpaquePtr())
  973. return QualType(T, 0);
  974. return Ctx.getAtomicType(valueType);
  975. }
  976. #undef TRIVIAL_TYPE_CLASS
  977. #undef SUGARED_TYPE_CLASS
  978. };
  979. struct SubstObjCTypeArgsVisitor
  980. : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
  981. using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
  982. ArrayRef<QualType> TypeArgs;
  983. ObjCSubstitutionContext SubstContext;
  984. SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
  985. ObjCSubstitutionContext context)
  986. : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
  987. QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
  988. // Replace an Objective-C type parameter reference with the corresponding
  989. // type argument.
  990. ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
  991. // If we have type arguments, use them.
  992. if (!TypeArgs.empty()) {
  993. QualType argType = TypeArgs[typeParam->getIndex()];
  994. if (OTPTy->qual_empty())
  995. return argType;
  996. // Apply protocol lists if exists.
  997. bool hasError;
  998. SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
  999. protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end());
  1000. ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
  1001. return Ctx.applyObjCProtocolQualifiers(
  1002. argType, protocolsToApply, hasError, true/*allowOnPointerType*/);
  1003. }
  1004. switch (SubstContext) {
  1005. case ObjCSubstitutionContext::Ordinary:
  1006. case ObjCSubstitutionContext::Parameter:
  1007. case ObjCSubstitutionContext::Superclass:
  1008. // Substitute the bound.
  1009. return typeParam->getUnderlyingType();
  1010. case ObjCSubstitutionContext::Result:
  1011. case ObjCSubstitutionContext::Property: {
  1012. // Substitute the __kindof form of the underlying type.
  1013. const auto *objPtr =
  1014. typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
  1015. // __kindof types, id, and Class don't need an additional
  1016. // __kindof.
  1017. if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
  1018. return typeParam->getUnderlyingType();
  1019. // Add __kindof.
  1020. const auto *obj = objPtr->getObjectType();
  1021. QualType resultTy = Ctx.getObjCObjectType(
  1022. obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
  1023. /*isKindOf=*/true);
  1024. // Rebuild object pointer type.
  1025. return Ctx.getObjCObjectPointerType(resultTy);
  1026. }
  1027. }
  1028. llvm_unreachable("Unexpected ObjCSubstitutionContext!");
  1029. }
  1030. QualType VisitFunctionType(const FunctionType *funcType) {
  1031. // If we have a function type, update the substitution context
  1032. // appropriately.
  1033. //Substitute result type.
  1034. QualType returnType = funcType->getReturnType().substObjCTypeArgs(
  1035. Ctx, TypeArgs, ObjCSubstitutionContext::Result);
  1036. if (returnType.isNull())
  1037. return {};
  1038. // Handle non-prototyped functions, which only substitute into the result
  1039. // type.
  1040. if (isa<FunctionNoProtoType>(funcType)) {
  1041. // If the return type was unchanged, do nothing.
  1042. if (returnType.getAsOpaquePtr() ==
  1043. funcType->getReturnType().getAsOpaquePtr())
  1044. return BaseType::VisitFunctionType(funcType);
  1045. // Otherwise, build a new type.
  1046. return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
  1047. }
  1048. const auto *funcProtoType = cast<FunctionProtoType>(funcType);
  1049. // Transform parameter types.
  1050. SmallVector<QualType, 4> paramTypes;
  1051. bool paramChanged = false;
  1052. for (auto paramType : funcProtoType->getParamTypes()) {
  1053. QualType newParamType = paramType.substObjCTypeArgs(
  1054. Ctx, TypeArgs, ObjCSubstitutionContext::Parameter);
  1055. if (newParamType.isNull())
  1056. return {};
  1057. if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
  1058. paramChanged = true;
  1059. paramTypes.push_back(newParamType);
  1060. }
  1061. // Transform extended info.
  1062. FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
  1063. bool exceptionChanged = false;
  1064. if (info.ExceptionSpec.Type == EST_Dynamic) {
  1065. SmallVector<QualType, 4> exceptionTypes;
  1066. for (auto exceptionType : info.ExceptionSpec.Exceptions) {
  1067. QualType newExceptionType = exceptionType.substObjCTypeArgs(
  1068. Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
  1069. if (newExceptionType.isNull())
  1070. return {};
  1071. if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
  1072. exceptionChanged = true;
  1073. exceptionTypes.push_back(newExceptionType);
  1074. }
  1075. if (exceptionChanged) {
  1076. info.ExceptionSpec.Exceptions =
  1077. llvm::makeArrayRef(exceptionTypes).copy(Ctx);
  1078. }
  1079. }
  1080. if (returnType.getAsOpaquePtr() ==
  1081. funcProtoType->getReturnType().getAsOpaquePtr() &&
  1082. !paramChanged && !exceptionChanged)
  1083. return BaseType::VisitFunctionType(funcType);
  1084. return Ctx.getFunctionType(returnType, paramTypes, info);
  1085. }
  1086. QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
  1087. // Substitute into the type arguments of a specialized Objective-C object
  1088. // type.
  1089. if (objcObjectType->isSpecializedAsWritten()) {
  1090. SmallVector<QualType, 4> newTypeArgs;
  1091. bool anyChanged = false;
  1092. for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
  1093. QualType newTypeArg = typeArg.substObjCTypeArgs(
  1094. Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
  1095. if (newTypeArg.isNull())
  1096. return {};
  1097. if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
  1098. // If we're substituting based on an unspecialized context type,
  1099. // produce an unspecialized type.
  1100. ArrayRef<ObjCProtocolDecl *> protocols(
  1101. objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
  1102. if (TypeArgs.empty() &&
  1103. SubstContext != ObjCSubstitutionContext::Superclass) {
  1104. return Ctx.getObjCObjectType(
  1105. objcObjectType->getBaseType(), {}, protocols,
  1106. objcObjectType->isKindOfTypeAsWritten());
  1107. }
  1108. anyChanged = true;
  1109. }
  1110. newTypeArgs.push_back(newTypeArg);
  1111. }
  1112. if (anyChanged) {
  1113. ArrayRef<ObjCProtocolDecl *> protocols(
  1114. objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
  1115. return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs,
  1116. protocols,
  1117. objcObjectType->isKindOfTypeAsWritten());
  1118. }
  1119. }
  1120. return BaseType::VisitObjCObjectType(objcObjectType);
  1121. }
  1122. QualType VisitAttributedType(const AttributedType *attrType) {
  1123. QualType newType = BaseType::VisitAttributedType(attrType);
  1124. if (newType.isNull())
  1125. return {};
  1126. const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
  1127. if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
  1128. return newType;
  1129. // Find out if it's an Objective-C object or object pointer type;
  1130. QualType newEquivType = newAttrType->getEquivalentType();
  1131. const ObjCObjectPointerType *ptrType =
  1132. newEquivType->getAs<ObjCObjectPointerType>();
  1133. const ObjCObjectType *objType = ptrType
  1134. ? ptrType->getObjectType()
  1135. : newEquivType->getAs<ObjCObjectType>();
  1136. if (!objType)
  1137. return newType;
  1138. // Rebuild the "equivalent" type, which pushes __kindof down into
  1139. // the object type.
  1140. newEquivType = Ctx.getObjCObjectType(
  1141. objType->getBaseType(), objType->getTypeArgsAsWritten(),
  1142. objType->getProtocols(),
  1143. // There is no need to apply kindof on an unqualified id type.
  1144. /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
  1145. // If we started with an object pointer type, rebuild it.
  1146. if (ptrType)
  1147. newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
  1148. // Rebuild the attributed type.
  1149. return Ctx.getAttributedType(newAttrType->getAttrKind(),
  1150. newAttrType->getModifiedType(), newEquivType);
  1151. }
  1152. };
  1153. struct StripObjCKindOfTypeVisitor
  1154. : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
  1155. using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
  1156. explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
  1157. QualType VisitObjCObjectType(const ObjCObjectType *objType) {
  1158. if (!objType->isKindOfType())
  1159. return BaseType::VisitObjCObjectType(objType);
  1160. QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
  1161. return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
  1162. objType->getProtocols(),
  1163. /*isKindOf=*/false);
  1164. }
  1165. };
  1166. } // namespace
  1167. /// Substitute the given type arguments for Objective-C type
  1168. /// parameters within the given type, recursively.
  1169. QualType QualType::substObjCTypeArgs(ASTContext &ctx,
  1170. ArrayRef<QualType> typeArgs,
  1171. ObjCSubstitutionContext context) const {
  1172. SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
  1173. return visitor.recurse(*this);
  1174. }
  1175. QualType QualType::substObjCMemberType(QualType objectType,
  1176. const DeclContext *dc,
  1177. ObjCSubstitutionContext context) const {
  1178. if (auto subs = objectType->getObjCSubstitutions(dc))
  1179. return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
  1180. return *this;
  1181. }
  1182. QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
  1183. // FIXME: Because ASTContext::getAttributedType() is non-const.
  1184. auto &ctx = const_cast<ASTContext &>(constCtx);
  1185. StripObjCKindOfTypeVisitor visitor(ctx);
  1186. return visitor.recurse(*this);
  1187. }
  1188. QualType QualType::getAtomicUnqualifiedType() const {
  1189. if (const auto AT = getTypePtr()->getAs<AtomicType>())
  1190. return AT->getValueType().getUnqualifiedType();
  1191. return getUnqualifiedType();
  1192. }
  1193. Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
  1194. const DeclContext *dc) const {
  1195. // Look through method scopes.
  1196. if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
  1197. dc = method->getDeclContext();
  1198. // Find the class or category in which the type we're substituting
  1199. // was declared.
  1200. const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
  1201. const ObjCCategoryDecl *dcCategoryDecl = nullptr;
  1202. ObjCTypeParamList *dcTypeParams = nullptr;
  1203. if (dcClassDecl) {
  1204. // If the class does not have any type parameters, there's no
  1205. // substitution to do.
  1206. dcTypeParams = dcClassDecl->getTypeParamList();
  1207. if (!dcTypeParams)
  1208. return None;
  1209. } else {
  1210. // If we are in neither a class nor a category, there's no
  1211. // substitution to perform.
  1212. dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
  1213. if (!dcCategoryDecl)
  1214. return None;
  1215. // If the category does not have any type parameters, there's no
  1216. // substitution to do.
  1217. dcTypeParams = dcCategoryDecl->getTypeParamList();
  1218. if (!dcTypeParams)
  1219. return None;
  1220. dcClassDecl = dcCategoryDecl->getClassInterface();
  1221. if (!dcClassDecl)
  1222. return None;
  1223. }
  1224. assert(dcTypeParams && "No substitutions to perform");
  1225. assert(dcClassDecl && "No class context");
  1226. // Find the underlying object type.
  1227. const ObjCObjectType *objectType;
  1228. if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
  1229. objectType = objectPointerType->getObjectType();
  1230. } else if (getAs<BlockPointerType>()) {
  1231. ASTContext &ctx = dc->getParentASTContext();
  1232. objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
  1233. ->castAs<ObjCObjectType>();
  1234. } else {
  1235. objectType = getAs<ObjCObjectType>();
  1236. }
  1237. /// Extract the class from the receiver object type.
  1238. ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
  1239. : nullptr;
  1240. if (!curClassDecl) {
  1241. // If we don't have a context type (e.g., this is "id" or some
  1242. // variant thereof), substitute the bounds.
  1243. return llvm::ArrayRef<QualType>();
  1244. }
  1245. // Follow the superclass chain until we've mapped the receiver type
  1246. // to the same class as the context.
  1247. while (curClassDecl != dcClassDecl) {
  1248. // Map to the superclass type.
  1249. QualType superType = objectType->getSuperClassType();
  1250. if (superType.isNull()) {
  1251. objectType = nullptr;
  1252. break;
  1253. }
  1254. objectType = superType->castAs<ObjCObjectType>();
  1255. curClassDecl = objectType->getInterface();
  1256. }
  1257. // If we don't have a receiver type, or the receiver type does not
  1258. // have type arguments, substitute in the defaults.
  1259. if (!objectType || objectType->isUnspecialized()) {
  1260. return llvm::ArrayRef<QualType>();
  1261. }
  1262. // The receiver type has the type arguments we want.
  1263. return objectType->getTypeArgs();
  1264. }
  1265. bool Type::acceptsObjCTypeParams() const {
  1266. if (auto *IfaceT = getAsObjCInterfaceType()) {
  1267. if (auto *ID = IfaceT->getInterface()) {
  1268. if (ID->getTypeParamList())
  1269. return true;
  1270. }
  1271. }
  1272. return false;
  1273. }
  1274. void ObjCObjectType::computeSuperClassTypeSlow() const {
  1275. // Retrieve the class declaration for this type. If there isn't one
  1276. // (e.g., this is some variant of "id" or "Class"), then there is no
  1277. // superclass type.
  1278. ObjCInterfaceDecl *classDecl = getInterface();
  1279. if (!classDecl) {
  1280. CachedSuperClassType.setInt(true);
  1281. return;
  1282. }
  1283. // Extract the superclass type.
  1284. const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
  1285. if (!superClassObjTy) {
  1286. CachedSuperClassType.setInt(true);
  1287. return;
  1288. }
  1289. ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
  1290. if (!superClassDecl) {
  1291. CachedSuperClassType.setInt(true);
  1292. return;
  1293. }
  1294. // If the superclass doesn't have type parameters, then there is no
  1295. // substitution to perform.
  1296. QualType superClassType(superClassObjTy, 0);
  1297. ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
  1298. if (!superClassTypeParams) {
  1299. CachedSuperClassType.setPointerAndInt(
  1300. superClassType->castAs<ObjCObjectType>(), true);
  1301. return;
  1302. }
  1303. // If the superclass reference is unspecialized, return it.
  1304. if (superClassObjTy->isUnspecialized()) {
  1305. CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
  1306. return;
  1307. }
  1308. // If the subclass is not parameterized, there aren't any type
  1309. // parameters in the superclass reference to substitute.
  1310. ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
  1311. if (!typeParams) {
  1312. CachedSuperClassType.setPointerAndInt(
  1313. superClassType->castAs<ObjCObjectType>(), true);
  1314. return;
  1315. }
  1316. // If the subclass type isn't specialized, return the unspecialized
  1317. // superclass.
  1318. if (isUnspecialized()) {
  1319. QualType unspecializedSuper
  1320. = classDecl->getASTContext().getObjCInterfaceType(
  1321. superClassObjTy->getInterface());
  1322. CachedSuperClassType.setPointerAndInt(
  1323. unspecializedSuper->castAs<ObjCObjectType>(),
  1324. true);
  1325. return;
  1326. }
  1327. // Substitute the provided type arguments into the superclass type.
  1328. ArrayRef<QualType> typeArgs = getTypeArgs();
  1329. assert(typeArgs.size() == typeParams->size());
  1330. CachedSuperClassType.setPointerAndInt(
  1331. superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
  1332. ObjCSubstitutionContext::Superclass)
  1333. ->castAs<ObjCObjectType>(),
  1334. true);
  1335. }
  1336. const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
  1337. if (auto interfaceDecl = getObjectType()->getInterface()) {
  1338. return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
  1339. ->castAs<ObjCInterfaceType>();
  1340. }
  1341. return nullptr;
  1342. }
  1343. QualType ObjCObjectPointerType::getSuperClassType() const {
  1344. QualType superObjectType = getObjectType()->getSuperClassType();
  1345. if (superObjectType.isNull())
  1346. return superObjectType;
  1347. ASTContext &ctx = getInterfaceDecl()->getASTContext();
  1348. return ctx.getObjCObjectPointerType(superObjectType);
  1349. }
  1350. const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
  1351. // There is no sugar for ObjCObjectType's, just return the canonical
  1352. // type pointer if it is the right class. There is no typedef information to
  1353. // return and these cannot be Address-space qualified.
  1354. if (const auto *T = getAs<ObjCObjectType>())
  1355. if (T->getNumProtocols() && T->getInterface())
  1356. return T;
  1357. return nullptr;
  1358. }
  1359. bool Type::isObjCQualifiedInterfaceType() const {
  1360. return getAsObjCQualifiedInterfaceType() != nullptr;
  1361. }
  1362. const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
  1363. // There is no sugar for ObjCQualifiedIdType's, just return the canonical
  1364. // type pointer if it is the right class.
  1365. if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
  1366. if (OPT->isObjCQualifiedIdType())
  1367. return OPT;
  1368. }
  1369. return nullptr;
  1370. }
  1371. const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
  1372. // There is no sugar for ObjCQualifiedClassType's, just return the canonical
  1373. // type pointer if it is the right class.
  1374. if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
  1375. if (OPT->isObjCQualifiedClassType())
  1376. return OPT;
  1377. }
  1378. return nullptr;
  1379. }
  1380. const ObjCObjectType *Type::getAsObjCInterfaceType() const {
  1381. if (const auto *OT = getAs<ObjCObjectType>()) {
  1382. if (OT->getInterface())
  1383. return OT;
  1384. }
  1385. return nullptr;
  1386. }
  1387. const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
  1388. if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
  1389. if (OPT->getInterfaceType())
  1390. return OPT;
  1391. }
  1392. return nullptr;
  1393. }
  1394. const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
  1395. QualType PointeeType;
  1396. if (const auto *PT = getAs<PointerType>())
  1397. PointeeType = PT->getPointeeType();
  1398. else if (const auto *RT = getAs<ReferenceType>())
  1399. PointeeType = RT->getPointeeType();
  1400. else
  1401. return nullptr;
  1402. if (const auto *RT = PointeeType->getAs<RecordType>())
  1403. return dyn_cast<CXXRecordDecl>(RT->getDecl());
  1404. return nullptr;
  1405. }
  1406. CXXRecordDecl *Type::getAsCXXRecordDecl() const {
  1407. return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
  1408. }
  1409. RecordDecl *Type::getAsRecordDecl() const {
  1410. return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
  1411. }
  1412. TagDecl *Type::getAsTagDecl() const {
  1413. if (const auto *TT = getAs<TagType>())
  1414. return TT->getDecl();
  1415. if (const auto *Injected = getAs<InjectedClassNameType>())
  1416. return Injected->getDecl();
  1417. return nullptr;
  1418. }
  1419. bool Type::hasAttr(attr::Kind AK) const {
  1420. const Type *Cur = this;
  1421. while (const auto *AT = Cur->getAs<AttributedType>()) {
  1422. if (AT->getAttrKind() == AK)
  1423. return true;
  1424. Cur = AT->getEquivalentType().getTypePtr();
  1425. }
  1426. return false;
  1427. }
  1428. namespace {
  1429. class GetContainedDeducedTypeVisitor :
  1430. public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
  1431. bool Syntactic;
  1432. public:
  1433. GetContainedDeducedTypeVisitor(bool Syntactic = false)
  1434. : Syntactic(Syntactic) {}
  1435. using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
  1436. Type *Visit(QualType T) {
  1437. if (T.isNull())
  1438. return nullptr;
  1439. return Visit(T.getTypePtr());
  1440. }
  1441. // The deduced type itself.
  1442. Type *VisitDeducedType(const DeducedType *AT) {
  1443. return const_cast<DeducedType*>(AT);
  1444. }
  1445. // Only these types can contain the desired 'auto' type.
  1446. Type *VisitElaboratedType(const ElaboratedType *T) {
  1447. return Visit(T->getNamedType());
  1448. }
  1449. Type *VisitPointerType(const PointerType *T) {
  1450. return Visit(T->getPointeeType());
  1451. }
  1452. Type *VisitBlockPointerType(const BlockPointerType *T) {
  1453. return Visit(T->getPointeeType());
  1454. }
  1455. Type *VisitReferenceType(const ReferenceType *T) {
  1456. return Visit(T->getPointeeTypeAsWritten());
  1457. }
  1458. Type *VisitMemberPointerType(const MemberPointerType *T) {
  1459. return Visit(T->getPointeeType());
  1460. }
  1461. Type *VisitArrayType(const ArrayType *T) {
  1462. return Visit(T->getElementType());
  1463. }
  1464. Type *VisitDependentSizedExtVectorType(
  1465. const DependentSizedExtVectorType *T) {
  1466. return Visit(T->getElementType());
  1467. }
  1468. Type *VisitVectorType(const VectorType *T) {
  1469. return Visit(T->getElementType());
  1470. }
  1471. Type *VisitFunctionProtoType(const FunctionProtoType *T) {
  1472. if (Syntactic && T->hasTrailingReturn())
  1473. return const_cast<FunctionProtoType*>(T);
  1474. return VisitFunctionType(T);
  1475. }
  1476. Type *VisitFunctionType(const FunctionType *T) {
  1477. return Visit(T->getReturnType());
  1478. }
  1479. Type *VisitParenType(const ParenType *T) {
  1480. return Visit(T->getInnerType());
  1481. }
  1482. Type *VisitAttributedType(const AttributedType *T) {
  1483. return Visit(T->getModifiedType());
  1484. }
  1485. Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
  1486. return Visit(T->getUnderlyingType());
  1487. }
  1488. Type *VisitAdjustedType(const AdjustedType *T) {
  1489. return Visit(T->getOriginalType());
  1490. }
  1491. Type *VisitPackExpansionType(const PackExpansionType *T) {
  1492. return Visit(T->getPattern());
  1493. }
  1494. };
  1495. } // namespace
  1496. DeducedType *Type::getContainedDeducedType() const {
  1497. return cast_or_null<DeducedType>(
  1498. GetContainedDeducedTypeVisitor().Visit(this));
  1499. }
  1500. bool Type::hasAutoForTrailingReturnType() const {
  1501. return dyn_cast_or_null<FunctionType>(
  1502. GetContainedDeducedTypeVisitor(true).Visit(this));
  1503. }
  1504. bool Type::hasIntegerRepresentation() const {
  1505. if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
  1506. return VT->getElementType()->isIntegerType();
  1507. else
  1508. return isIntegerType();
  1509. }
  1510. /// Determine whether this type is an integral type.
  1511. ///
  1512. /// This routine determines whether the given type is an integral type per
  1513. /// C++ [basic.fundamental]p7. Although the C standard does not define the
  1514. /// term "integral type", it has a similar term "integer type", and in C++
  1515. /// the two terms are equivalent. However, C's "integer type" includes
  1516. /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
  1517. /// parameter is used to determine whether we should be following the C or
  1518. /// C++ rules when determining whether this type is an integral/integer type.
  1519. ///
  1520. /// For cases where C permits "an integer type" and C++ permits "an integral
  1521. /// type", use this routine.
  1522. ///
  1523. /// For cases where C permits "an integer type" and C++ permits "an integral
  1524. /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
  1525. ///
  1526. /// \param Ctx The context in which this type occurs.
  1527. ///
  1528. /// \returns true if the type is considered an integral type, false otherwise.
  1529. bool Type::isIntegralType(const ASTContext &Ctx) const {
  1530. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1531. return BT->getKind() >= BuiltinType::Bool &&
  1532. BT->getKind() <= BuiltinType::Int128;
  1533. // Complete enum types are integral in C.
  1534. if (!Ctx.getLangOpts().CPlusPlus)
  1535. if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
  1536. return ET->getDecl()->isComplete();
  1537. return false;
  1538. }
  1539. bool Type::isIntegralOrUnscopedEnumerationType() const {
  1540. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1541. return BT->getKind() >= BuiltinType::Bool &&
  1542. BT->getKind() <= BuiltinType::Int128;
  1543. // Check for a complete enum type; incomplete enum types are not properly an
  1544. // enumeration type in the sense required here.
  1545. // C++0x: However, if the underlying type of the enum is fixed, it is
  1546. // considered complete.
  1547. if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
  1548. return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
  1549. return false;
  1550. }
  1551. bool Type::isCharType() const {
  1552. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1553. return BT->getKind() == BuiltinType::Char_U ||
  1554. BT->getKind() == BuiltinType::UChar ||
  1555. BT->getKind() == BuiltinType::Char_S ||
  1556. BT->getKind() == BuiltinType::SChar;
  1557. return false;
  1558. }
  1559. bool Type::isWideCharType() const {
  1560. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1561. return BT->getKind() == BuiltinType::WChar_S ||
  1562. BT->getKind() == BuiltinType::WChar_U;
  1563. return false;
  1564. }
  1565. bool Type::isChar8Type() const {
  1566. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1567. return BT->getKind() == BuiltinType::Char8;
  1568. return false;
  1569. }
  1570. bool Type::isChar16Type() const {
  1571. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1572. return BT->getKind() == BuiltinType::Char16;
  1573. return false;
  1574. }
  1575. bool Type::isChar32Type() const {
  1576. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1577. return BT->getKind() == BuiltinType::Char32;
  1578. return false;
  1579. }
  1580. /// Determine whether this type is any of the built-in character
  1581. /// types.
  1582. bool Type::isAnyCharacterType() const {
  1583. const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
  1584. if (!BT) return false;
  1585. switch (BT->getKind()) {
  1586. default: return false;
  1587. case BuiltinType::Char_U:
  1588. case BuiltinType::UChar:
  1589. case BuiltinType::WChar_U:
  1590. case BuiltinType::Char8:
  1591. case BuiltinType::Char16:
  1592. case BuiltinType::Char32:
  1593. case BuiltinType::Char_S:
  1594. case BuiltinType::SChar:
  1595. case BuiltinType::WChar_S:
  1596. return true;
  1597. }
  1598. }
  1599. /// isSignedIntegerType - Return true if this is an integer type that is
  1600. /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
  1601. /// an enum decl which has a signed representation
  1602. bool Type::isSignedIntegerType() const {
  1603. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1604. return BT->getKind() >= BuiltinType::Char_S &&
  1605. BT->getKind() <= BuiltinType::Int128;
  1606. }
  1607. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
  1608. // Incomplete enum types are not treated as integer types.
  1609. // FIXME: In C++, enum types are never integer types.
  1610. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  1611. return ET->getDecl()->getIntegerType()->isSignedIntegerType();
  1612. }
  1613. return false;
  1614. }
  1615. bool Type::isSignedIntegerOrEnumerationType() const {
  1616. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1617. return BT->getKind() >= BuiltinType::Char_S &&
  1618. BT->getKind() <= BuiltinType::Int128;
  1619. }
  1620. if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
  1621. if (ET->getDecl()->isComplete())
  1622. return ET->getDecl()->getIntegerType()->isSignedIntegerType();
  1623. }
  1624. return false;
  1625. }
  1626. bool Type::hasSignedIntegerRepresentation() const {
  1627. if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
  1628. return VT->getElementType()->isSignedIntegerOrEnumerationType();
  1629. else
  1630. return isSignedIntegerOrEnumerationType();
  1631. }
  1632. /// isUnsignedIntegerType - Return true if this is an integer type that is
  1633. /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
  1634. /// decl which has an unsigned representation
  1635. bool Type::isUnsignedIntegerType() const {
  1636. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1637. return BT->getKind() >= BuiltinType::Bool &&
  1638. BT->getKind() <= BuiltinType::UInt128;
  1639. }
  1640. if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
  1641. // Incomplete enum types are not treated as integer types.
  1642. // FIXME: In C++, enum types are never integer types.
  1643. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  1644. return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
  1645. }
  1646. return false;
  1647. }
  1648. bool Type::isUnsignedIntegerOrEnumerationType() const {
  1649. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1650. return BT->getKind() >= BuiltinType::Bool &&
  1651. BT->getKind() <= BuiltinType::UInt128;
  1652. }
  1653. if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
  1654. if (ET->getDecl()->isComplete())
  1655. return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
  1656. }
  1657. return false;
  1658. }
  1659. bool Type::hasUnsignedIntegerRepresentation() const {
  1660. if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
  1661. return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
  1662. else
  1663. return isUnsignedIntegerOrEnumerationType();
  1664. }
  1665. bool Type::isFloatingType() const {
  1666. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1667. return BT->getKind() >= BuiltinType::Half &&
  1668. BT->getKind() <= BuiltinType::Float128;
  1669. if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
  1670. return CT->getElementType()->isFloatingType();
  1671. return false;
  1672. }
  1673. bool Type::hasFloatingRepresentation() const {
  1674. if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
  1675. return VT->getElementType()->isFloatingType();
  1676. else
  1677. return isFloatingType();
  1678. }
  1679. bool Type::isRealFloatingType() const {
  1680. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1681. return BT->isFloatingPoint();
  1682. return false;
  1683. }
  1684. bool Type::isRealType() const {
  1685. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1686. return BT->getKind() >= BuiltinType::Bool &&
  1687. BT->getKind() <= BuiltinType::Float128;
  1688. if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
  1689. return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
  1690. return false;
  1691. }
  1692. bool Type::isArithmeticType() const {
  1693. if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
  1694. return BT->getKind() >= BuiltinType::Bool &&
  1695. BT->getKind() <= BuiltinType::Float128;
  1696. if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
  1697. // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
  1698. // If a body isn't seen by the time we get here, return false.
  1699. //
  1700. // C++0x: Enumerations are not arithmetic types. For now, just return
  1701. // false for scoped enumerations since that will disable any
  1702. // unwanted implicit conversions.
  1703. return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
  1704. return isa<ComplexType>(CanonicalType);
  1705. }
  1706. Type::ScalarTypeKind Type::getScalarTypeKind() const {
  1707. assert(isScalarType());
  1708. const Type *T = CanonicalType.getTypePtr();
  1709. if (const auto *BT = dyn_cast<BuiltinType>(T)) {
  1710. if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
  1711. if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
  1712. if (BT->isInteger()) return STK_Integral;
  1713. if (BT->isFloatingPoint()) return STK_Floating;
  1714. if (BT->isFixedPointType()) return STK_FixedPoint;
  1715. llvm_unreachable("unknown scalar builtin type");
  1716. } else if (isa<PointerType>(T)) {
  1717. return STK_CPointer;
  1718. } else if (isa<BlockPointerType>(T)) {
  1719. return STK_BlockPointer;
  1720. } else if (isa<ObjCObjectPointerType>(T)) {
  1721. return STK_ObjCObjectPointer;
  1722. } else if (isa<MemberPointerType>(T)) {
  1723. return STK_MemberPointer;
  1724. } else if (isa<EnumType>(T)) {
  1725. assert(cast<EnumType>(T)->getDecl()->isComplete());
  1726. return STK_Integral;
  1727. } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
  1728. if (CT->getElementType()->isRealFloatingType())
  1729. return STK_FloatingComplex;
  1730. return STK_IntegralComplex;
  1731. }
  1732. llvm_unreachable("unknown scalar type");
  1733. }
  1734. /// Determines whether the type is a C++ aggregate type or C
  1735. /// aggregate or union type.
  1736. ///
  1737. /// An aggregate type is an array or a class type (struct, union, or
  1738. /// class) that has no user-declared constructors, no private or
  1739. /// protected non-static data members, no base classes, and no virtual
  1740. /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
  1741. /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
  1742. /// includes union types.
  1743. bool Type::isAggregateType() const {
  1744. if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
  1745. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
  1746. return ClassDecl->isAggregate();
  1747. return true;
  1748. }
  1749. return isa<ArrayType>(CanonicalType);
  1750. }
  1751. /// isConstantSizeType - Return true if this is not a variable sized type,
  1752. /// according to the rules of C99 6.7.5p3. It is not legal to call this on
  1753. /// incomplete types or dependent types.
  1754. bool Type::isConstantSizeType() const {
  1755. assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
  1756. assert(!isDependentType() && "This doesn't make sense for dependent types");
  1757. // The VAT must have a size, as it is known to be complete.
  1758. return !isa<VariableArrayType>(CanonicalType);
  1759. }
  1760. /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
  1761. /// - a type that can describe objects, but which lacks information needed to
  1762. /// determine its size.
  1763. bool Type::isIncompleteType(NamedDecl **Def) const {
  1764. if (Def)
  1765. *Def = nullptr;
  1766. switch (CanonicalType->getTypeClass()) {
  1767. default: return false;
  1768. case Builtin:
  1769. // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
  1770. // be completed.
  1771. return isVoidType();
  1772. case Enum: {
  1773. EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
  1774. if (Def)
  1775. *Def = EnumD;
  1776. return !EnumD->isComplete();
  1777. }
  1778. case Record: {
  1779. // A tagged type (struct/union/enum/class) is incomplete if the decl is a
  1780. // forward declaration, but not a full definition (C99 6.2.5p22).
  1781. RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
  1782. if (Def)
  1783. *Def = Rec;
  1784. return !Rec->isCompleteDefinition();
  1785. }
  1786. case ConstantArray:
  1787. // An array is incomplete if its element type is incomplete
  1788. // (C++ [dcl.array]p1).
  1789. // We don't handle variable arrays (they're not allowed in C++) or
  1790. // dependent-sized arrays (dependent types are never treated as incomplete).
  1791. return cast<ArrayType>(CanonicalType)->getElementType()
  1792. ->isIncompleteType(Def);
  1793. case IncompleteArray:
  1794. // An array of unknown size is an incomplete type (C99 6.2.5p22).
  1795. return true;
  1796. case MemberPointer: {
  1797. // Member pointers in the MS ABI have special behavior in
  1798. // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
  1799. // to indicate which inheritance model to use.
  1800. auto *MPTy = cast<MemberPointerType>(CanonicalType);
  1801. const Type *ClassTy = MPTy->getClass();
  1802. // Member pointers with dependent class types don't get special treatment.
  1803. if (ClassTy->isDependentType())
  1804. return false;
  1805. const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
  1806. ASTContext &Context = RD->getASTContext();
  1807. // Member pointers not in the MS ABI don't get special treatment.
  1808. if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
  1809. return false;
  1810. // The inheritance attribute might only be present on the most recent
  1811. // CXXRecordDecl, use that one.
  1812. RD = RD->getMostRecentNonInjectedDecl();
  1813. // Nothing interesting to do if the inheritance attribute is already set.
  1814. if (RD->hasAttr<MSInheritanceAttr>())
  1815. return false;
  1816. return true;
  1817. }
  1818. case ObjCObject:
  1819. return cast<ObjCObjectType>(CanonicalType)->getBaseType()
  1820. ->isIncompleteType(Def);
  1821. case ObjCInterface: {
  1822. // ObjC interfaces are incomplete if they are @class, not @interface.
  1823. ObjCInterfaceDecl *Interface
  1824. = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
  1825. if (Def)
  1826. *Def = Interface;
  1827. return !Interface->hasDefinition();
  1828. }
  1829. }
  1830. }
  1831. bool QualType::isPODType(const ASTContext &Context) const {
  1832. // C++11 has a more relaxed definition of POD.
  1833. if (Context.getLangOpts().CPlusPlus11)
  1834. return isCXX11PODType(Context);
  1835. return isCXX98PODType(Context);
  1836. }
  1837. bool QualType::isCXX98PODType(const ASTContext &Context) const {
  1838. // The compiler shouldn't query this for incomplete types, but the user might.
  1839. // We return false for that case. Except for incomplete arrays of PODs, which
  1840. // are PODs according to the standard.
  1841. if (isNull())
  1842. return false;
  1843. if ((*this)->isIncompleteArrayType())
  1844. return Context.getBaseElementType(*this).isCXX98PODType(Context);
  1845. if ((*this)->isIncompleteType())
  1846. return false;
  1847. if (hasNonTrivialObjCLifetime())
  1848. return false;
  1849. QualType CanonicalType = getTypePtr()->CanonicalType;
  1850. switch (CanonicalType->getTypeClass()) {
  1851. // Everything not explicitly mentioned is not POD.
  1852. default: return false;
  1853. case Type::VariableArray:
  1854. case Type::ConstantArray:
  1855. // IncompleteArray is handled above.
  1856. return Context.getBaseElementType(*this).isCXX98PODType(Context);
  1857. case Type::ObjCObjectPointer:
  1858. case Type::BlockPointer:
  1859. case Type::Builtin:
  1860. case Type::Complex:
  1861. case Type::Pointer:
  1862. case Type::MemberPointer:
  1863. case Type::Vector:
  1864. case Type::ExtVector:
  1865. return true;
  1866. case Type::Enum:
  1867. return true;
  1868. case Type::Record:
  1869. if (const auto *ClassDecl =
  1870. dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
  1871. return ClassDecl->isPOD();
  1872. // C struct/union is POD.
  1873. return true;
  1874. }
  1875. }
  1876. bool QualType::isTrivialType(const ASTContext &Context) const {
  1877. // The compiler shouldn't query this for incomplete types, but the user might.
  1878. // We return false for that case. Except for incomplete arrays of PODs, which
  1879. // are PODs according to the standard.
  1880. if (isNull())
  1881. return false;
  1882. if ((*this)->isArrayType())
  1883. return Context.getBaseElementType(*this).isTrivialType(Context);
  1884. // Return false for incomplete types after skipping any incomplete array
  1885. // types which are expressly allowed by the standard and thus our API.
  1886. if ((*this)->isIncompleteType())
  1887. return false;
  1888. if (hasNonTrivialObjCLifetime())
  1889. return false;
  1890. QualType CanonicalType = getTypePtr()->CanonicalType;
  1891. if (CanonicalType->isDependentType())
  1892. return false;
  1893. // C++0x [basic.types]p9:
  1894. // Scalar types, trivial class types, arrays of such types, and
  1895. // cv-qualified versions of these types are collectively called trivial
  1896. // types.
  1897. // As an extension, Clang treats vector types as Scalar types.
  1898. if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
  1899. return true;
  1900. if (const auto *RT = CanonicalType->getAs<RecordType>()) {
  1901. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  1902. // C++11 [class]p6:
  1903. // A trivial class is a class that has a default constructor,
  1904. // has no non-trivial default constructors, and is trivially
  1905. // copyable.
  1906. return ClassDecl->hasDefaultConstructor() &&
  1907. !ClassDecl->hasNonTrivialDefaultConstructor() &&
  1908. ClassDecl->isTriviallyCopyable();
  1909. }
  1910. return true;
  1911. }
  1912. // No other types can match.
  1913. return false;
  1914. }
  1915. bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
  1916. if ((*this)->isArrayType())
  1917. return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
  1918. if (hasNonTrivialObjCLifetime())
  1919. return false;
  1920. // C++11 [basic.types]p9 - See Core 2094
  1921. // Scalar types, trivially copyable class types, arrays of such types, and
  1922. // cv-qualified versions of these types are collectively
  1923. // called trivially copyable types.
  1924. QualType CanonicalType = getCanonicalType();
  1925. if (CanonicalType->isDependentType())
  1926. return false;
  1927. // Return false for incomplete types after skipping any incomplete array types
  1928. // which are expressly allowed by the standard and thus our API.
  1929. if (CanonicalType->isIncompleteType())
  1930. return false;
  1931. // As an extension, Clang treats vector types as Scalar types.
  1932. if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
  1933. return true;
  1934. if (const auto *RT = CanonicalType->getAs<RecordType>()) {
  1935. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  1936. if (!ClassDecl->isTriviallyCopyable()) return false;
  1937. }
  1938. return true;
  1939. }
  1940. // No other types can match.
  1941. return false;
  1942. }
  1943. bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
  1944. return !Context.getLangOpts().ObjCAutoRefCount &&
  1945. Context.getLangOpts().ObjCWeak &&
  1946. getObjCLifetime() != Qualifiers::OCL_Weak;
  1947. }
  1948. bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
  1949. return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
  1950. }
  1951. bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
  1952. return RD->hasNonTrivialToPrimitiveDestructCUnion();
  1953. }
  1954. bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
  1955. return RD->hasNonTrivialToPrimitiveCopyCUnion();
  1956. }
  1957. QualType::PrimitiveDefaultInitializeKind
  1958. QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
  1959. if (const auto *RT =
  1960. getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1961. if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
  1962. return PDIK_Struct;
  1963. switch (getQualifiers().getObjCLifetime()) {
  1964. case Qualifiers::OCL_Strong:
  1965. return PDIK_ARCStrong;
  1966. case Qualifiers::OCL_Weak:
  1967. return PDIK_ARCWeak;
  1968. default:
  1969. return PDIK_Trivial;
  1970. }
  1971. }
  1972. QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
  1973. if (const auto *RT =
  1974. getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1975. if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
  1976. return PCK_Struct;
  1977. Qualifiers Qs = getQualifiers();
  1978. switch (Qs.getObjCLifetime()) {
  1979. case Qualifiers::OCL_Strong:
  1980. return PCK_ARCStrong;
  1981. case Qualifiers::OCL_Weak:
  1982. return PCK_ARCWeak;
  1983. default:
  1984. return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
  1985. }
  1986. }
  1987. QualType::PrimitiveCopyKind
  1988. QualType::isNonTrivialToPrimitiveDestructiveMove() const {
  1989. return isNonTrivialToPrimitiveCopy();
  1990. }
  1991. bool Type::isLiteralType(const ASTContext &Ctx) const {
  1992. if (isDependentType())
  1993. return false;
  1994. // C++1y [basic.types]p10:
  1995. // A type is a literal type if it is:
  1996. // -- cv void; or
  1997. if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
  1998. return true;
  1999. // C++11 [basic.types]p10:
  2000. // A type is a literal type if it is:
  2001. // [...]
  2002. // -- an array of literal type other than an array of runtime bound; or
  2003. if (isVariableArrayType())
  2004. return false;
  2005. const Type *BaseTy = getBaseElementTypeUnsafe();
  2006. assert(BaseTy && "NULL element type");
  2007. // Return false for incomplete types after skipping any incomplete array
  2008. // types; those are expressly allowed by the standard and thus our API.
  2009. if (BaseTy->isIncompleteType())
  2010. return false;
  2011. // C++11 [basic.types]p10:
  2012. // A type is a literal type if it is:
  2013. // -- a scalar type; or
  2014. // As an extension, Clang treats vector types and complex types as
  2015. // literal types.
  2016. if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
  2017. BaseTy->isAnyComplexType())
  2018. return true;
  2019. // -- a reference type; or
  2020. if (BaseTy->isReferenceType())
  2021. return true;
  2022. // -- a class type that has all of the following properties:
  2023. if (const auto *RT = BaseTy->getAs<RecordType>()) {
  2024. // -- a trivial destructor,
  2025. // -- every constructor call and full-expression in the
  2026. // brace-or-equal-initializers for non-static data members (if any)
  2027. // is a constant expression,
  2028. // -- it is an aggregate type or has at least one constexpr
  2029. // constructor or constructor template that is not a copy or move
  2030. // constructor, and
  2031. // -- all non-static data members and base classes of literal types
  2032. //
  2033. // We resolve DR1361 by ignoring the second bullet.
  2034. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2035. return ClassDecl->isLiteral();
  2036. return true;
  2037. }
  2038. // We treat _Atomic T as a literal type if T is a literal type.
  2039. if (const auto *AT = BaseTy->getAs<AtomicType>())
  2040. return AT->getValueType()->isLiteralType(Ctx);
  2041. // If this type hasn't been deduced yet, then conservatively assume that
  2042. // it'll work out to be a literal type.
  2043. if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
  2044. return true;
  2045. return false;
  2046. }
  2047. bool Type::isStandardLayoutType() const {
  2048. if (isDependentType())
  2049. return false;
  2050. // C++0x [basic.types]p9:
  2051. // Scalar types, standard-layout class types, arrays of such types, and
  2052. // cv-qualified versions of these types are collectively called
  2053. // standard-layout types.
  2054. const Type *BaseTy = getBaseElementTypeUnsafe();
  2055. assert(BaseTy && "NULL element type");
  2056. // Return false for incomplete types after skipping any incomplete array
  2057. // types which are expressly allowed by the standard and thus our API.
  2058. if (BaseTy->isIncompleteType())
  2059. return false;
  2060. // As an extension, Clang treats vector types as Scalar types.
  2061. if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
  2062. if (const auto *RT = BaseTy->getAs<RecordType>()) {
  2063. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2064. if (!ClassDecl->isStandardLayout())
  2065. return false;
  2066. // Default to 'true' for non-C++ class types.
  2067. // FIXME: This is a bit dubious, but plain C structs should trivially meet
  2068. // all the requirements of standard layout classes.
  2069. return true;
  2070. }
  2071. // No other types can match.
  2072. return false;
  2073. }
  2074. // This is effectively the intersection of isTrivialType and
  2075. // isStandardLayoutType. We implement it directly to avoid redundant
  2076. // conversions from a type to a CXXRecordDecl.
  2077. bool QualType::isCXX11PODType(const ASTContext &Context) const {
  2078. const Type *ty = getTypePtr();
  2079. if (ty->isDependentType())
  2080. return false;
  2081. if (hasNonTrivialObjCLifetime())
  2082. return false;
  2083. // C++11 [basic.types]p9:
  2084. // Scalar types, POD classes, arrays of such types, and cv-qualified
  2085. // versions of these types are collectively called trivial types.
  2086. const Type *BaseTy = ty->getBaseElementTypeUnsafe();
  2087. assert(BaseTy && "NULL element type");
  2088. // Return false for incomplete types after skipping any incomplete array
  2089. // types which are expressly allowed by the standard and thus our API.
  2090. if (BaseTy->isIncompleteType())
  2091. return false;
  2092. // As an extension, Clang treats vector types as Scalar types.
  2093. if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
  2094. if (const auto *RT = BaseTy->getAs<RecordType>()) {
  2095. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  2096. // C++11 [class]p10:
  2097. // A POD struct is a non-union class that is both a trivial class [...]
  2098. if (!ClassDecl->isTrivial()) return false;
  2099. // C++11 [class]p10:
  2100. // A POD struct is a non-union class that is both a trivial class and
  2101. // a standard-layout class [...]
  2102. if (!ClassDecl->isStandardLayout()) return false;
  2103. // C++11 [class]p10:
  2104. // A POD struct is a non-union class that is both a trivial class and
  2105. // a standard-layout class, and has no non-static data members of type
  2106. // non-POD struct, non-POD union (or array of such types). [...]
  2107. //
  2108. // We don't directly query the recursive aspect as the requirements for
  2109. // both standard-layout classes and trivial classes apply recursively
  2110. // already.
  2111. }
  2112. return true;
  2113. }
  2114. // No other types can match.
  2115. return false;
  2116. }
  2117. bool Type::isNothrowT() const {
  2118. if (const auto *RD = getAsCXXRecordDecl()) {
  2119. IdentifierInfo *II = RD->getIdentifier();
  2120. if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
  2121. return true;
  2122. }
  2123. return false;
  2124. }
  2125. bool Type::isAlignValT() const {
  2126. if (const auto *ET = getAs<EnumType>()) {
  2127. IdentifierInfo *II = ET->getDecl()->getIdentifier();
  2128. if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
  2129. return true;
  2130. }
  2131. return false;
  2132. }
  2133. bool Type::isStdByteType() const {
  2134. if (const auto *ET = getAs<EnumType>()) {
  2135. IdentifierInfo *II = ET->getDecl()->getIdentifier();
  2136. if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
  2137. return true;
  2138. }
  2139. return false;
  2140. }
  2141. bool Type::isPromotableIntegerType() const {
  2142. if (const auto *BT = getAs<BuiltinType>())
  2143. switch (BT->getKind()) {
  2144. case BuiltinType::Bool:
  2145. case BuiltinType::Char_S:
  2146. case BuiltinType::Char_U:
  2147. case BuiltinType::SChar:
  2148. case BuiltinType::UChar:
  2149. case BuiltinType::Short:
  2150. case BuiltinType::UShort:
  2151. case BuiltinType::WChar_S:
  2152. case BuiltinType::WChar_U:
  2153. case BuiltinType::Char8:
  2154. case BuiltinType::Char16:
  2155. case BuiltinType::Char32:
  2156. return true;
  2157. default:
  2158. return false;
  2159. }
  2160. // Enumerated types are promotable to their compatible integer types
  2161. // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
  2162. if (const auto *ET = getAs<EnumType>()){
  2163. if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
  2164. || ET->getDecl()->isScoped())
  2165. return false;
  2166. return true;
  2167. }
  2168. return false;
  2169. }
  2170. bool Type::isSpecifierType() const {
  2171. // Note that this intentionally does not use the canonical type.
  2172. switch (getTypeClass()) {
  2173. case Builtin:
  2174. case Record:
  2175. case Enum:
  2176. case Typedef:
  2177. case Complex:
  2178. case TypeOfExpr:
  2179. case TypeOf:
  2180. case TemplateTypeParm:
  2181. case SubstTemplateTypeParm:
  2182. case TemplateSpecialization:
  2183. case Elaborated:
  2184. case DependentName:
  2185. case DependentTemplateSpecialization:
  2186. case ObjCInterface:
  2187. case ObjCObject:
  2188. case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
  2189. return true;
  2190. default:
  2191. return false;
  2192. }
  2193. }
  2194. ElaboratedTypeKeyword
  2195. TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
  2196. switch (TypeSpec) {
  2197. default: return ETK_None;
  2198. case TST_typename: return ETK_Typename;
  2199. case TST_class: return ETK_Class;
  2200. case TST_struct: return ETK_Struct;
  2201. case TST_interface: return ETK_Interface;
  2202. case TST_union: return ETK_Union;
  2203. case TST_enum: return ETK_Enum;
  2204. }
  2205. }
  2206. TagTypeKind
  2207. TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
  2208. switch(TypeSpec) {
  2209. case TST_class: return TTK_Class;
  2210. case TST_struct: return TTK_Struct;
  2211. case TST_interface: return TTK_Interface;
  2212. case TST_union: return TTK_Union;
  2213. case TST_enum: return TTK_Enum;
  2214. }
  2215. llvm_unreachable("Type specifier is not a tag type kind.");
  2216. }
  2217. ElaboratedTypeKeyword
  2218. TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
  2219. switch (Kind) {
  2220. case TTK_Class: return ETK_Class;
  2221. case TTK_Struct: return ETK_Struct;
  2222. case TTK_Interface: return ETK_Interface;
  2223. case TTK_Union: return ETK_Union;
  2224. case TTK_Enum: return ETK_Enum;
  2225. }
  2226. llvm_unreachable("Unknown tag type kind.");
  2227. }
  2228. TagTypeKind
  2229. TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
  2230. switch (Keyword) {
  2231. case ETK_Class: return TTK_Class;
  2232. case ETK_Struct: return TTK_Struct;
  2233. case ETK_Interface: return TTK_Interface;
  2234. case ETK_Union: return TTK_Union;
  2235. case ETK_Enum: return TTK_Enum;
  2236. case ETK_None: // Fall through.
  2237. case ETK_Typename:
  2238. llvm_unreachable("Elaborated type keyword is not a tag type kind.");
  2239. }
  2240. llvm_unreachable("Unknown elaborated type keyword.");
  2241. }
  2242. bool
  2243. TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
  2244. switch (Keyword) {
  2245. case ETK_None:
  2246. case ETK_Typename:
  2247. return false;
  2248. case ETK_Class:
  2249. case ETK_Struct:
  2250. case ETK_Interface:
  2251. case ETK_Union:
  2252. case ETK_Enum:
  2253. return true;
  2254. }
  2255. llvm_unreachable("Unknown elaborated type keyword.");
  2256. }
  2257. StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
  2258. switch (Keyword) {
  2259. case ETK_None: return {};
  2260. case ETK_Typename: return "typename";
  2261. case ETK_Class: return "class";
  2262. case ETK_Struct: return "struct";
  2263. case ETK_Interface: return "__interface";
  2264. case ETK_Union: return "union";
  2265. case ETK_Enum: return "enum";
  2266. }
  2267. llvm_unreachable("Unknown elaborated type keyword.");
  2268. }
  2269. DependentTemplateSpecializationType::DependentTemplateSpecializationType(
  2270. ElaboratedTypeKeyword Keyword,
  2271. NestedNameSpecifier *NNS, const IdentifierInfo *Name,
  2272. ArrayRef<TemplateArgument> Args,
  2273. QualType Canon)
  2274. : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
  2275. /*VariablyModified=*/false,
  2276. NNS && NNS->containsUnexpandedParameterPack()),
  2277. NNS(NNS), Name(Name) {
  2278. DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
  2279. assert((!NNS || NNS->isDependent()) &&
  2280. "DependentTemplateSpecializatonType requires dependent qualifier");
  2281. TemplateArgument *ArgBuffer = getArgBuffer();
  2282. for (const TemplateArgument &Arg : Args) {
  2283. if (Arg.containsUnexpandedParameterPack())
  2284. setContainsUnexpandedParameterPack();
  2285. new (ArgBuffer++) TemplateArgument(Arg);
  2286. }
  2287. }
  2288. void
  2289. DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
  2290. const ASTContext &Context,
  2291. ElaboratedTypeKeyword Keyword,
  2292. NestedNameSpecifier *Qualifier,
  2293. const IdentifierInfo *Name,
  2294. ArrayRef<TemplateArgument> Args) {
  2295. ID.AddInteger(Keyword);
  2296. ID.AddPointer(Qualifier);
  2297. ID.AddPointer(Name);
  2298. for (const TemplateArgument &Arg : Args)
  2299. Arg.Profile(ID, Context);
  2300. }
  2301. bool Type::isElaboratedTypeSpecifier() const {
  2302. ElaboratedTypeKeyword Keyword;
  2303. if (const auto *Elab = dyn_cast<ElaboratedType>(this))
  2304. Keyword = Elab->getKeyword();
  2305. else if (const auto *DepName = dyn_cast<DependentNameType>(this))
  2306. Keyword = DepName->getKeyword();
  2307. else if (const auto *DepTST =
  2308. dyn_cast<DependentTemplateSpecializationType>(this))
  2309. Keyword = DepTST->getKeyword();
  2310. else
  2311. return false;
  2312. return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
  2313. }
  2314. const char *Type::getTypeClassName() const {
  2315. switch (TypeBits.TC) {
  2316. #define ABSTRACT_TYPE(Derived, Base)
  2317. #define TYPE(Derived, Base) case Derived: return #Derived;
  2318. #include "clang/AST/TypeNodes.inc"
  2319. }
  2320. llvm_unreachable("Invalid type class.");
  2321. }
  2322. StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
  2323. switch (getKind()) {
  2324. case Void:
  2325. return "void";
  2326. case Bool:
  2327. return Policy.Bool ? "bool" : "_Bool";
  2328. case Char_S:
  2329. return "char";
  2330. case Char_U:
  2331. return "char";
  2332. case SChar:
  2333. return "signed char";
  2334. case Short:
  2335. return "short";
  2336. case Int:
  2337. return "int";
  2338. case Long:
  2339. return "long";
  2340. case LongLong:
  2341. return "long long";
  2342. case Int128:
  2343. return "__int128";
  2344. case UChar:
  2345. return "unsigned char";
  2346. case UShort:
  2347. return "unsigned short";
  2348. case UInt:
  2349. return "unsigned int";
  2350. case ULong:
  2351. return "unsigned long";
  2352. case ULongLong:
  2353. return "unsigned long long";
  2354. case UInt128:
  2355. return "unsigned __int128";
  2356. case Half:
  2357. return Policy.Half ? "half" : "__fp16";
  2358. case Float:
  2359. return "float";
  2360. case Double:
  2361. return "double";
  2362. case LongDouble:
  2363. return "long double";
  2364. case ShortAccum:
  2365. return "short _Accum";
  2366. case Accum:
  2367. return "_Accum";
  2368. case LongAccum:
  2369. return "long _Accum";
  2370. case UShortAccum:
  2371. return "unsigned short _Accum";
  2372. case UAccum:
  2373. return "unsigned _Accum";
  2374. case ULongAccum:
  2375. return "unsigned long _Accum";
  2376. case BuiltinType::ShortFract:
  2377. return "short _Fract";
  2378. case BuiltinType::Fract:
  2379. return "_Fract";
  2380. case BuiltinType::LongFract:
  2381. return "long _Fract";
  2382. case BuiltinType::UShortFract:
  2383. return "unsigned short _Fract";
  2384. case BuiltinType::UFract:
  2385. return "unsigned _Fract";
  2386. case BuiltinType::ULongFract:
  2387. return "unsigned long _Fract";
  2388. case BuiltinType::SatShortAccum:
  2389. return "_Sat short _Accum";
  2390. case BuiltinType::SatAccum:
  2391. return "_Sat _Accum";
  2392. case BuiltinType::SatLongAccum:
  2393. return "_Sat long _Accum";
  2394. case BuiltinType::SatUShortAccum:
  2395. return "_Sat unsigned short _Accum";
  2396. case BuiltinType::SatUAccum:
  2397. return "_Sat unsigned _Accum";
  2398. case BuiltinType::SatULongAccum:
  2399. return "_Sat unsigned long _Accum";
  2400. case BuiltinType::SatShortFract:
  2401. return "_Sat short _Fract";
  2402. case BuiltinType::SatFract:
  2403. return "_Sat _Fract";
  2404. case BuiltinType::SatLongFract:
  2405. return "_Sat long _Fract";
  2406. case BuiltinType::SatUShortFract:
  2407. return "_Sat unsigned short _Fract";
  2408. case BuiltinType::SatUFract:
  2409. return "_Sat unsigned _Fract";
  2410. case BuiltinType::SatULongFract:
  2411. return "_Sat unsigned long _Fract";
  2412. case Float16:
  2413. return "_Float16";
  2414. case Float128:
  2415. return "__float128";
  2416. case WChar_S:
  2417. case WChar_U:
  2418. return Policy.MSWChar ? "__wchar_t" : "wchar_t";
  2419. case Char8:
  2420. return "char8_t";
  2421. case Char16:
  2422. return "char16_t";
  2423. case Char32:
  2424. return "char32_t";
  2425. case NullPtr:
  2426. return "nullptr_t";
  2427. case Overload:
  2428. return "<overloaded function type>";
  2429. case BoundMember:
  2430. return "<bound member function type>";
  2431. case PseudoObject:
  2432. return "<pseudo-object type>";
  2433. case Dependent:
  2434. return "<dependent type>";
  2435. case UnknownAny:
  2436. return "<unknown type>";
  2437. case ARCUnbridgedCast:
  2438. return "<ARC unbridged cast type>";
  2439. case BuiltinFn:
  2440. return "<builtin fn type>";
  2441. case ObjCId:
  2442. return "id";
  2443. case ObjCClass:
  2444. return "Class";
  2445. case ObjCSel:
  2446. return "SEL";
  2447. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2448. case Id: \
  2449. return "__" #Access " " #ImgType "_t";
  2450. #include "clang/Basic/OpenCLImageTypes.def"
  2451. case OCLSampler:
  2452. return "sampler_t";
  2453. case OCLEvent:
  2454. return "event_t";
  2455. case OCLClkEvent:
  2456. return "clk_event_t";
  2457. case OCLQueue:
  2458. return "queue_t";
  2459. case OCLReserveID:
  2460. return "reserve_id_t";
  2461. case OMPArraySection:
  2462. return "<OpenMP array section type>";
  2463. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  2464. case Id: \
  2465. return #ExtType;
  2466. #include "clang/Basic/OpenCLExtensionTypes.def"
  2467. #define SVE_TYPE(Name, Id, SingletonId) \
  2468. case Id: \
  2469. return Name;
  2470. #include "clang/Basic/AArch64SVEACLETypes.def"
  2471. }
  2472. llvm_unreachable("Invalid builtin type.");
  2473. }
  2474. QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
  2475. if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
  2476. return RefType->getPointeeType();
  2477. // C++0x [basic.lval]:
  2478. // Class prvalues can have cv-qualified types; non-class prvalues always
  2479. // have cv-unqualified types.
  2480. //
  2481. // See also C99 6.3.2.1p2.
  2482. if (!Context.getLangOpts().CPlusPlus ||
  2483. (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
  2484. return getUnqualifiedType();
  2485. return *this;
  2486. }
  2487. StringRef FunctionType::getNameForCallConv(CallingConv CC) {
  2488. switch (CC) {
  2489. case CC_C: return "cdecl";
  2490. case CC_X86StdCall: return "stdcall";
  2491. case CC_X86FastCall: return "fastcall";
  2492. case CC_X86ThisCall: return "thiscall";
  2493. case CC_X86Pascal: return "pascal";
  2494. case CC_X86VectorCall: return "vectorcall";
  2495. case CC_Win64: return "ms_abi";
  2496. case CC_X86_64SysV: return "sysv_abi";
  2497. case CC_X86RegCall : return "regcall";
  2498. case CC_AAPCS: return "aapcs";
  2499. case CC_AAPCS_VFP: return "aapcs-vfp";
  2500. case CC_AArch64VectorCall: return "aarch64_vector_pcs";
  2501. case CC_IntelOclBicc: return "intel_ocl_bicc";
  2502. case CC_SpirFunction: return "spir_function";
  2503. case CC_OpenCLKernel: return "opencl_kernel";
  2504. case CC_Swift: return "swiftcall";
  2505. case CC_PreserveMost: return "preserve_most";
  2506. case CC_PreserveAll: return "preserve_all";
  2507. }
  2508. llvm_unreachable("Invalid calling convention.");
  2509. }
  2510. FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
  2511. QualType canonical,
  2512. const ExtProtoInfo &epi)
  2513. : FunctionType(FunctionProto, result, canonical, result->isDependentType(),
  2514. result->isInstantiationDependentType(),
  2515. result->isVariablyModifiedType(),
  2516. result->containsUnexpandedParameterPack(), epi.ExtInfo) {
  2517. FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
  2518. FunctionTypeBits.RefQualifier = epi.RefQualifier;
  2519. FunctionTypeBits.NumParams = params.size();
  2520. assert(getNumParams() == params.size() && "NumParams overflow!");
  2521. FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
  2522. FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
  2523. FunctionTypeBits.Variadic = epi.Variadic;
  2524. FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
  2525. // Fill in the extra trailing bitfields if present.
  2526. if (hasExtraBitfields(epi.ExceptionSpec.Type)) {
  2527. auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
  2528. ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
  2529. }
  2530. // Fill in the trailing argument array.
  2531. auto *argSlot = getTrailingObjects<QualType>();
  2532. for (unsigned i = 0; i != getNumParams(); ++i) {
  2533. if (params[i]->isDependentType())
  2534. setDependent();
  2535. else if (params[i]->isInstantiationDependentType())
  2536. setInstantiationDependent();
  2537. if (params[i]->containsUnexpandedParameterPack())
  2538. setContainsUnexpandedParameterPack();
  2539. argSlot[i] = params[i];
  2540. }
  2541. // Fill in the exception type array if present.
  2542. if (getExceptionSpecType() == EST_Dynamic) {
  2543. assert(hasExtraBitfields() && "missing trailing extra bitfields!");
  2544. auto *exnSlot =
  2545. reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
  2546. unsigned I = 0;
  2547. for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
  2548. // Note that, before C++17, a dependent exception specification does
  2549. // *not* make a type dependent; it's not even part of the C++ type
  2550. // system.
  2551. if (ExceptionType->isInstantiationDependentType())
  2552. setInstantiationDependent();
  2553. if (ExceptionType->containsUnexpandedParameterPack())
  2554. setContainsUnexpandedParameterPack();
  2555. exnSlot[I++] = ExceptionType;
  2556. }
  2557. }
  2558. // Fill in the Expr * in the exception specification if present.
  2559. else if (isComputedNoexcept(getExceptionSpecType())) {
  2560. assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
  2561. assert((getExceptionSpecType() == EST_DependentNoexcept) ==
  2562. epi.ExceptionSpec.NoexceptExpr->isValueDependent());
  2563. // Store the noexcept expression and context.
  2564. *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
  2565. if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
  2566. epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
  2567. setInstantiationDependent();
  2568. if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
  2569. setContainsUnexpandedParameterPack();
  2570. }
  2571. // Fill in the FunctionDecl * in the exception specification if present.
  2572. else if (getExceptionSpecType() == EST_Uninstantiated) {
  2573. // Store the function decl from which we will resolve our
  2574. // exception specification.
  2575. auto **slot = getTrailingObjects<FunctionDecl *>();
  2576. slot[0] = epi.ExceptionSpec.SourceDecl;
  2577. slot[1] = epi.ExceptionSpec.SourceTemplate;
  2578. // This exception specification doesn't make the type dependent, because
  2579. // it's not instantiated as part of instantiating the type.
  2580. } else if (getExceptionSpecType() == EST_Unevaluated) {
  2581. // Store the function decl from which we will resolve our
  2582. // exception specification.
  2583. auto **slot = getTrailingObjects<FunctionDecl *>();
  2584. slot[0] = epi.ExceptionSpec.SourceDecl;
  2585. }
  2586. // If this is a canonical type, and its exception specification is dependent,
  2587. // then it's a dependent type. This only happens in C++17 onwards.
  2588. if (isCanonicalUnqualified()) {
  2589. if (getExceptionSpecType() == EST_Dynamic ||
  2590. getExceptionSpecType() == EST_DependentNoexcept) {
  2591. assert(hasDependentExceptionSpec() && "type should not be canonical");
  2592. setDependent();
  2593. }
  2594. } else if (getCanonicalTypeInternal()->isDependentType()) {
  2595. // Ask our canonical type whether our exception specification was dependent.
  2596. setDependent();
  2597. }
  2598. // Fill in the extra parameter info if present.
  2599. if (epi.ExtParameterInfos) {
  2600. auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
  2601. for (unsigned i = 0; i != getNumParams(); ++i)
  2602. extParamInfos[i] = epi.ExtParameterInfos[i];
  2603. }
  2604. if (epi.TypeQuals.hasNonFastQualifiers()) {
  2605. FunctionTypeBits.HasExtQuals = 1;
  2606. *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
  2607. } else {
  2608. FunctionTypeBits.HasExtQuals = 0;
  2609. }
  2610. }
  2611. bool FunctionProtoType::hasDependentExceptionSpec() const {
  2612. if (Expr *NE = getNoexceptExpr())
  2613. return NE->isValueDependent();
  2614. for (QualType ET : exceptions())
  2615. // A pack expansion with a non-dependent pattern is still dependent,
  2616. // because we don't know whether the pattern is in the exception spec
  2617. // or not (that depends on whether the pack has 0 expansions).
  2618. if (ET->isDependentType() || ET->getAs<PackExpansionType>())
  2619. return true;
  2620. return false;
  2621. }
  2622. bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
  2623. if (Expr *NE = getNoexceptExpr())
  2624. return NE->isInstantiationDependent();
  2625. for (QualType ET : exceptions())
  2626. if (ET->isInstantiationDependentType())
  2627. return true;
  2628. return false;
  2629. }
  2630. CanThrowResult FunctionProtoType::canThrow() const {
  2631. switch (getExceptionSpecType()) {
  2632. case EST_Unparsed:
  2633. case EST_Unevaluated:
  2634. case EST_Uninstantiated:
  2635. llvm_unreachable("should not call this with unresolved exception specs");
  2636. case EST_DynamicNone:
  2637. case EST_BasicNoexcept:
  2638. case EST_NoexceptTrue:
  2639. case EST_NoThrow:
  2640. return CT_Cannot;
  2641. case EST_None:
  2642. case EST_MSAny:
  2643. case EST_NoexceptFalse:
  2644. return CT_Can;
  2645. case EST_Dynamic:
  2646. // A dynamic exception specification is throwing unless every exception
  2647. // type is an (unexpanded) pack expansion type.
  2648. for (unsigned I = 0; I != getNumExceptions(); ++I)
  2649. if (!getExceptionType(I)->getAs<PackExpansionType>())
  2650. return CT_Can;
  2651. return CT_Dependent;
  2652. case EST_DependentNoexcept:
  2653. return CT_Dependent;
  2654. }
  2655. llvm_unreachable("unexpected exception specification kind");
  2656. }
  2657. bool FunctionProtoType::isTemplateVariadic() const {
  2658. for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
  2659. if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
  2660. return true;
  2661. return false;
  2662. }
  2663. void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
  2664. const QualType *ArgTys, unsigned NumParams,
  2665. const ExtProtoInfo &epi,
  2666. const ASTContext &Context, bool Canonical) {
  2667. // We have to be careful not to get ambiguous profile encodings.
  2668. // Note that valid type pointers are never ambiguous with anything else.
  2669. //
  2670. // The encoding grammar begins:
  2671. // type type* bool int bool
  2672. // If that final bool is true, then there is a section for the EH spec:
  2673. // bool type*
  2674. // This is followed by an optional "consumed argument" section of the
  2675. // same length as the first type sequence:
  2676. // bool*
  2677. // Finally, we have the ext info and trailing return type flag:
  2678. // int bool
  2679. //
  2680. // There is no ambiguity between the consumed arguments and an empty EH
  2681. // spec because of the leading 'bool' which unambiguously indicates
  2682. // whether the following bool is the EH spec or part of the arguments.
  2683. ID.AddPointer(Result.getAsOpaquePtr());
  2684. for (unsigned i = 0; i != NumParams; ++i)
  2685. ID.AddPointer(ArgTys[i].getAsOpaquePtr());
  2686. // This method is relatively performance sensitive, so as a performance
  2687. // shortcut, use one AddInteger call instead of four for the next four
  2688. // fields.
  2689. assert(!(unsigned(epi.Variadic) & ~1) &&
  2690. !(unsigned(epi.RefQualifier) & ~3) &&
  2691. !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
  2692. "Values larger than expected.");
  2693. ID.AddInteger(unsigned(epi.Variadic) +
  2694. (epi.RefQualifier << 1) +
  2695. (epi.ExceptionSpec.Type << 3));
  2696. ID.Add(epi.TypeQuals);
  2697. if (epi.ExceptionSpec.Type == EST_Dynamic) {
  2698. for (QualType Ex : epi.ExceptionSpec.Exceptions)
  2699. ID.AddPointer(Ex.getAsOpaquePtr());
  2700. } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
  2701. epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
  2702. } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
  2703. epi.ExceptionSpec.Type == EST_Unevaluated) {
  2704. ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
  2705. }
  2706. if (epi.ExtParameterInfos) {
  2707. for (unsigned i = 0; i != NumParams; ++i)
  2708. ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
  2709. }
  2710. epi.ExtInfo.Profile(ID);
  2711. ID.AddBoolean(epi.HasTrailingReturn);
  2712. }
  2713. void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
  2714. const ASTContext &Ctx) {
  2715. Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
  2716. getExtProtoInfo(), Ctx, isCanonicalUnqualified());
  2717. }
  2718. QualType TypedefType::desugar() const {
  2719. return getDecl()->getUnderlyingType();
  2720. }
  2721. QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
  2722. QualType MacroQualifiedType::getModifiedType() const {
  2723. // Step over MacroQualifiedTypes from the same macro to find the type
  2724. // ultimately qualified by the macro qualifier.
  2725. QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
  2726. while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
  2727. if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
  2728. break;
  2729. Inner = InnerMQT->getModifiedType();
  2730. }
  2731. return Inner;
  2732. }
  2733. TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
  2734. : Type(TypeOfExpr, can, E->isTypeDependent(),
  2735. E->isInstantiationDependent(),
  2736. E->getType()->isVariablyModifiedType(),
  2737. E->containsUnexpandedParameterPack()),
  2738. TOExpr(E) {}
  2739. bool TypeOfExprType::isSugared() const {
  2740. return !TOExpr->isTypeDependent();
  2741. }
  2742. QualType TypeOfExprType::desugar() const {
  2743. if (isSugared())
  2744. return getUnderlyingExpr()->getType();
  2745. return QualType(this, 0);
  2746. }
  2747. void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
  2748. const ASTContext &Context, Expr *E) {
  2749. E->Profile(ID, Context, true);
  2750. }
  2751. DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
  2752. // C++11 [temp.type]p2: "If an expression e involves a template parameter,
  2753. // decltype(e) denotes a unique dependent type." Hence a decltype type is
  2754. // type-dependent even if its expression is only instantiation-dependent.
  2755. : Type(Decltype, can, E->isInstantiationDependent(),
  2756. E->isInstantiationDependent(),
  2757. E->getType()->isVariablyModifiedType(),
  2758. E->containsUnexpandedParameterPack()),
  2759. E(E), UnderlyingType(underlyingType) {}
  2760. bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
  2761. QualType DecltypeType::desugar() const {
  2762. if (isSugared())
  2763. return getUnderlyingType();
  2764. return QualType(this, 0);
  2765. }
  2766. DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
  2767. : DecltypeType(E, Context.DependentTy), Context(Context) {}
  2768. void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
  2769. const ASTContext &Context, Expr *E) {
  2770. E->Profile(ID, Context, true);
  2771. }
  2772. UnaryTransformType::UnaryTransformType(QualType BaseType,
  2773. QualType UnderlyingType,
  2774. UTTKind UKind,
  2775. QualType CanonicalType)
  2776. : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(),
  2777. BaseType->isInstantiationDependentType(),
  2778. BaseType->isVariablyModifiedType(),
  2779. BaseType->containsUnexpandedParameterPack()),
  2780. BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
  2781. DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
  2782. QualType BaseType,
  2783. UTTKind UKind)
  2784. : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
  2785. TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
  2786. : Type(TC, can, D->isDependentType(),
  2787. /*InstantiationDependent=*/D->isDependentType(),
  2788. /*VariablyModified=*/false,
  2789. /*ContainsUnexpandedParameterPack=*/false),
  2790. decl(const_cast<TagDecl*>(D)) {}
  2791. static TagDecl *getInterestingTagDecl(TagDecl *decl) {
  2792. for (auto I : decl->redecls()) {
  2793. if (I->isCompleteDefinition() || I->isBeingDefined())
  2794. return I;
  2795. }
  2796. // If there's no definition (not even in progress), return what we have.
  2797. return decl;
  2798. }
  2799. TagDecl *TagType::getDecl() const {
  2800. return getInterestingTagDecl(decl);
  2801. }
  2802. bool TagType::isBeingDefined() const {
  2803. return getDecl()->isBeingDefined();
  2804. }
  2805. bool RecordType::hasConstFields() const {
  2806. std::vector<const RecordType*> RecordTypeList;
  2807. RecordTypeList.push_back(this);
  2808. unsigned NextToCheckIndex = 0;
  2809. while (RecordTypeList.size() > NextToCheckIndex) {
  2810. for (FieldDecl *FD :
  2811. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  2812. QualType FieldTy = FD->getType();
  2813. if (FieldTy.isConstQualified())
  2814. return true;
  2815. FieldTy = FieldTy.getCanonicalType();
  2816. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  2817. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  2818. RecordTypeList.push_back(FieldRecTy);
  2819. }
  2820. }
  2821. ++NextToCheckIndex;
  2822. }
  2823. return false;
  2824. }
  2825. bool AttributedType::isQualifier() const {
  2826. // FIXME: Generate this with TableGen.
  2827. switch (getAttrKind()) {
  2828. // These are type qualifiers in the traditional C sense: they annotate
  2829. // something about a specific value/variable of a type. (They aren't
  2830. // always part of the canonical type, though.)
  2831. case attr::ObjCGC:
  2832. case attr::ObjCOwnership:
  2833. case attr::ObjCInertUnsafeUnretained:
  2834. case attr::TypeNonNull:
  2835. case attr::TypeNullable:
  2836. case attr::TypeNullUnspecified:
  2837. case attr::LifetimeBound:
  2838. case attr::AddressSpace:
  2839. return true;
  2840. // All other type attributes aren't qualifiers; they rewrite the modified
  2841. // type to be a semantically different type.
  2842. default:
  2843. return false;
  2844. }
  2845. }
  2846. bool AttributedType::isMSTypeSpec() const {
  2847. // FIXME: Generate this with TableGen?
  2848. switch (getAttrKind()) {
  2849. default: return false;
  2850. case attr::Ptr32:
  2851. case attr::Ptr64:
  2852. case attr::SPtr:
  2853. case attr::UPtr:
  2854. return true;
  2855. }
  2856. llvm_unreachable("invalid attr kind");
  2857. }
  2858. bool AttributedType::isCallingConv() const {
  2859. // FIXME: Generate this with TableGen.
  2860. switch (getAttrKind()) {
  2861. default: return false;
  2862. case attr::Pcs:
  2863. case attr::CDecl:
  2864. case attr::FastCall:
  2865. case attr::StdCall:
  2866. case attr::ThisCall:
  2867. case attr::RegCall:
  2868. case attr::SwiftCall:
  2869. case attr::VectorCall:
  2870. case attr::AArch64VectorPcs:
  2871. case attr::Pascal:
  2872. case attr::MSABI:
  2873. case attr::SysVABI:
  2874. case attr::IntelOclBicc:
  2875. case attr::PreserveMost:
  2876. case attr::PreserveAll:
  2877. return true;
  2878. }
  2879. llvm_unreachable("invalid attr kind");
  2880. }
  2881. CXXRecordDecl *InjectedClassNameType::getDecl() const {
  2882. return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
  2883. }
  2884. IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
  2885. return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
  2886. }
  2887. SubstTemplateTypeParmPackType::
  2888. SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
  2889. QualType Canon,
  2890. const TemplateArgument &ArgPack)
  2891. : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
  2892. Replaced(Param), Arguments(ArgPack.pack_begin()) {
  2893. SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
  2894. }
  2895. TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
  2896. return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs()));
  2897. }
  2898. void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
  2899. Profile(ID, getReplacedParameter(), getArgumentPack());
  2900. }
  2901. void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
  2902. const TemplateTypeParmType *Replaced,
  2903. const TemplateArgument &ArgPack) {
  2904. ID.AddPointer(Replaced);
  2905. ID.AddInteger(ArgPack.pack_size());
  2906. for (const auto &P : ArgPack.pack_elements())
  2907. ID.AddPointer(P.getAsType().getAsOpaquePtr());
  2908. }
  2909. bool TemplateSpecializationType::
  2910. anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
  2911. bool &InstantiationDependent) {
  2912. return anyDependentTemplateArguments(Args.arguments(),
  2913. InstantiationDependent);
  2914. }
  2915. bool TemplateSpecializationType::
  2916. anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
  2917. bool &InstantiationDependent) {
  2918. for (const TemplateArgumentLoc &ArgLoc : Args) {
  2919. if (ArgLoc.getArgument().isDependent()) {
  2920. InstantiationDependent = true;
  2921. return true;
  2922. }
  2923. if (ArgLoc.getArgument().isInstantiationDependent())
  2924. InstantiationDependent = true;
  2925. }
  2926. return false;
  2927. }
  2928. TemplateSpecializationType::
  2929. TemplateSpecializationType(TemplateName T,
  2930. ArrayRef<TemplateArgument> Args,
  2931. QualType Canon, QualType AliasedType)
  2932. : Type(TemplateSpecialization,
  2933. Canon.isNull()? QualType(this, 0) : Canon,
  2934. Canon.isNull()? true : Canon->isDependentType(),
  2935. Canon.isNull()? true : Canon->isInstantiationDependentType(),
  2936. false,
  2937. T.containsUnexpandedParameterPack()), Template(T) {
  2938. TemplateSpecializationTypeBits.NumArgs = Args.size();
  2939. TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
  2940. assert(!T.getAsDependentTemplateName() &&
  2941. "Use DependentTemplateSpecializationType for dependent template-name");
  2942. assert((T.getKind() == TemplateName::Template ||
  2943. T.getKind() == TemplateName::SubstTemplateTemplateParm ||
  2944. T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
  2945. "Unexpected template name for TemplateSpecializationType");
  2946. auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
  2947. for (const TemplateArgument &Arg : Args) {
  2948. // Update instantiation-dependent and variably-modified bits.
  2949. // If the canonical type exists and is non-dependent, the template
  2950. // specialization type can be non-dependent even if one of the type
  2951. // arguments is. Given:
  2952. // template<typename T> using U = int;
  2953. // U<T> is always non-dependent, irrespective of the type T.
  2954. // However, U<Ts> contains an unexpanded parameter pack, even though
  2955. // its expansion (and thus its desugared type) doesn't.
  2956. if (Arg.isInstantiationDependent())
  2957. setInstantiationDependent();
  2958. if (Arg.getKind() == TemplateArgument::Type &&
  2959. Arg.getAsType()->isVariablyModifiedType())
  2960. setVariablyModified();
  2961. if (Arg.containsUnexpandedParameterPack())
  2962. setContainsUnexpandedParameterPack();
  2963. new (TemplateArgs++) TemplateArgument(Arg);
  2964. }
  2965. // Store the aliased type if this is a type alias template specialization.
  2966. if (isTypeAlias()) {
  2967. auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
  2968. *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
  2969. }
  2970. }
  2971. void
  2972. TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
  2973. TemplateName T,
  2974. ArrayRef<TemplateArgument> Args,
  2975. const ASTContext &Context) {
  2976. T.Profile(ID);
  2977. for (const TemplateArgument &Arg : Args)
  2978. Arg.Profile(ID, Context);
  2979. }
  2980. QualType
  2981. QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
  2982. if (!hasNonFastQualifiers())
  2983. return QT.withFastQualifiers(getFastQualifiers());
  2984. return Context.getQualifiedType(QT, *this);
  2985. }
  2986. QualType
  2987. QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
  2988. if (!hasNonFastQualifiers())
  2989. return QualType(T, getFastQualifiers());
  2990. return Context.getQualifiedType(T, *this);
  2991. }
  2992. void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
  2993. QualType BaseType,
  2994. ArrayRef<QualType> typeArgs,
  2995. ArrayRef<ObjCProtocolDecl *> protocols,
  2996. bool isKindOf) {
  2997. ID.AddPointer(BaseType.getAsOpaquePtr());
  2998. ID.AddInteger(typeArgs.size());
  2999. for (auto typeArg : typeArgs)
  3000. ID.AddPointer(typeArg.getAsOpaquePtr());
  3001. ID.AddInteger(protocols.size());
  3002. for (auto proto : protocols)
  3003. ID.AddPointer(proto);
  3004. ID.AddBoolean(isKindOf);
  3005. }
  3006. void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
  3007. Profile(ID, getBaseType(), getTypeArgsAsWritten(),
  3008. llvm::makeArrayRef(qual_begin(), getNumProtocols()),
  3009. isKindOfTypeAsWritten());
  3010. }
  3011. void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
  3012. const ObjCTypeParamDecl *OTPDecl,
  3013. ArrayRef<ObjCProtocolDecl *> protocols) {
  3014. ID.AddPointer(OTPDecl);
  3015. ID.AddInteger(protocols.size());
  3016. for (auto proto : protocols)
  3017. ID.AddPointer(proto);
  3018. }
  3019. void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
  3020. Profile(ID, getDecl(),
  3021. llvm::makeArrayRef(qual_begin(), getNumProtocols()));
  3022. }
  3023. namespace {
  3024. /// The cached properties of a type.
  3025. class CachedProperties {
  3026. Linkage L;
  3027. bool local;
  3028. public:
  3029. CachedProperties(Linkage L, bool local) : L(L), local(local) {}
  3030. Linkage getLinkage() const { return L; }
  3031. bool hasLocalOrUnnamedType() const { return local; }
  3032. friend CachedProperties merge(CachedProperties L, CachedProperties R) {
  3033. Linkage MergedLinkage = minLinkage(L.L, R.L);
  3034. return CachedProperties(MergedLinkage,
  3035. L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
  3036. }
  3037. };
  3038. } // namespace
  3039. static CachedProperties computeCachedProperties(const Type *T);
  3040. namespace clang {
  3041. /// The type-property cache. This is templated so as to be
  3042. /// instantiated at an internal type to prevent unnecessary symbol
  3043. /// leakage.
  3044. template <class Private> class TypePropertyCache {
  3045. public:
  3046. static CachedProperties get(QualType T) {
  3047. return get(T.getTypePtr());
  3048. }
  3049. static CachedProperties get(const Type *T) {
  3050. ensure(T);
  3051. return CachedProperties(T->TypeBits.getLinkage(),
  3052. T->TypeBits.hasLocalOrUnnamedType());
  3053. }
  3054. static void ensure(const Type *T) {
  3055. // If the cache is valid, we're okay.
  3056. if (T->TypeBits.isCacheValid()) return;
  3057. // If this type is non-canonical, ask its canonical type for the
  3058. // relevant information.
  3059. if (!T->isCanonicalUnqualified()) {
  3060. const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
  3061. ensure(CT);
  3062. T->TypeBits.CacheValid = true;
  3063. T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
  3064. T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
  3065. return;
  3066. }
  3067. // Compute the cached properties and then set the cache.
  3068. CachedProperties Result = computeCachedProperties(T);
  3069. T->TypeBits.CacheValid = true;
  3070. T->TypeBits.CachedLinkage = Result.getLinkage();
  3071. T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
  3072. }
  3073. };
  3074. } // namespace clang
  3075. // Instantiate the friend template at a private class. In a
  3076. // reasonable implementation, these symbols will be internal.
  3077. // It is terrible that this is the best way to accomplish this.
  3078. namespace {
  3079. class Private {};
  3080. } // namespace
  3081. using Cache = TypePropertyCache<Private>;
  3082. static CachedProperties computeCachedProperties(const Type *T) {
  3083. switch (T->getTypeClass()) {
  3084. #define TYPE(Class,Base)
  3085. #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
  3086. #include "clang/AST/TypeNodes.inc"
  3087. llvm_unreachable("didn't expect a non-canonical type here");
  3088. #define TYPE(Class,Base)
  3089. #define DEPENDENT_TYPE(Class,Base) case Type::Class:
  3090. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
  3091. #include "clang/AST/TypeNodes.inc"
  3092. // Treat instantiation-dependent types as external.
  3093. if (!T->isInstantiationDependentType()) T->dump();
  3094. assert(T->isInstantiationDependentType());
  3095. return CachedProperties(ExternalLinkage, false);
  3096. case Type::Auto:
  3097. case Type::DeducedTemplateSpecialization:
  3098. // Give non-deduced 'auto' types external linkage. We should only see them
  3099. // here in error recovery.
  3100. return CachedProperties(ExternalLinkage, false);
  3101. case Type::Builtin:
  3102. // C++ [basic.link]p8:
  3103. // A type is said to have linkage if and only if:
  3104. // - it is a fundamental type (3.9.1); or
  3105. return CachedProperties(ExternalLinkage, false);
  3106. case Type::Record:
  3107. case Type::Enum: {
  3108. const TagDecl *Tag = cast<TagType>(T)->getDecl();
  3109. // C++ [basic.link]p8:
  3110. // - it is a class or enumeration type that is named (or has a name
  3111. // for linkage purposes (7.1.3)) and the name has linkage; or
  3112. // - it is a specialization of a class template (14); or
  3113. Linkage L = Tag->getLinkageInternal();
  3114. bool IsLocalOrUnnamed =
  3115. Tag->getDeclContext()->isFunctionOrMethod() ||
  3116. !Tag->hasNameForLinkage();
  3117. return CachedProperties(L, IsLocalOrUnnamed);
  3118. }
  3119. // C++ [basic.link]p8:
  3120. // - it is a compound type (3.9.2) other than a class or enumeration,
  3121. // compounded exclusively from types that have linkage; or
  3122. case Type::Complex:
  3123. return Cache::get(cast<ComplexType>(T)->getElementType());
  3124. case Type::Pointer:
  3125. return Cache::get(cast<PointerType>(T)->getPointeeType());
  3126. case Type::BlockPointer:
  3127. return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
  3128. case Type::LValueReference:
  3129. case Type::RValueReference:
  3130. return Cache::get(cast<ReferenceType>(T)->getPointeeType());
  3131. case Type::MemberPointer: {
  3132. const auto *MPT = cast<MemberPointerType>(T);
  3133. return merge(Cache::get(MPT->getClass()),
  3134. Cache::get(MPT->getPointeeType()));
  3135. }
  3136. case Type::ConstantArray:
  3137. case Type::IncompleteArray:
  3138. case Type::VariableArray:
  3139. return Cache::get(cast<ArrayType>(T)->getElementType());
  3140. case Type::Vector:
  3141. case Type::ExtVector:
  3142. return Cache::get(cast<VectorType>(T)->getElementType());
  3143. case Type::FunctionNoProto:
  3144. return Cache::get(cast<FunctionType>(T)->getReturnType());
  3145. case Type::FunctionProto: {
  3146. const auto *FPT = cast<FunctionProtoType>(T);
  3147. CachedProperties result = Cache::get(FPT->getReturnType());
  3148. for (const auto &ai : FPT->param_types())
  3149. result = merge(result, Cache::get(ai));
  3150. return result;
  3151. }
  3152. case Type::ObjCInterface: {
  3153. Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
  3154. return CachedProperties(L, false);
  3155. }
  3156. case Type::ObjCObject:
  3157. return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
  3158. case Type::ObjCObjectPointer:
  3159. return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
  3160. case Type::Atomic:
  3161. return Cache::get(cast<AtomicType>(T)->getValueType());
  3162. case Type::Pipe:
  3163. return Cache::get(cast<PipeType>(T)->getElementType());
  3164. }
  3165. llvm_unreachable("unhandled type class");
  3166. }
  3167. /// Determine the linkage of this type.
  3168. Linkage Type::getLinkage() const {
  3169. Cache::ensure(this);
  3170. return TypeBits.getLinkage();
  3171. }
  3172. bool Type::hasUnnamedOrLocalType() const {
  3173. Cache::ensure(this);
  3174. return TypeBits.hasLocalOrUnnamedType();
  3175. }
  3176. LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
  3177. switch (T->getTypeClass()) {
  3178. #define TYPE(Class,Base)
  3179. #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
  3180. #include "clang/AST/TypeNodes.inc"
  3181. llvm_unreachable("didn't expect a non-canonical type here");
  3182. #define TYPE(Class,Base)
  3183. #define DEPENDENT_TYPE(Class,Base) case Type::Class:
  3184. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
  3185. #include "clang/AST/TypeNodes.inc"
  3186. // Treat instantiation-dependent types as external.
  3187. assert(T->isInstantiationDependentType());
  3188. return LinkageInfo::external();
  3189. case Type::Builtin:
  3190. return LinkageInfo::external();
  3191. case Type::Auto:
  3192. case Type::DeducedTemplateSpecialization:
  3193. return LinkageInfo::external();
  3194. case Type::Record:
  3195. case Type::Enum:
  3196. return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
  3197. case Type::Complex:
  3198. return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
  3199. case Type::Pointer:
  3200. return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
  3201. case Type::BlockPointer:
  3202. return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
  3203. case Type::LValueReference:
  3204. case Type::RValueReference:
  3205. return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
  3206. case Type::MemberPointer: {
  3207. const auto *MPT = cast<MemberPointerType>(T);
  3208. LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
  3209. LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
  3210. return LV;
  3211. }
  3212. case Type::ConstantArray:
  3213. case Type::IncompleteArray:
  3214. case Type::VariableArray:
  3215. return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
  3216. case Type::Vector:
  3217. case Type::ExtVector:
  3218. return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
  3219. case Type::FunctionNoProto:
  3220. return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
  3221. case Type::FunctionProto: {
  3222. const auto *FPT = cast<FunctionProtoType>(T);
  3223. LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
  3224. for (const auto &ai : FPT->param_types())
  3225. LV.merge(computeTypeLinkageInfo(ai));
  3226. return LV;
  3227. }
  3228. case Type::ObjCInterface:
  3229. return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
  3230. case Type::ObjCObject:
  3231. return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
  3232. case Type::ObjCObjectPointer:
  3233. return computeTypeLinkageInfo(
  3234. cast<ObjCObjectPointerType>(T)->getPointeeType());
  3235. case Type::Atomic:
  3236. return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
  3237. case Type::Pipe:
  3238. return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
  3239. }
  3240. llvm_unreachable("unhandled type class");
  3241. }
  3242. bool Type::isLinkageValid() const {
  3243. if (!TypeBits.isCacheValid())
  3244. return true;
  3245. Linkage L = LinkageComputer{}
  3246. .computeTypeLinkageInfo(getCanonicalTypeInternal())
  3247. .getLinkage();
  3248. return L == TypeBits.getLinkage();
  3249. }
  3250. LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
  3251. if (!T->isCanonicalUnqualified())
  3252. return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
  3253. LinkageInfo LV = computeTypeLinkageInfo(T);
  3254. assert(LV.getLinkage() == T->getLinkage());
  3255. return LV;
  3256. }
  3257. LinkageInfo Type::getLinkageAndVisibility() const {
  3258. return LinkageComputer{}.getTypeLinkageAndVisibility(this);
  3259. }
  3260. Optional<NullabilityKind>
  3261. Type::getNullability(const ASTContext &Context) const {
  3262. QualType Type(this, 0);
  3263. while (const auto *AT = Type->getAs<AttributedType>()) {
  3264. // Check whether this is an attributed type with nullability
  3265. // information.
  3266. if (auto Nullability = AT->getImmediateNullability())
  3267. return Nullability;
  3268. Type = AT->getEquivalentType();
  3269. }
  3270. return None;
  3271. }
  3272. bool Type::canHaveNullability(bool ResultIfUnknown) const {
  3273. QualType type = getCanonicalTypeInternal();
  3274. switch (type->getTypeClass()) {
  3275. // We'll only see canonical types here.
  3276. #define NON_CANONICAL_TYPE(Class, Parent) \
  3277. case Type::Class: \
  3278. llvm_unreachable("non-canonical type");
  3279. #define TYPE(Class, Parent)
  3280. #include "clang/AST/TypeNodes.inc"
  3281. // Pointer types.
  3282. case Type::Pointer:
  3283. case Type::BlockPointer:
  3284. case Type::MemberPointer:
  3285. case Type::ObjCObjectPointer:
  3286. return true;
  3287. // Dependent types that could instantiate to pointer types.
  3288. case Type::UnresolvedUsing:
  3289. case Type::TypeOfExpr:
  3290. case Type::TypeOf:
  3291. case Type::Decltype:
  3292. case Type::UnaryTransform:
  3293. case Type::TemplateTypeParm:
  3294. case Type::SubstTemplateTypeParmPack:
  3295. case Type::DependentName:
  3296. case Type::DependentTemplateSpecialization:
  3297. case Type::Auto:
  3298. return ResultIfUnknown;
  3299. // Dependent template specializations can instantiate to pointer
  3300. // types unless they're known to be specializations of a class
  3301. // template.
  3302. case Type::TemplateSpecialization:
  3303. if (TemplateDecl *templateDecl
  3304. = cast<TemplateSpecializationType>(type.getTypePtr())
  3305. ->getTemplateName().getAsTemplateDecl()) {
  3306. if (isa<ClassTemplateDecl>(templateDecl))
  3307. return false;
  3308. }
  3309. return ResultIfUnknown;
  3310. case Type::Builtin:
  3311. switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
  3312. // Signed, unsigned, and floating-point types cannot have nullability.
  3313. #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  3314. #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  3315. #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
  3316. #define BUILTIN_TYPE(Id, SingletonId)
  3317. #include "clang/AST/BuiltinTypes.def"
  3318. return false;
  3319. // Dependent types that could instantiate to a pointer type.
  3320. case BuiltinType::Dependent:
  3321. case BuiltinType::Overload:
  3322. case BuiltinType::BoundMember:
  3323. case BuiltinType::PseudoObject:
  3324. case BuiltinType::UnknownAny:
  3325. case BuiltinType::ARCUnbridgedCast:
  3326. return ResultIfUnknown;
  3327. case BuiltinType::Void:
  3328. case BuiltinType::ObjCId:
  3329. case BuiltinType::ObjCClass:
  3330. case BuiltinType::ObjCSel:
  3331. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  3332. case BuiltinType::Id:
  3333. #include "clang/Basic/OpenCLImageTypes.def"
  3334. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  3335. case BuiltinType::Id:
  3336. #include "clang/Basic/OpenCLExtensionTypes.def"
  3337. case BuiltinType::OCLSampler:
  3338. case BuiltinType::OCLEvent:
  3339. case BuiltinType::OCLClkEvent:
  3340. case BuiltinType::OCLQueue:
  3341. case BuiltinType::OCLReserveID:
  3342. #define SVE_TYPE(Name, Id, SingletonId) \
  3343. case BuiltinType::Id:
  3344. #include "clang/Basic/AArch64SVEACLETypes.def"
  3345. case BuiltinType::BuiltinFn:
  3346. case BuiltinType::NullPtr:
  3347. case BuiltinType::OMPArraySection:
  3348. return false;
  3349. }
  3350. llvm_unreachable("unknown builtin type");
  3351. // Non-pointer types.
  3352. case Type::Complex:
  3353. case Type::LValueReference:
  3354. case Type::RValueReference:
  3355. case Type::ConstantArray:
  3356. case Type::IncompleteArray:
  3357. case Type::VariableArray:
  3358. case Type::DependentSizedArray:
  3359. case Type::DependentVector:
  3360. case Type::DependentSizedExtVector:
  3361. case Type::Vector:
  3362. case Type::ExtVector:
  3363. case Type::DependentAddressSpace:
  3364. case Type::FunctionProto:
  3365. case Type::FunctionNoProto:
  3366. case Type::Record:
  3367. case Type::DeducedTemplateSpecialization:
  3368. case Type::Enum:
  3369. case Type::InjectedClassName:
  3370. case Type::PackExpansion:
  3371. case Type::ObjCObject:
  3372. case Type::ObjCInterface:
  3373. case Type::Atomic:
  3374. case Type::Pipe:
  3375. return false;
  3376. }
  3377. llvm_unreachable("bad type kind!");
  3378. }
  3379. llvm::Optional<NullabilityKind>
  3380. AttributedType::getImmediateNullability() const {
  3381. if (getAttrKind() == attr::TypeNonNull)
  3382. return NullabilityKind::NonNull;
  3383. if (getAttrKind() == attr::TypeNullable)
  3384. return NullabilityKind::Nullable;
  3385. if (getAttrKind() == attr::TypeNullUnspecified)
  3386. return NullabilityKind::Unspecified;
  3387. return None;
  3388. }
  3389. Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
  3390. QualType AttrTy = T;
  3391. if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
  3392. AttrTy = MacroTy->getUnderlyingType();
  3393. if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
  3394. if (auto nullability = attributed->getImmediateNullability()) {
  3395. T = attributed->getModifiedType();
  3396. return nullability;
  3397. }
  3398. }
  3399. return None;
  3400. }
  3401. bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
  3402. const auto *objcPtr = getAs<ObjCObjectPointerType>();
  3403. if (!objcPtr)
  3404. return false;
  3405. if (objcPtr->isObjCIdType()) {
  3406. // id is always okay.
  3407. return true;
  3408. }
  3409. // Blocks are NSObjects.
  3410. if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
  3411. if (iface->getIdentifier() != ctx.getNSObjectName())
  3412. return false;
  3413. // Continue to check qualifiers, below.
  3414. } else if (objcPtr->isObjCQualifiedIdType()) {
  3415. // Continue to check qualifiers, below.
  3416. } else {
  3417. return false;
  3418. }
  3419. // Check protocol qualifiers.
  3420. for (ObjCProtocolDecl *proto : objcPtr->quals()) {
  3421. // Blocks conform to NSObject and NSCopying.
  3422. if (proto->getIdentifier() != ctx.getNSObjectName() &&
  3423. proto->getIdentifier() != ctx.getNSCopyingName())
  3424. return false;
  3425. }
  3426. return true;
  3427. }
  3428. Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
  3429. if (isObjCARCImplicitlyUnretainedType())
  3430. return Qualifiers::OCL_ExplicitNone;
  3431. return Qualifiers::OCL_Strong;
  3432. }
  3433. bool Type::isObjCARCImplicitlyUnretainedType() const {
  3434. assert(isObjCLifetimeType() &&
  3435. "cannot query implicit lifetime for non-inferrable type");
  3436. const Type *canon = getCanonicalTypeInternal().getTypePtr();
  3437. // Walk down to the base type. We don't care about qualifiers for this.
  3438. while (const auto *array = dyn_cast<ArrayType>(canon))
  3439. canon = array->getElementType().getTypePtr();
  3440. if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
  3441. // Class and Class<Protocol> don't require retention.
  3442. if (opt->getObjectType()->isObjCClass())
  3443. return true;
  3444. }
  3445. return false;
  3446. }
  3447. bool Type::isObjCNSObjectType() const {
  3448. const Type *cur = this;
  3449. while (true) {
  3450. if (const auto *typedefType = dyn_cast<TypedefType>(cur))
  3451. return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
  3452. // Single-step desugar until we run out of sugar.
  3453. QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
  3454. if (next.getTypePtr() == cur) return false;
  3455. cur = next.getTypePtr();
  3456. }
  3457. }
  3458. bool Type::isObjCIndependentClassType() const {
  3459. if (const auto *typedefType = dyn_cast<TypedefType>(this))
  3460. return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
  3461. return false;
  3462. }
  3463. bool Type::isObjCRetainableType() const {
  3464. return isObjCObjectPointerType() ||
  3465. isBlockPointerType() ||
  3466. isObjCNSObjectType();
  3467. }
  3468. bool Type::isObjCIndirectLifetimeType() const {
  3469. if (isObjCLifetimeType())
  3470. return true;
  3471. if (const auto *OPT = getAs<PointerType>())
  3472. return OPT->getPointeeType()->isObjCIndirectLifetimeType();
  3473. if (const auto *Ref = getAs<ReferenceType>())
  3474. return Ref->getPointeeType()->isObjCIndirectLifetimeType();
  3475. if (const auto *MemPtr = getAs<MemberPointerType>())
  3476. return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
  3477. return false;
  3478. }
  3479. /// Returns true if objects of this type have lifetime semantics under
  3480. /// ARC.
  3481. bool Type::isObjCLifetimeType() const {
  3482. const Type *type = this;
  3483. while (const ArrayType *array = type->getAsArrayTypeUnsafe())
  3484. type = array->getElementType().getTypePtr();
  3485. return type->isObjCRetainableType();
  3486. }
  3487. /// Determine whether the given type T is a "bridgable" Objective-C type,
  3488. /// which is either an Objective-C object pointer type or an
  3489. bool Type::isObjCARCBridgableType() const {
  3490. return isObjCObjectPointerType() || isBlockPointerType();
  3491. }
  3492. /// Determine whether the given type T is a "bridgeable" C type.
  3493. bool Type::isCARCBridgableType() const {
  3494. const auto *Pointer = getAs<PointerType>();
  3495. if (!Pointer)
  3496. return false;
  3497. QualType Pointee = Pointer->getPointeeType();
  3498. return Pointee->isVoidType() || Pointee->isRecordType();
  3499. }
  3500. bool Type::hasSizedVLAType() const {
  3501. if (!isVariablyModifiedType()) return false;
  3502. if (const auto *ptr = getAs<PointerType>())
  3503. return ptr->getPointeeType()->hasSizedVLAType();
  3504. if (const auto *ref = getAs<ReferenceType>())
  3505. return ref->getPointeeType()->hasSizedVLAType();
  3506. if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
  3507. if (isa<VariableArrayType>(arr) &&
  3508. cast<VariableArrayType>(arr)->getSizeExpr())
  3509. return true;
  3510. return arr->getElementType()->hasSizedVLAType();
  3511. }
  3512. return false;
  3513. }
  3514. QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
  3515. switch (type.getObjCLifetime()) {
  3516. case Qualifiers::OCL_None:
  3517. case Qualifiers::OCL_ExplicitNone:
  3518. case Qualifiers::OCL_Autoreleasing:
  3519. break;
  3520. case Qualifiers::OCL_Strong:
  3521. return DK_objc_strong_lifetime;
  3522. case Qualifiers::OCL_Weak:
  3523. return DK_objc_weak_lifetime;
  3524. }
  3525. if (const auto *RT =
  3526. type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  3527. const RecordDecl *RD = RT->getDecl();
  3528. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3529. /// Check if this is a C++ object with a non-trivial destructor.
  3530. if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
  3531. return DK_cxx_destructor;
  3532. } else {
  3533. /// Check if this is a C struct that is non-trivial to destroy or an array
  3534. /// that contains such a struct.
  3535. if (RD->isNonTrivialToPrimitiveDestroy())
  3536. return DK_nontrivial_c_struct;
  3537. }
  3538. }
  3539. return DK_none;
  3540. }
  3541. CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
  3542. return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
  3543. }
  3544. void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
  3545. llvm::APSInt Val, unsigned Scale) {
  3546. FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
  3547. /*IsSaturated=*/false,
  3548. /*HasUnsignedPadding=*/false);
  3549. APFixedPoint(Val, FXSema).toString(Str);
  3550. }