Type.cpp 137 KB

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