SemaType.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519
  1. //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements type-related semantic analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/ScopeInfo.h"
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/Sema/Template.h"
  16. #include "clang/Basic/OpenCL.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/ASTMutationListener.h"
  19. #include "clang/AST/CXXInheritance.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/TypeLocVisitor.h"
  24. #include "clang/AST/Expr.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Parse/ParseDiagnostic.h"
  29. #include "clang/Sema/DeclSpec.h"
  30. #include "clang/Sema/DelayedDiagnostic.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "llvm/ADT/SmallPtrSet.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. using namespace clang;
  35. /// isOmittedBlockReturnType - Return true if this declarator is missing a
  36. /// return type because this is a omitted return type on a block literal.
  37. static bool isOmittedBlockReturnType(const Declarator &D) {
  38. if (D.getContext() != Declarator::BlockLiteralContext ||
  39. D.getDeclSpec().hasTypeSpecifier())
  40. return false;
  41. if (D.getNumTypeObjects() == 0)
  42. return true; // ^{ ... }
  43. if (D.getNumTypeObjects() == 1 &&
  44. D.getTypeObject(0).Kind == DeclaratorChunk::Function)
  45. return true; // ^(int X, float Y) { ... }
  46. return false;
  47. }
  48. /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
  49. /// doesn't apply to the given type.
  50. static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
  51. QualType type) {
  52. bool useExpansionLoc = false;
  53. unsigned diagID = 0;
  54. switch (attr.getKind()) {
  55. case AttributeList::AT_objc_gc:
  56. diagID = diag::warn_pointer_attribute_wrong_type;
  57. useExpansionLoc = true;
  58. break;
  59. case AttributeList::AT_objc_ownership:
  60. diagID = diag::warn_objc_object_attribute_wrong_type;
  61. useExpansionLoc = true;
  62. break;
  63. default:
  64. // Assume everything else was a function attribute.
  65. diagID = diag::warn_function_attribute_wrong_type;
  66. break;
  67. }
  68. SourceLocation loc = attr.getLoc();
  69. StringRef name = attr.getName()->getName();
  70. // The GC attributes are usually written with macros; special-case them.
  71. if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
  72. if (attr.getParameterName()->isStr("strong")) {
  73. if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
  74. } else if (attr.getParameterName()->isStr("weak")) {
  75. if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
  76. }
  77. }
  78. S.Diag(loc, diagID) << name << type;
  79. }
  80. // objc_gc applies to Objective-C pointers or, otherwise, to the
  81. // smallest available pointer type (i.e. 'void*' in 'void**').
  82. #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
  83. case AttributeList::AT_objc_gc: \
  84. case AttributeList::AT_objc_ownership
  85. // Function type attributes.
  86. #define FUNCTION_TYPE_ATTRS_CASELIST \
  87. case AttributeList::AT_noreturn: \
  88. case AttributeList::AT_cdecl: \
  89. case AttributeList::AT_fastcall: \
  90. case AttributeList::AT_stdcall: \
  91. case AttributeList::AT_thiscall: \
  92. case AttributeList::AT_pascal: \
  93. case AttributeList::AT_regparm: \
  94. case AttributeList::AT_pcs \
  95. namespace {
  96. /// An object which stores processing state for the entire
  97. /// GetTypeForDeclarator process.
  98. class TypeProcessingState {
  99. Sema &sema;
  100. /// The declarator being processed.
  101. Declarator &declarator;
  102. /// The index of the declarator chunk we're currently processing.
  103. /// May be the total number of valid chunks, indicating the
  104. /// DeclSpec.
  105. unsigned chunkIndex;
  106. /// Whether there are non-trivial modifications to the decl spec.
  107. bool trivial;
  108. /// Whether we saved the attributes in the decl spec.
  109. bool hasSavedAttrs;
  110. /// The original set of attributes on the DeclSpec.
  111. SmallVector<AttributeList*, 2> savedAttrs;
  112. /// A list of attributes to diagnose the uselessness of when the
  113. /// processing is complete.
  114. SmallVector<AttributeList*, 2> ignoredTypeAttrs;
  115. public:
  116. TypeProcessingState(Sema &sema, Declarator &declarator)
  117. : sema(sema), declarator(declarator),
  118. chunkIndex(declarator.getNumTypeObjects()),
  119. trivial(true), hasSavedAttrs(false) {}
  120. Sema &getSema() const {
  121. return sema;
  122. }
  123. Declarator &getDeclarator() const {
  124. return declarator;
  125. }
  126. unsigned getCurrentChunkIndex() const {
  127. return chunkIndex;
  128. }
  129. void setCurrentChunkIndex(unsigned idx) {
  130. assert(idx <= declarator.getNumTypeObjects());
  131. chunkIndex = idx;
  132. }
  133. AttributeList *&getCurrentAttrListRef() const {
  134. assert(chunkIndex <= declarator.getNumTypeObjects());
  135. if (chunkIndex == declarator.getNumTypeObjects())
  136. return getMutableDeclSpec().getAttributes().getListRef();
  137. return declarator.getTypeObject(chunkIndex).getAttrListRef();
  138. }
  139. /// Save the current set of attributes on the DeclSpec.
  140. void saveDeclSpecAttrs() {
  141. // Don't try to save them multiple times.
  142. if (hasSavedAttrs) return;
  143. DeclSpec &spec = getMutableDeclSpec();
  144. for (AttributeList *attr = spec.getAttributes().getList(); attr;
  145. attr = attr->getNext())
  146. savedAttrs.push_back(attr);
  147. trivial &= savedAttrs.empty();
  148. hasSavedAttrs = true;
  149. }
  150. /// Record that we had nowhere to put the given type attribute.
  151. /// We will diagnose such attributes later.
  152. void addIgnoredTypeAttr(AttributeList &attr) {
  153. ignoredTypeAttrs.push_back(&attr);
  154. }
  155. /// Diagnose all the ignored type attributes, given that the
  156. /// declarator worked out to the given type.
  157. void diagnoseIgnoredTypeAttrs(QualType type) const {
  158. for (SmallVectorImpl<AttributeList*>::const_iterator
  159. i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
  160. i != e; ++i)
  161. diagnoseBadTypeAttribute(getSema(), **i, type);
  162. }
  163. ~TypeProcessingState() {
  164. if (trivial) return;
  165. restoreDeclSpecAttrs();
  166. }
  167. private:
  168. DeclSpec &getMutableDeclSpec() const {
  169. return const_cast<DeclSpec&>(declarator.getDeclSpec());
  170. }
  171. void restoreDeclSpecAttrs() {
  172. assert(hasSavedAttrs);
  173. if (savedAttrs.empty()) {
  174. getMutableDeclSpec().getAttributes().set(0);
  175. return;
  176. }
  177. getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
  178. for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
  179. savedAttrs[i]->setNext(savedAttrs[i+1]);
  180. savedAttrs.back()->setNext(0);
  181. }
  182. };
  183. /// Basically std::pair except that we really want to avoid an
  184. /// implicit operator= for safety concerns. It's also a minor
  185. /// link-time optimization for this to be a private type.
  186. struct AttrAndList {
  187. /// The attribute.
  188. AttributeList &first;
  189. /// The head of the list the attribute is currently in.
  190. AttributeList *&second;
  191. AttrAndList(AttributeList &attr, AttributeList *&head)
  192. : first(attr), second(head) {}
  193. };
  194. }
  195. namespace llvm {
  196. template <> struct isPodLike<AttrAndList> {
  197. static const bool value = true;
  198. };
  199. }
  200. static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
  201. attr.setNext(head);
  202. head = &attr;
  203. }
  204. static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
  205. if (head == &attr) {
  206. head = attr.getNext();
  207. return;
  208. }
  209. AttributeList *cur = head;
  210. while (true) {
  211. assert(cur && cur->getNext() && "ran out of attrs?");
  212. if (cur->getNext() == &attr) {
  213. cur->setNext(attr.getNext());
  214. return;
  215. }
  216. cur = cur->getNext();
  217. }
  218. }
  219. static void moveAttrFromListToList(AttributeList &attr,
  220. AttributeList *&fromList,
  221. AttributeList *&toList) {
  222. spliceAttrOutOfList(attr, fromList);
  223. spliceAttrIntoList(attr, toList);
  224. }
  225. static void processTypeAttrs(TypeProcessingState &state,
  226. QualType &type, bool isDeclSpec,
  227. AttributeList *attrs);
  228. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  229. AttributeList &attr,
  230. QualType &type);
  231. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  232. AttributeList &attr, QualType &type);
  233. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  234. AttributeList &attr, QualType &type);
  235. static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
  236. AttributeList &attr, QualType &type) {
  237. if (attr.getKind() == AttributeList::AT_objc_gc)
  238. return handleObjCGCTypeAttr(state, attr, type);
  239. assert(attr.getKind() == AttributeList::AT_objc_ownership);
  240. return handleObjCOwnershipTypeAttr(state, attr, type);
  241. }
  242. /// Given that an objc_gc attribute was written somewhere on a
  243. /// declaration *other* than on the declarator itself (for which, use
  244. /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
  245. /// didn't apply in whatever position it was written in, try to move
  246. /// it to a more appropriate position.
  247. static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
  248. AttributeList &attr,
  249. QualType type) {
  250. Declarator &declarator = state.getDeclarator();
  251. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  252. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  253. switch (chunk.Kind) {
  254. case DeclaratorChunk::Pointer:
  255. case DeclaratorChunk::BlockPointer:
  256. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  257. chunk.getAttrListRef());
  258. return;
  259. case DeclaratorChunk::Paren:
  260. case DeclaratorChunk::Array:
  261. continue;
  262. // Don't walk through these.
  263. case DeclaratorChunk::Reference:
  264. case DeclaratorChunk::Function:
  265. case DeclaratorChunk::MemberPointer:
  266. goto error;
  267. }
  268. }
  269. error:
  270. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  271. }
  272. /// Distribute an objc_gc type attribute that was written on the
  273. /// declarator.
  274. static void
  275. distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
  276. AttributeList &attr,
  277. QualType &declSpecType) {
  278. Declarator &declarator = state.getDeclarator();
  279. // objc_gc goes on the innermost pointer to something that's not a
  280. // pointer.
  281. unsigned innermost = -1U;
  282. bool considerDeclSpec = true;
  283. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  284. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  285. switch (chunk.Kind) {
  286. case DeclaratorChunk::Pointer:
  287. case DeclaratorChunk::BlockPointer:
  288. innermost = i;
  289. continue;
  290. case DeclaratorChunk::Reference:
  291. case DeclaratorChunk::MemberPointer:
  292. case DeclaratorChunk::Paren:
  293. case DeclaratorChunk::Array:
  294. continue;
  295. case DeclaratorChunk::Function:
  296. considerDeclSpec = false;
  297. goto done;
  298. }
  299. }
  300. done:
  301. // That might actually be the decl spec if we weren't blocked by
  302. // anything in the declarator.
  303. if (considerDeclSpec) {
  304. if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
  305. // Splice the attribute into the decl spec. Prevents the
  306. // attribute from being applied multiple times and gives
  307. // the source-location-filler something to work with.
  308. state.saveDeclSpecAttrs();
  309. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  310. declarator.getMutableDeclSpec().getAttributes().getListRef());
  311. return;
  312. }
  313. }
  314. // Otherwise, if we found an appropriate chunk, splice the attribute
  315. // into it.
  316. if (innermost != -1U) {
  317. moveAttrFromListToList(attr, declarator.getAttrListRef(),
  318. declarator.getTypeObject(innermost).getAttrListRef());
  319. return;
  320. }
  321. // Otherwise, diagnose when we're done building the type.
  322. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  323. state.addIgnoredTypeAttr(attr);
  324. }
  325. /// A function type attribute was written somewhere in a declaration
  326. /// *other* than on the declarator itself or in the decl spec. Given
  327. /// that it didn't apply in whatever position it was written in, try
  328. /// to move it to a more appropriate position.
  329. static void distributeFunctionTypeAttr(TypeProcessingState &state,
  330. AttributeList &attr,
  331. QualType type) {
  332. Declarator &declarator = state.getDeclarator();
  333. // Try to push the attribute from the return type of a function to
  334. // the function itself.
  335. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  336. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  337. switch (chunk.Kind) {
  338. case DeclaratorChunk::Function:
  339. moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
  340. chunk.getAttrListRef());
  341. return;
  342. case DeclaratorChunk::Paren:
  343. case DeclaratorChunk::Pointer:
  344. case DeclaratorChunk::BlockPointer:
  345. case DeclaratorChunk::Array:
  346. case DeclaratorChunk::Reference:
  347. case DeclaratorChunk::MemberPointer:
  348. continue;
  349. }
  350. }
  351. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  352. }
  353. /// Try to distribute a function type attribute to the innermost
  354. /// function chunk or type. Returns true if the attribute was
  355. /// distributed, false if no location was found.
  356. static bool
  357. distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
  358. AttributeList &attr,
  359. AttributeList *&attrList,
  360. QualType &declSpecType) {
  361. Declarator &declarator = state.getDeclarator();
  362. // Put it on the innermost function chunk, if there is one.
  363. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  364. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  365. if (chunk.Kind != DeclaratorChunk::Function) continue;
  366. moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
  367. return true;
  368. }
  369. if (handleFunctionTypeAttr(state, attr, declSpecType)) {
  370. spliceAttrOutOfList(attr, attrList);
  371. return true;
  372. }
  373. return false;
  374. }
  375. /// A function type attribute was written in the decl spec. Try to
  376. /// apply it somewhere.
  377. static void
  378. distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
  379. AttributeList &attr,
  380. QualType &declSpecType) {
  381. state.saveDeclSpecAttrs();
  382. // Try to distribute to the innermost.
  383. if (distributeFunctionTypeAttrToInnermost(state, attr,
  384. state.getCurrentAttrListRef(),
  385. declSpecType))
  386. return;
  387. // If that failed, diagnose the bad attribute when the declarator is
  388. // fully built.
  389. state.addIgnoredTypeAttr(attr);
  390. }
  391. /// A function type attribute was written on the declarator. Try to
  392. /// apply it somewhere.
  393. static void
  394. distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
  395. AttributeList &attr,
  396. QualType &declSpecType) {
  397. Declarator &declarator = state.getDeclarator();
  398. // Try to distribute to the innermost.
  399. if (distributeFunctionTypeAttrToInnermost(state, attr,
  400. declarator.getAttrListRef(),
  401. declSpecType))
  402. return;
  403. // If that failed, diagnose the bad attribute when the declarator is
  404. // fully built.
  405. spliceAttrOutOfList(attr, declarator.getAttrListRef());
  406. state.addIgnoredTypeAttr(attr);
  407. }
  408. /// \brief Given that there are attributes written on the declarator
  409. /// itself, try to distribute any type attributes to the appropriate
  410. /// declarator chunk.
  411. ///
  412. /// These are attributes like the following:
  413. /// int f ATTR;
  414. /// int (f ATTR)();
  415. /// but not necessarily this:
  416. /// int f() ATTR;
  417. static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
  418. QualType &declSpecType) {
  419. // Collect all the type attributes from the declarator itself.
  420. assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
  421. AttributeList *attr = state.getDeclarator().getAttributes();
  422. AttributeList *next;
  423. do {
  424. next = attr->getNext();
  425. switch (attr->getKind()) {
  426. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  427. distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
  428. break;
  429. case AttributeList::AT_ns_returns_retained:
  430. if (!state.getSema().getLangOpts().ObjCAutoRefCount)
  431. break;
  432. // fallthrough
  433. FUNCTION_TYPE_ATTRS_CASELIST:
  434. distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
  435. break;
  436. default:
  437. break;
  438. }
  439. } while ((attr = next));
  440. }
  441. /// Add a synthetic '()' to a block-literal declarator if it is
  442. /// required, given the return type.
  443. static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
  444. QualType declSpecType) {
  445. Declarator &declarator = state.getDeclarator();
  446. // First, check whether the declarator would produce a function,
  447. // i.e. whether the innermost semantic chunk is a function.
  448. if (declarator.isFunctionDeclarator()) {
  449. // If so, make that declarator a prototyped declarator.
  450. declarator.getFunctionTypeInfo().hasPrototype = true;
  451. return;
  452. }
  453. // If there are any type objects, the type as written won't name a
  454. // function, regardless of the decl spec type. This is because a
  455. // block signature declarator is always an abstract-declarator, and
  456. // abstract-declarators can't just be parentheses chunks. Therefore
  457. // we need to build a function chunk unless there are no type
  458. // objects and the decl spec type is a function.
  459. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
  460. return;
  461. // Note that there *are* cases with invalid declarators where
  462. // declarators consist solely of parentheses. In general, these
  463. // occur only in failed efforts to make function declarators, so
  464. // faking up the function chunk is still the right thing to do.
  465. // Otherwise, we need to fake up a function declarator.
  466. SourceLocation loc = declarator.getLocStart();
  467. // ...and *prepend* it to the declarator.
  468. declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
  469. /*proto*/ true,
  470. /*variadic*/ false, SourceLocation(),
  471. /*args*/ 0, 0,
  472. /*type quals*/ 0,
  473. /*ref-qualifier*/true, SourceLocation(),
  474. /*const qualifier*/SourceLocation(),
  475. /*volatile qualifier*/SourceLocation(),
  476. /*mutable qualifier*/SourceLocation(),
  477. /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0, 0,
  478. /*parens*/ loc, loc,
  479. declarator));
  480. // For consistency, make sure the state still has us as processing
  481. // the decl spec.
  482. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
  483. state.setCurrentChunkIndex(declarator.getNumTypeObjects());
  484. }
  485. /// \brief Convert the specified declspec to the appropriate type
  486. /// object.
  487. /// \param D the declarator containing the declaration specifier.
  488. /// \returns The type described by the declaration specifiers. This function
  489. /// never returns null.
  490. static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
  491. // FIXME: Should move the logic from DeclSpec::Finish to here for validity
  492. // checking.
  493. Sema &S = state.getSema();
  494. Declarator &declarator = state.getDeclarator();
  495. const DeclSpec &DS = declarator.getDeclSpec();
  496. SourceLocation DeclLoc = declarator.getIdentifierLoc();
  497. if (DeclLoc.isInvalid())
  498. DeclLoc = DS.getLocStart();
  499. ASTContext &Context = S.Context;
  500. QualType Result;
  501. switch (DS.getTypeSpecType()) {
  502. case DeclSpec::TST_void:
  503. Result = Context.VoidTy;
  504. break;
  505. case DeclSpec::TST_char:
  506. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  507. Result = Context.CharTy;
  508. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
  509. Result = Context.SignedCharTy;
  510. else {
  511. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  512. "Unknown TSS value");
  513. Result = Context.UnsignedCharTy;
  514. }
  515. break;
  516. case DeclSpec::TST_wchar:
  517. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  518. Result = Context.WCharTy;
  519. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
  520. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  521. << DS.getSpecifierName(DS.getTypeSpecType());
  522. Result = Context.getSignedWCharType();
  523. } else {
  524. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  525. "Unknown TSS value");
  526. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  527. << DS.getSpecifierName(DS.getTypeSpecType());
  528. Result = Context.getUnsignedWCharType();
  529. }
  530. break;
  531. case DeclSpec::TST_char16:
  532. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  533. "Unknown TSS value");
  534. Result = Context.Char16Ty;
  535. break;
  536. case DeclSpec::TST_char32:
  537. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  538. "Unknown TSS value");
  539. Result = Context.Char32Ty;
  540. break;
  541. case DeclSpec::TST_unspecified:
  542. // "<proto1,proto2>" is an objc qualified ID with a missing id.
  543. if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
  544. Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
  545. (ObjCProtocolDecl**)PQ,
  546. DS.getNumProtocolQualifiers());
  547. Result = Context.getObjCObjectPointerType(Result);
  548. break;
  549. }
  550. // If this is a missing declspec in a block literal return context, then it
  551. // is inferred from the return statements inside the block.
  552. // The declspec is always missing in a lambda expr context; it is either
  553. // specified with a trailing return type or inferred.
  554. if (declarator.getContext() == Declarator::LambdaExprContext ||
  555. isOmittedBlockReturnType(declarator)) {
  556. Result = Context.DependentTy;
  557. break;
  558. }
  559. // Unspecified typespec defaults to int in C90. However, the C90 grammar
  560. // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
  561. // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
  562. // Note that the one exception to this is function definitions, which are
  563. // allowed to be completely missing a declspec. This is handled in the
  564. // parser already though by it pretending to have seen an 'int' in this
  565. // case.
  566. if (S.getLangOpts().ImplicitInt) {
  567. // In C89 mode, we only warn if there is a completely missing declspec
  568. // when one is not allowed.
  569. if (DS.isEmpty()) {
  570. S.Diag(DeclLoc, diag::ext_missing_declspec)
  571. << DS.getSourceRange()
  572. << FixItHint::CreateInsertion(DS.getLocStart(), "int");
  573. }
  574. } else if (!DS.hasTypeSpecifier()) {
  575. // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
  576. // "At least one type specifier shall be given in the declaration
  577. // specifiers in each declaration, and in the specifier-qualifier list in
  578. // each struct declaration and type name."
  579. // FIXME: Does Microsoft really have the implicit int extension in C++?
  580. if (S.getLangOpts().CPlusPlus &&
  581. !S.getLangOpts().MicrosoftExt) {
  582. S.Diag(DeclLoc, diag::err_missing_type_specifier)
  583. << DS.getSourceRange();
  584. // When this occurs in C++ code, often something is very broken with the
  585. // value being declared, poison it as invalid so we don't get chains of
  586. // errors.
  587. declarator.setInvalidType(true);
  588. } else {
  589. S.Diag(DeclLoc, diag::ext_missing_type_specifier)
  590. << DS.getSourceRange();
  591. }
  592. }
  593. // FALL THROUGH.
  594. case DeclSpec::TST_int: {
  595. if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
  596. switch (DS.getTypeSpecWidth()) {
  597. case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
  598. case DeclSpec::TSW_short: Result = Context.ShortTy; break;
  599. case DeclSpec::TSW_long: Result = Context.LongTy; break;
  600. case DeclSpec::TSW_longlong:
  601. Result = Context.LongLongTy;
  602. // long long is a C99 feature.
  603. if (!S.getLangOpts().C99)
  604. S.Diag(DS.getTypeSpecWidthLoc(),
  605. S.getLangOpts().CPlusPlus0x ?
  606. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  607. break;
  608. }
  609. } else {
  610. switch (DS.getTypeSpecWidth()) {
  611. case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
  612. case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
  613. case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
  614. case DeclSpec::TSW_longlong:
  615. Result = Context.UnsignedLongLongTy;
  616. // long long is a C99 feature.
  617. if (!S.getLangOpts().C99)
  618. S.Diag(DS.getTypeSpecWidthLoc(),
  619. S.getLangOpts().CPlusPlus0x ?
  620. diag::warn_cxx98_compat_longlong : diag::ext_longlong);
  621. break;
  622. }
  623. }
  624. break;
  625. }
  626. case DeclSpec::TST_int128:
  627. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  628. Result = Context.UnsignedInt128Ty;
  629. else
  630. Result = Context.Int128Ty;
  631. break;
  632. case DeclSpec::TST_half: Result = Context.HalfTy; break;
  633. case DeclSpec::TST_float: Result = Context.FloatTy; break;
  634. case DeclSpec::TST_double:
  635. if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
  636. Result = Context.LongDoubleTy;
  637. else
  638. Result = Context.DoubleTy;
  639. if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
  640. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
  641. declarator.setInvalidType(true);
  642. }
  643. break;
  644. case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
  645. case DeclSpec::TST_decimal32: // _Decimal32
  646. case DeclSpec::TST_decimal64: // _Decimal64
  647. case DeclSpec::TST_decimal128: // _Decimal128
  648. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
  649. Result = Context.IntTy;
  650. declarator.setInvalidType(true);
  651. break;
  652. case DeclSpec::TST_class:
  653. case DeclSpec::TST_enum:
  654. case DeclSpec::TST_union:
  655. case DeclSpec::TST_struct: {
  656. TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
  657. if (!D) {
  658. // This can happen in C++ with ambiguous lookups.
  659. Result = Context.IntTy;
  660. declarator.setInvalidType(true);
  661. break;
  662. }
  663. // If the type is deprecated or unavailable, diagnose it.
  664. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
  665. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  666. DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
  667. // TypeQuals handled by caller.
  668. Result = Context.getTypeDeclType(D);
  669. // In both C and C++, make an ElaboratedType.
  670. ElaboratedTypeKeyword Keyword
  671. = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
  672. Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
  673. break;
  674. }
  675. case DeclSpec::TST_typename: {
  676. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  677. DS.getTypeSpecSign() == 0 &&
  678. "Can't handle qualifiers on typedef names yet!");
  679. Result = S.GetTypeFromParser(DS.getRepAsType());
  680. if (Result.isNull())
  681. declarator.setInvalidType(true);
  682. else if (DeclSpec::ProtocolQualifierListTy PQ
  683. = DS.getProtocolQualifiers()) {
  684. if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
  685. // Silently drop any existing protocol qualifiers.
  686. // TODO: determine whether that's the right thing to do.
  687. if (ObjT->getNumProtocols())
  688. Result = ObjT->getBaseType();
  689. if (DS.getNumProtocolQualifiers())
  690. Result = Context.getObjCObjectType(Result,
  691. (ObjCProtocolDecl**) PQ,
  692. DS.getNumProtocolQualifiers());
  693. } else if (Result->isObjCIdType()) {
  694. // id<protocol-list>
  695. Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
  696. (ObjCProtocolDecl**) PQ,
  697. DS.getNumProtocolQualifiers());
  698. Result = Context.getObjCObjectPointerType(Result);
  699. } else if (Result->isObjCClassType()) {
  700. // Class<protocol-list>
  701. Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
  702. (ObjCProtocolDecl**) PQ,
  703. DS.getNumProtocolQualifiers());
  704. Result = Context.getObjCObjectPointerType(Result);
  705. } else {
  706. S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
  707. << DS.getSourceRange();
  708. declarator.setInvalidType(true);
  709. }
  710. }
  711. // TypeQuals handled by caller.
  712. break;
  713. }
  714. case DeclSpec::TST_typeofType:
  715. // FIXME: Preserve type source info.
  716. Result = S.GetTypeFromParser(DS.getRepAsType());
  717. assert(!Result.isNull() && "Didn't get a type for typeof?");
  718. if (!Result->isDependentType())
  719. if (const TagType *TT = Result->getAs<TagType>())
  720. S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
  721. // TypeQuals handled by caller.
  722. Result = Context.getTypeOfType(Result);
  723. break;
  724. case DeclSpec::TST_typeofExpr: {
  725. Expr *E = DS.getRepAsExpr();
  726. assert(E && "Didn't get an expression for typeof?");
  727. // TypeQuals handled by caller.
  728. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
  729. if (Result.isNull()) {
  730. Result = Context.IntTy;
  731. declarator.setInvalidType(true);
  732. }
  733. break;
  734. }
  735. case DeclSpec::TST_decltype: {
  736. Expr *E = DS.getRepAsExpr();
  737. assert(E && "Didn't get an expression for decltype?");
  738. // TypeQuals handled by caller.
  739. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
  740. if (Result.isNull()) {
  741. Result = Context.IntTy;
  742. declarator.setInvalidType(true);
  743. }
  744. break;
  745. }
  746. case DeclSpec::TST_underlyingType:
  747. Result = S.GetTypeFromParser(DS.getRepAsType());
  748. assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
  749. Result = S.BuildUnaryTransformType(Result,
  750. UnaryTransformType::EnumUnderlyingType,
  751. DS.getTypeSpecTypeLoc());
  752. if (Result.isNull()) {
  753. Result = Context.IntTy;
  754. declarator.setInvalidType(true);
  755. }
  756. break;
  757. case DeclSpec::TST_auto: {
  758. // TypeQuals handled by caller.
  759. Result = Context.getAutoType(QualType());
  760. break;
  761. }
  762. case DeclSpec::TST_unknown_anytype:
  763. Result = Context.UnknownAnyTy;
  764. break;
  765. case DeclSpec::TST_atomic:
  766. Result = S.GetTypeFromParser(DS.getRepAsType());
  767. assert(!Result.isNull() && "Didn't get a type for _Atomic?");
  768. Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
  769. if (Result.isNull()) {
  770. Result = Context.IntTy;
  771. declarator.setInvalidType(true);
  772. }
  773. break;
  774. case DeclSpec::TST_error:
  775. Result = Context.IntTy;
  776. declarator.setInvalidType(true);
  777. break;
  778. }
  779. // Handle complex types.
  780. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
  781. if (S.getLangOpts().Freestanding)
  782. S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
  783. Result = Context.getComplexType(Result);
  784. } else if (DS.isTypeAltiVecVector()) {
  785. unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
  786. assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
  787. VectorType::VectorKind VecKind = VectorType::AltiVecVector;
  788. if (DS.isTypeAltiVecPixel())
  789. VecKind = VectorType::AltiVecPixel;
  790. else if (DS.isTypeAltiVecBool())
  791. VecKind = VectorType::AltiVecBool;
  792. Result = Context.getVectorType(Result, 128/typeSize, VecKind);
  793. }
  794. // FIXME: Imaginary.
  795. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
  796. S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
  797. // Before we process any type attributes, synthesize a block literal
  798. // function declarator if necessary.
  799. if (declarator.getContext() == Declarator::BlockLiteralContext)
  800. maybeSynthesizeBlockSignature(state, Result);
  801. // Apply any type attributes from the decl spec. This may cause the
  802. // list of type attributes to be temporarily saved while the type
  803. // attributes are pushed around.
  804. if (AttributeList *attrs = DS.getAttributes().getList())
  805. processTypeAttrs(state, Result, true, attrs);
  806. // Apply const/volatile/restrict qualifiers to T.
  807. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  808. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  809. // or incomplete types shall not be restrict-qualified." C++ also allows
  810. // restrict-qualified references.
  811. if (TypeQuals & DeclSpec::TQ_restrict) {
  812. if (Result->isAnyPointerType() || Result->isReferenceType()) {
  813. QualType EltTy;
  814. if (Result->isObjCObjectPointerType())
  815. EltTy = Result;
  816. else
  817. EltTy = Result->isPointerType() ?
  818. Result->getAs<PointerType>()->getPointeeType() :
  819. Result->getAs<ReferenceType>()->getPointeeType();
  820. // If we have a pointer or reference, the pointee must have an object
  821. // incomplete type.
  822. if (!EltTy->isIncompleteOrObjectType()) {
  823. S.Diag(DS.getRestrictSpecLoc(),
  824. diag::err_typecheck_invalid_restrict_invalid_pointee)
  825. << EltTy << DS.getSourceRange();
  826. TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
  827. }
  828. } else {
  829. S.Diag(DS.getRestrictSpecLoc(),
  830. diag::err_typecheck_invalid_restrict_not_pointer)
  831. << Result << DS.getSourceRange();
  832. TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
  833. }
  834. }
  835. // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
  836. // of a function type includes any type qualifiers, the behavior is
  837. // undefined."
  838. if (Result->isFunctionType() && TypeQuals) {
  839. // Get some location to point at, either the C or V location.
  840. SourceLocation Loc;
  841. if (TypeQuals & DeclSpec::TQ_const)
  842. Loc = DS.getConstSpecLoc();
  843. else if (TypeQuals & DeclSpec::TQ_volatile)
  844. Loc = DS.getVolatileSpecLoc();
  845. else {
  846. assert((TypeQuals & DeclSpec::TQ_restrict) &&
  847. "Has CVR quals but not C, V, or R?");
  848. Loc = DS.getRestrictSpecLoc();
  849. }
  850. S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
  851. << Result << DS.getSourceRange();
  852. }
  853. // C++ [dcl.ref]p1:
  854. // Cv-qualified references are ill-formed except when the
  855. // cv-qualifiers are introduced through the use of a typedef
  856. // (7.1.3) or of a template type argument (14.3), in which
  857. // case the cv-qualifiers are ignored.
  858. // FIXME: Shouldn't we be checking SCS_typedef here?
  859. if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  860. TypeQuals && Result->isReferenceType()) {
  861. TypeQuals &= ~DeclSpec::TQ_const;
  862. TypeQuals &= ~DeclSpec::TQ_volatile;
  863. }
  864. // C90 6.5.3 constraints: "The same type qualifier shall not appear more
  865. // than once in the same specifier-list or qualifier-list, either directly
  866. // or via one or more typedefs."
  867. if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
  868. && TypeQuals & Result.getCVRQualifiers()) {
  869. if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
  870. S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
  871. << "const";
  872. }
  873. if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
  874. S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
  875. << "volatile";
  876. }
  877. // C90 doesn't have restrict, so it doesn't force us to produce a warning
  878. // in this case.
  879. }
  880. Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
  881. Result = Context.getQualifiedType(Result, Quals);
  882. }
  883. return Result;
  884. }
  885. static std::string getPrintableNameForEntity(DeclarationName Entity) {
  886. if (Entity)
  887. return Entity.getAsString();
  888. return "type name";
  889. }
  890. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  891. Qualifiers Qs) {
  892. // Enforce C99 6.7.3p2: "Types other than pointer types derived from
  893. // object or incomplete types shall not be restrict-qualified."
  894. if (Qs.hasRestrict()) {
  895. unsigned DiagID = 0;
  896. QualType ProblemTy;
  897. const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
  898. if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
  899. if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
  900. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  901. ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
  902. }
  903. } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
  904. if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
  905. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  906. ProblemTy = T->getAs<PointerType>()->getPointeeType();
  907. }
  908. } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
  909. if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
  910. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  911. ProblemTy = T->getAs<PointerType>()->getPointeeType();
  912. }
  913. } else if (!Ty->isDependentType()) {
  914. // FIXME: this deserves a proper diagnostic
  915. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  916. ProblemTy = T;
  917. }
  918. if (DiagID) {
  919. Diag(Loc, DiagID) << ProblemTy;
  920. Qs.removeRestrict();
  921. }
  922. }
  923. return Context.getQualifiedType(T, Qs);
  924. }
  925. /// \brief Build a paren type including \p T.
  926. QualType Sema::BuildParenType(QualType T) {
  927. return Context.getParenType(T);
  928. }
  929. /// Given that we're building a pointer or reference to the given
  930. static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
  931. SourceLocation loc,
  932. bool isReference) {
  933. // Bail out if retention is unrequired or already specified.
  934. if (!type->isObjCLifetimeType() ||
  935. type.getObjCLifetime() != Qualifiers::OCL_None)
  936. return type;
  937. Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
  938. // If the object type is const-qualified, we can safely use
  939. // __unsafe_unretained. This is safe (because there are no read
  940. // barriers), and it'll be safe to coerce anything but __weak* to
  941. // the resulting type.
  942. if (type.isConstQualified()) {
  943. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  944. // Otherwise, check whether the static type does not require
  945. // retaining. This currently only triggers for Class (possibly
  946. // protocol-qualifed, and arrays thereof).
  947. } else if (type->isObjCARCImplicitlyUnretainedType()) {
  948. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  949. // If we are in an unevaluated context, like sizeof, skip adding a
  950. // qualification.
  951. } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
  952. return type;
  953. // If that failed, give an error and recover using __strong. __strong
  954. // is the option most likely to prevent spurious second-order diagnostics,
  955. // like when binding a reference to a field.
  956. } else {
  957. // These types can show up in private ivars in system headers, so
  958. // we need this to not be an error in those cases. Instead we
  959. // want to delay.
  960. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  961. S.DelayedDiagnostics.add(
  962. sema::DelayedDiagnostic::makeForbiddenType(loc,
  963. diag::err_arc_indirect_no_ownership, type, isReference));
  964. } else {
  965. S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
  966. }
  967. implicitLifetime = Qualifiers::OCL_Strong;
  968. }
  969. assert(implicitLifetime && "didn't infer any lifetime!");
  970. Qualifiers qs;
  971. qs.addObjCLifetime(implicitLifetime);
  972. return S.Context.getQualifiedType(type, qs);
  973. }
  974. /// \brief Build a pointer type.
  975. ///
  976. /// \param T The type to which we'll be building a pointer.
  977. ///
  978. /// \param Loc The location of the entity whose type involves this
  979. /// pointer type or, if there is no such entity, the location of the
  980. /// type that will have pointer type.
  981. ///
  982. /// \param Entity The name of the entity that involves the pointer
  983. /// type, if known.
  984. ///
  985. /// \returns A suitable pointer type, if there are no
  986. /// errors. Otherwise, returns a NULL type.
  987. QualType Sema::BuildPointerType(QualType T,
  988. SourceLocation Loc, DeclarationName Entity) {
  989. if (T->isReferenceType()) {
  990. // C++ 8.3.2p4: There shall be no ... pointers to references ...
  991. Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
  992. << getPrintableNameForEntity(Entity) << T;
  993. return QualType();
  994. }
  995. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  996. // In ARC, it is forbidden to build pointers to unqualified pointers.
  997. if (getLangOpts().ObjCAutoRefCount)
  998. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
  999. // Build the pointer type.
  1000. return Context.getPointerType(T);
  1001. }
  1002. /// \brief Build a reference type.
  1003. ///
  1004. /// \param T The type to which we'll be building a reference.
  1005. ///
  1006. /// \param Loc The location of the entity whose type involves this
  1007. /// reference type or, if there is no such entity, the location of the
  1008. /// type that will have reference type.
  1009. ///
  1010. /// \param Entity The name of the entity that involves the reference
  1011. /// type, if known.
  1012. ///
  1013. /// \returns A suitable reference type, if there are no
  1014. /// errors. Otherwise, returns a NULL type.
  1015. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
  1016. SourceLocation Loc,
  1017. DeclarationName Entity) {
  1018. assert(Context.getCanonicalType(T) != Context.OverloadTy &&
  1019. "Unresolved overloaded function type");
  1020. // C++0x [dcl.ref]p6:
  1021. // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
  1022. // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
  1023. // type T, an attempt to create the type "lvalue reference to cv TR" creates
  1024. // the type "lvalue reference to T", while an attempt to create the type
  1025. // "rvalue reference to cv TR" creates the type TR.
  1026. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
  1027. // C++ [dcl.ref]p4: There shall be no references to references.
  1028. //
  1029. // According to C++ DR 106, references to references are only
  1030. // diagnosed when they are written directly (e.g., "int & &"),
  1031. // but not when they happen via a typedef:
  1032. //
  1033. // typedef int& intref;
  1034. // typedef intref& intref2;
  1035. //
  1036. // Parser::ParseDeclaratorInternal diagnoses the case where
  1037. // references are written directly; here, we handle the
  1038. // collapsing of references-to-references as described in C++0x.
  1039. // DR 106 and 540 introduce reference-collapsing into C++98/03.
  1040. // C++ [dcl.ref]p1:
  1041. // A declarator that specifies the type "reference to cv void"
  1042. // is ill-formed.
  1043. if (T->isVoidType()) {
  1044. Diag(Loc, diag::err_reference_to_void);
  1045. return QualType();
  1046. }
  1047. // In ARC, it is forbidden to build references to unqualified pointers.
  1048. if (getLangOpts().ObjCAutoRefCount)
  1049. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
  1050. // Handle restrict on references.
  1051. if (LValueRef)
  1052. return Context.getLValueReferenceType(T, SpelledAsLValue);
  1053. return Context.getRValueReferenceType(T);
  1054. }
  1055. /// Check whether the specified array size makes the array type a VLA. If so,
  1056. /// return true, if not, return the size of the array in SizeVal.
  1057. static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
  1058. // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
  1059. // (like gnu99, but not c99) accept any evaluatable value as an extension.
  1060. return S.VerifyIntegerConstantExpression(
  1061. ArraySize, &SizeVal, S.PDiag(), S.LangOpts.GNUMode,
  1062. S.PDiag(diag::ext_vla_folded_to_constant)).isInvalid();
  1063. }
  1064. /// \brief Build an array type.
  1065. ///
  1066. /// \param T The type of each element in the array.
  1067. ///
  1068. /// \param ASM C99 array size modifier (e.g., '*', 'static').
  1069. ///
  1070. /// \param ArraySize Expression describing the size of the array.
  1071. ///
  1072. /// \param Loc The location of the entity whose type involves this
  1073. /// array type or, if there is no such entity, the location of the
  1074. /// type that will have array type.
  1075. ///
  1076. /// \param Entity The name of the entity that involves the array
  1077. /// type, if known.
  1078. ///
  1079. /// \returns A suitable array type, if there are no errors. Otherwise,
  1080. /// returns a NULL type.
  1081. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
  1082. Expr *ArraySize, unsigned Quals,
  1083. SourceRange Brackets, DeclarationName Entity) {
  1084. SourceLocation Loc = Brackets.getBegin();
  1085. if (getLangOpts().CPlusPlus) {
  1086. // C++ [dcl.array]p1:
  1087. // T is called the array element type; this type shall not be a reference
  1088. // type, the (possibly cv-qualified) type void, a function type or an
  1089. // abstract class type.
  1090. //
  1091. // Note: function types are handled in the common path with C.
  1092. if (T->isReferenceType()) {
  1093. Diag(Loc, diag::err_illegal_decl_array_of_references)
  1094. << getPrintableNameForEntity(Entity) << T;
  1095. return QualType();
  1096. }
  1097. if (T->isVoidType()) {
  1098. Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
  1099. return QualType();
  1100. }
  1101. if (RequireNonAbstractType(Brackets.getBegin(), T,
  1102. diag::err_array_of_abstract_type))
  1103. return QualType();
  1104. } else {
  1105. // C99 6.7.5.2p1: If the element type is an incomplete or function type,
  1106. // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
  1107. if (RequireCompleteType(Loc, T,
  1108. diag::err_illegal_decl_array_incomplete_type))
  1109. return QualType();
  1110. }
  1111. if (T->isFunctionType()) {
  1112. Diag(Loc, diag::err_illegal_decl_array_of_functions)
  1113. << getPrintableNameForEntity(Entity) << T;
  1114. return QualType();
  1115. }
  1116. if (T->getContainedAutoType()) {
  1117. Diag(Loc, diag::err_illegal_decl_array_of_auto)
  1118. << getPrintableNameForEntity(Entity) << T;
  1119. return QualType();
  1120. }
  1121. if (const RecordType *EltTy = T->getAs<RecordType>()) {
  1122. // If the element type is a struct or union that contains a variadic
  1123. // array, accept it as a GNU extension: C99 6.7.2.1p2.
  1124. if (EltTy->getDecl()->hasFlexibleArrayMember())
  1125. Diag(Loc, diag::ext_flexible_array_in_array) << T;
  1126. } else if (T->isObjCObjectType()) {
  1127. Diag(Loc, diag::err_objc_array_of_interfaces) << T;
  1128. return QualType();
  1129. }
  1130. // Do placeholder conversions on the array size expression.
  1131. if (ArraySize && ArraySize->hasPlaceholderType()) {
  1132. ExprResult Result = CheckPlaceholderExpr(ArraySize);
  1133. if (Result.isInvalid()) return QualType();
  1134. ArraySize = Result.take();
  1135. }
  1136. // Do lvalue-to-rvalue conversions on the array size expression.
  1137. if (ArraySize && !ArraySize->isRValue()) {
  1138. ExprResult Result = DefaultLvalueConversion(ArraySize);
  1139. if (Result.isInvalid())
  1140. return QualType();
  1141. ArraySize = Result.take();
  1142. }
  1143. // C99 6.7.5.2p1: The size expression shall have integer type.
  1144. // C++11 allows contextual conversions to such types.
  1145. if (!getLangOpts().CPlusPlus0x &&
  1146. ArraySize && !ArraySize->isTypeDependent() &&
  1147. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1148. Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
  1149. << ArraySize->getType() << ArraySize->getSourceRange();
  1150. return QualType();
  1151. }
  1152. llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
  1153. if (!ArraySize) {
  1154. if (ASM == ArrayType::Star)
  1155. T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
  1156. else
  1157. T = Context.getIncompleteArrayType(T, ASM, Quals);
  1158. } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
  1159. T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
  1160. } else if ((!T->isDependentType() && !T->isIncompleteType() &&
  1161. !T->isConstantSizeType()) ||
  1162. isArraySizeVLA(*this, ArraySize, ConstVal)) {
  1163. // Even in C++11, don't allow contextual conversions in the array bound
  1164. // of a VLA.
  1165. if (getLangOpts().CPlusPlus0x &&
  1166. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1167. Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
  1168. << ArraySize->getType() << ArraySize->getSourceRange();
  1169. return QualType();
  1170. }
  1171. // C99: an array with an element type that has a non-constant-size is a VLA.
  1172. // C99: an array with a non-ICE size is a VLA. We accept any expression
  1173. // that we can fold to a non-zero positive value as an extension.
  1174. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1175. } else {
  1176. // C99 6.7.5.2p1: If the expression is a constant expression, it shall
  1177. // have a value greater than zero.
  1178. if (ConstVal.isSigned() && ConstVal.isNegative()) {
  1179. if (Entity)
  1180. Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
  1181. << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
  1182. else
  1183. Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
  1184. << ArraySize->getSourceRange();
  1185. return QualType();
  1186. }
  1187. if (ConstVal == 0) {
  1188. // GCC accepts zero sized static arrays. We allow them when
  1189. // we're not in a SFINAE context.
  1190. Diag(ArraySize->getLocStart(),
  1191. isSFINAEContext()? diag::err_typecheck_zero_array_size
  1192. : diag::ext_typecheck_zero_array_size)
  1193. << ArraySize->getSourceRange();
  1194. if (ASM == ArrayType::Static) {
  1195. Diag(ArraySize->getLocStart(),
  1196. diag::warn_typecheck_zero_static_array_size)
  1197. << ArraySize->getSourceRange();
  1198. ASM = ArrayType::Normal;
  1199. }
  1200. } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
  1201. !T->isIncompleteType()) {
  1202. // Is the array too large?
  1203. unsigned ActiveSizeBits
  1204. = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
  1205. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
  1206. Diag(ArraySize->getLocStart(), diag::err_array_too_large)
  1207. << ConstVal.toString(10)
  1208. << ArraySize->getSourceRange();
  1209. }
  1210. T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
  1211. }
  1212. // If this is not C99, extwarn about VLA's and C99 array size modifiers.
  1213. if (!getLangOpts().C99) {
  1214. if (T->isVariableArrayType()) {
  1215. // Prohibit the use of non-POD types in VLAs.
  1216. QualType BaseT = Context.getBaseElementType(T);
  1217. if (!T->isDependentType() &&
  1218. !BaseT.isPODType(Context) &&
  1219. !BaseT->isObjCLifetimeType()) {
  1220. Diag(Loc, diag::err_vla_non_pod)
  1221. << BaseT;
  1222. return QualType();
  1223. }
  1224. // Prohibit the use of VLAs during template argument deduction.
  1225. else if (isSFINAEContext()) {
  1226. Diag(Loc, diag::err_vla_in_sfinae);
  1227. return QualType();
  1228. }
  1229. // Just extwarn about VLAs.
  1230. else
  1231. Diag(Loc, diag::ext_vla);
  1232. } else if (ASM != ArrayType::Normal || Quals != 0)
  1233. Diag(Loc,
  1234. getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
  1235. : diag::ext_c99_array_usage) << ASM;
  1236. }
  1237. return T;
  1238. }
  1239. /// \brief Build an ext-vector type.
  1240. ///
  1241. /// Run the required checks for the extended vector type.
  1242. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
  1243. SourceLocation AttrLoc) {
  1244. // unlike gcc's vector_size attribute, we do not allow vectors to be defined
  1245. // in conjunction with complex types (pointers, arrays, functions, etc.).
  1246. if (!T->isDependentType() &&
  1247. !T->isIntegerType() && !T->isRealFloatingType()) {
  1248. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
  1249. return QualType();
  1250. }
  1251. if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
  1252. llvm::APSInt vecSize(32);
  1253. if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
  1254. Diag(AttrLoc, diag::err_attribute_argument_not_int)
  1255. << "ext_vector_type" << ArraySize->getSourceRange();
  1256. return QualType();
  1257. }
  1258. // unlike gcc's vector_size attribute, the size is specified as the
  1259. // number of elements, not the number of bytes.
  1260. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
  1261. if (vectorSize == 0) {
  1262. Diag(AttrLoc, diag::err_attribute_zero_size)
  1263. << ArraySize->getSourceRange();
  1264. return QualType();
  1265. }
  1266. return Context.getExtVectorType(T, vectorSize);
  1267. }
  1268. return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
  1269. }
  1270. /// \brief Build a function type.
  1271. ///
  1272. /// This routine checks the function type according to C++ rules and
  1273. /// under the assumption that the result type and parameter types have
  1274. /// just been instantiated from a template. It therefore duplicates
  1275. /// some of the behavior of GetTypeForDeclarator, but in a much
  1276. /// simpler form that is only suitable for this narrow use case.
  1277. ///
  1278. /// \param T The return type of the function.
  1279. ///
  1280. /// \param ParamTypes The parameter types of the function. This array
  1281. /// will be modified to account for adjustments to the types of the
  1282. /// function parameters.
  1283. ///
  1284. /// \param NumParamTypes The number of parameter types in ParamTypes.
  1285. ///
  1286. /// \param Variadic Whether this is a variadic function type.
  1287. ///
  1288. /// \param HasTrailingReturn Whether this function has a trailing return type.
  1289. ///
  1290. /// \param Quals The cvr-qualifiers to be applied to the function type.
  1291. ///
  1292. /// \param Loc The location of the entity whose type involves this
  1293. /// function type or, if there is no such entity, the location of the
  1294. /// type that will have function type.
  1295. ///
  1296. /// \param Entity The name of the entity that involves the function
  1297. /// type, if known.
  1298. ///
  1299. /// \returns A suitable function type, if there are no
  1300. /// errors. Otherwise, returns a NULL type.
  1301. QualType Sema::BuildFunctionType(QualType T,
  1302. QualType *ParamTypes,
  1303. unsigned NumParamTypes,
  1304. bool Variadic, bool HasTrailingReturn,
  1305. unsigned Quals,
  1306. RefQualifierKind RefQualifier,
  1307. SourceLocation Loc, DeclarationName Entity,
  1308. FunctionType::ExtInfo Info) {
  1309. if (T->isArrayType() || T->isFunctionType()) {
  1310. Diag(Loc, diag::err_func_returning_array_function)
  1311. << T->isFunctionType() << T;
  1312. return QualType();
  1313. }
  1314. // Functions cannot return half FP.
  1315. if (T->isHalfType()) {
  1316. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
  1317. FixItHint::CreateInsertion(Loc, "*");
  1318. return QualType();
  1319. }
  1320. bool Invalid = false;
  1321. for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
  1322. // FIXME: Loc is too inprecise here, should use proper locations for args.
  1323. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
  1324. if (ParamType->isVoidType()) {
  1325. Diag(Loc, diag::err_param_with_void_type);
  1326. Invalid = true;
  1327. } else if (ParamType->isHalfType()) {
  1328. // Disallow half FP arguments.
  1329. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
  1330. FixItHint::CreateInsertion(Loc, "*");
  1331. Invalid = true;
  1332. }
  1333. ParamTypes[Idx] = ParamType;
  1334. }
  1335. if (Invalid)
  1336. return QualType();
  1337. FunctionProtoType::ExtProtoInfo EPI;
  1338. EPI.Variadic = Variadic;
  1339. EPI.HasTrailingReturn = HasTrailingReturn;
  1340. EPI.TypeQuals = Quals;
  1341. EPI.RefQualifier = RefQualifier;
  1342. EPI.ExtInfo = Info;
  1343. return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
  1344. }
  1345. /// \brief Build a member pointer type \c T Class::*.
  1346. ///
  1347. /// \param T the type to which the member pointer refers.
  1348. /// \param Class the class type into which the member pointer points.
  1349. /// \param Loc the location where this type begins
  1350. /// \param Entity the name of the entity that will have this member pointer type
  1351. ///
  1352. /// \returns a member pointer type, if successful, or a NULL type if there was
  1353. /// an error.
  1354. QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
  1355. SourceLocation Loc,
  1356. DeclarationName Entity) {
  1357. // Verify that we're not building a pointer to pointer to function with
  1358. // exception specification.
  1359. if (CheckDistantExceptionSpec(T)) {
  1360. Diag(Loc, diag::err_distant_exception_spec);
  1361. // FIXME: If we're doing this as part of template instantiation,
  1362. // we should return immediately.
  1363. // Build the type anyway, but use the canonical type so that the
  1364. // exception specifiers are stripped off.
  1365. T = Context.getCanonicalType(T);
  1366. }
  1367. // C++ 8.3.3p3: A pointer to member shall not point to ... a member
  1368. // with reference type, or "cv void."
  1369. if (T->isReferenceType()) {
  1370. Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
  1371. << (Entity? Entity.getAsString() : "type name") << T;
  1372. return QualType();
  1373. }
  1374. if (T->isVoidType()) {
  1375. Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
  1376. << (Entity? Entity.getAsString() : "type name");
  1377. return QualType();
  1378. }
  1379. if (!Class->isDependentType() && !Class->isRecordType()) {
  1380. Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
  1381. return QualType();
  1382. }
  1383. // In the Microsoft ABI, the class is allowed to be an incomplete
  1384. // type. In such cases, the compiler makes a worst-case assumption.
  1385. // We make no such assumption right now, so emit an error if the
  1386. // class isn't a complete type.
  1387. if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
  1388. RequireCompleteType(Loc, Class, diag::err_incomplete_type))
  1389. return QualType();
  1390. return Context.getMemberPointerType(T, Class.getTypePtr());
  1391. }
  1392. /// \brief Build a block pointer type.
  1393. ///
  1394. /// \param T The type to which we'll be building a block pointer.
  1395. ///
  1396. /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
  1397. ///
  1398. /// \param Loc The location of the entity whose type involves this
  1399. /// block pointer type or, if there is no such entity, the location of the
  1400. /// type that will have block pointer type.
  1401. ///
  1402. /// \param Entity The name of the entity that involves the block pointer
  1403. /// type, if known.
  1404. ///
  1405. /// \returns A suitable block pointer type, if there are no
  1406. /// errors. Otherwise, returns a NULL type.
  1407. QualType Sema::BuildBlockPointerType(QualType T,
  1408. SourceLocation Loc,
  1409. DeclarationName Entity) {
  1410. if (!T->isFunctionType()) {
  1411. Diag(Loc, diag::err_nonfunction_block_type);
  1412. return QualType();
  1413. }
  1414. return Context.getBlockPointerType(T);
  1415. }
  1416. QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
  1417. QualType QT = Ty.get();
  1418. if (QT.isNull()) {
  1419. if (TInfo) *TInfo = 0;
  1420. return QualType();
  1421. }
  1422. TypeSourceInfo *DI = 0;
  1423. if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
  1424. QT = LIT->getType();
  1425. DI = LIT->getTypeSourceInfo();
  1426. }
  1427. if (TInfo) *TInfo = DI;
  1428. return QT;
  1429. }
  1430. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  1431. Qualifiers::ObjCLifetime ownership,
  1432. unsigned chunkIndex);
  1433. /// Given that this is the declaration of a parameter under ARC,
  1434. /// attempt to infer attributes and such for pointer-to-whatever
  1435. /// types.
  1436. static void inferARCWriteback(TypeProcessingState &state,
  1437. QualType &declSpecType) {
  1438. Sema &S = state.getSema();
  1439. Declarator &declarator = state.getDeclarator();
  1440. // TODO: should we care about decl qualifiers?
  1441. // Check whether the declarator has the expected form. We walk
  1442. // from the inside out in order to make the block logic work.
  1443. unsigned outermostPointerIndex = 0;
  1444. bool isBlockPointer = false;
  1445. unsigned numPointers = 0;
  1446. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  1447. unsigned chunkIndex = i;
  1448. DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
  1449. switch (chunk.Kind) {
  1450. case DeclaratorChunk::Paren:
  1451. // Ignore parens.
  1452. break;
  1453. case DeclaratorChunk::Reference:
  1454. case DeclaratorChunk::Pointer:
  1455. // Count the number of pointers. Treat references
  1456. // interchangeably as pointers; if they're mis-ordered, normal
  1457. // type building will discover that.
  1458. outermostPointerIndex = chunkIndex;
  1459. numPointers++;
  1460. break;
  1461. case DeclaratorChunk::BlockPointer:
  1462. // If we have a pointer to block pointer, that's an acceptable
  1463. // indirect reference; anything else is not an application of
  1464. // the rules.
  1465. if (numPointers != 1) return;
  1466. numPointers++;
  1467. outermostPointerIndex = chunkIndex;
  1468. isBlockPointer = true;
  1469. // We don't care about pointer structure in return values here.
  1470. goto done;
  1471. case DeclaratorChunk::Array: // suppress if written (id[])?
  1472. case DeclaratorChunk::Function:
  1473. case DeclaratorChunk::MemberPointer:
  1474. return;
  1475. }
  1476. }
  1477. done:
  1478. // If we have *one* pointer, then we want to throw the qualifier on
  1479. // the declaration-specifiers, which means that it needs to be a
  1480. // retainable object type.
  1481. if (numPointers == 1) {
  1482. // If it's not a retainable object type, the rule doesn't apply.
  1483. if (!declSpecType->isObjCRetainableType()) return;
  1484. // If it already has lifetime, don't do anything.
  1485. if (declSpecType.getObjCLifetime()) return;
  1486. // Otherwise, modify the type in-place.
  1487. Qualifiers qs;
  1488. if (declSpecType->isObjCARCImplicitlyUnretainedType())
  1489. qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
  1490. else
  1491. qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
  1492. declSpecType = S.Context.getQualifiedType(declSpecType, qs);
  1493. // If we have *two* pointers, then we want to throw the qualifier on
  1494. // the outermost pointer.
  1495. } else if (numPointers == 2) {
  1496. // If we don't have a block pointer, we need to check whether the
  1497. // declaration-specifiers gave us something that will turn into a
  1498. // retainable object pointer after we slap the first pointer on it.
  1499. if (!isBlockPointer && !declSpecType->isObjCObjectType())
  1500. return;
  1501. // Look for an explicit lifetime attribute there.
  1502. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
  1503. if (chunk.Kind != DeclaratorChunk::Pointer &&
  1504. chunk.Kind != DeclaratorChunk::BlockPointer)
  1505. return;
  1506. for (const AttributeList *attr = chunk.getAttrs(); attr;
  1507. attr = attr->getNext())
  1508. if (attr->getKind() == AttributeList::AT_objc_ownership)
  1509. return;
  1510. transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
  1511. outermostPointerIndex);
  1512. // Any other number of pointers/references does not trigger the rule.
  1513. } else return;
  1514. // TODO: mark whether we did this inference?
  1515. }
  1516. static void DiagnoseIgnoredQualifiers(unsigned Quals,
  1517. SourceLocation ConstQualLoc,
  1518. SourceLocation VolatileQualLoc,
  1519. SourceLocation RestrictQualLoc,
  1520. Sema& S) {
  1521. std::string QualStr;
  1522. unsigned NumQuals = 0;
  1523. SourceLocation Loc;
  1524. FixItHint ConstFixIt;
  1525. FixItHint VolatileFixIt;
  1526. FixItHint RestrictFixIt;
  1527. const SourceManager &SM = S.getSourceManager();
  1528. // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
  1529. // find a range and grow it to encompass all the qualifiers, regardless of
  1530. // the order in which they textually appear.
  1531. if (Quals & Qualifiers::Const) {
  1532. ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
  1533. QualStr = "const";
  1534. ++NumQuals;
  1535. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
  1536. Loc = ConstQualLoc;
  1537. }
  1538. if (Quals & Qualifiers::Volatile) {
  1539. VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
  1540. QualStr += (NumQuals == 0 ? "volatile" : " volatile");
  1541. ++NumQuals;
  1542. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
  1543. Loc = VolatileQualLoc;
  1544. }
  1545. if (Quals & Qualifiers::Restrict) {
  1546. RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
  1547. QualStr += (NumQuals == 0 ? "restrict" : " restrict");
  1548. ++NumQuals;
  1549. if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
  1550. Loc = RestrictQualLoc;
  1551. }
  1552. assert(NumQuals > 0 && "No known qualifiers?");
  1553. S.Diag(Loc, diag::warn_qual_return_type)
  1554. << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
  1555. }
  1556. static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
  1557. TypeSourceInfo *&ReturnTypeInfo) {
  1558. Sema &SemaRef = state.getSema();
  1559. Declarator &D = state.getDeclarator();
  1560. QualType T;
  1561. ReturnTypeInfo = 0;
  1562. // The TagDecl owned by the DeclSpec.
  1563. TagDecl *OwnedTagDecl = 0;
  1564. switch (D.getName().getKind()) {
  1565. case UnqualifiedId::IK_ImplicitSelfParam:
  1566. case UnqualifiedId::IK_OperatorFunctionId:
  1567. case UnqualifiedId::IK_Identifier:
  1568. case UnqualifiedId::IK_LiteralOperatorId:
  1569. case UnqualifiedId::IK_TemplateId:
  1570. T = ConvertDeclSpecToType(state);
  1571. if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
  1572. OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  1573. // Owned declaration is embedded in declarator.
  1574. OwnedTagDecl->setEmbeddedInDeclarator(true);
  1575. }
  1576. break;
  1577. case UnqualifiedId::IK_ConstructorName:
  1578. case UnqualifiedId::IK_ConstructorTemplateId:
  1579. case UnqualifiedId::IK_DestructorName:
  1580. // Constructors and destructors don't have return types. Use
  1581. // "void" instead.
  1582. T = SemaRef.Context.VoidTy;
  1583. break;
  1584. case UnqualifiedId::IK_ConversionFunctionId:
  1585. // The result type of a conversion function is the type that it
  1586. // converts to.
  1587. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
  1588. &ReturnTypeInfo);
  1589. break;
  1590. }
  1591. if (D.getAttributes())
  1592. distributeTypeAttrsFromDeclarator(state, T);
  1593. // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
  1594. // In C++11, a function declarator using 'auto' must have a trailing return
  1595. // type (this is checked later) and we can skip this. In other languages
  1596. // using auto, we need to check regardless.
  1597. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  1598. (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) {
  1599. int Error = -1;
  1600. switch (D.getContext()) {
  1601. case Declarator::KNRTypeListContext:
  1602. llvm_unreachable("K&R type lists aren't allowed in C++");
  1603. case Declarator::LambdaExprContext:
  1604. llvm_unreachable("Can't specify a type specifier in lambda grammar");
  1605. case Declarator::ObjCParameterContext:
  1606. case Declarator::ObjCResultContext:
  1607. case Declarator::PrototypeContext:
  1608. Error = 0; // Function prototype
  1609. break;
  1610. case Declarator::MemberContext:
  1611. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
  1612. break;
  1613. switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
  1614. case TTK_Enum: llvm_unreachable("unhandled tag kind");
  1615. case TTK_Struct: Error = 1; /* Struct member */ break;
  1616. case TTK_Union: Error = 2; /* Union member */ break;
  1617. case TTK_Class: Error = 3; /* Class member */ break;
  1618. }
  1619. break;
  1620. case Declarator::CXXCatchContext:
  1621. case Declarator::ObjCCatchContext:
  1622. Error = 4; // Exception declaration
  1623. break;
  1624. case Declarator::TemplateParamContext:
  1625. Error = 5; // Template parameter
  1626. break;
  1627. case Declarator::BlockLiteralContext:
  1628. Error = 6; // Block literal
  1629. break;
  1630. case Declarator::TemplateTypeArgContext:
  1631. Error = 7; // Template type argument
  1632. break;
  1633. case Declarator::AliasDeclContext:
  1634. case Declarator::AliasTemplateContext:
  1635. Error = 9; // Type alias
  1636. break;
  1637. case Declarator::TrailingReturnContext:
  1638. Error = 10; // Function return type
  1639. break;
  1640. case Declarator::TypeNameContext:
  1641. Error = 11; // Generic
  1642. break;
  1643. case Declarator::FileContext:
  1644. case Declarator::BlockContext:
  1645. case Declarator::ForContext:
  1646. case Declarator::ConditionContext:
  1647. case Declarator::CXXNewContext:
  1648. break;
  1649. }
  1650. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  1651. Error = 8;
  1652. // In Objective-C it is an error to use 'auto' on a function declarator.
  1653. if (D.isFunctionDeclarator())
  1654. Error = 10;
  1655. // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
  1656. // contains a trailing return type. That is only legal at the outermost
  1657. // level. Check all declarator chunks (outermost first) anyway, to give
  1658. // better diagnostics.
  1659. if (SemaRef.getLangOpts().CPlusPlus0x && Error != -1) {
  1660. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  1661. unsigned chunkIndex = e - i - 1;
  1662. state.setCurrentChunkIndex(chunkIndex);
  1663. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  1664. if (DeclType.Kind == DeclaratorChunk::Function) {
  1665. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  1666. if (FTI.TrailingReturnType) {
  1667. Error = -1;
  1668. break;
  1669. }
  1670. }
  1671. }
  1672. }
  1673. if (Error != -1) {
  1674. SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1675. diag::err_auto_not_allowed)
  1676. << Error;
  1677. T = SemaRef.Context.IntTy;
  1678. D.setInvalidType(true);
  1679. } else
  1680. SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1681. diag::warn_cxx98_compat_auto_type_specifier);
  1682. }
  1683. if (SemaRef.getLangOpts().CPlusPlus &&
  1684. OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
  1685. // Check the contexts where C++ forbids the declaration of a new class
  1686. // or enumeration in a type-specifier-seq.
  1687. switch (D.getContext()) {
  1688. case Declarator::TrailingReturnContext:
  1689. // Class and enumeration definitions are syntactically not allowed in
  1690. // trailing return types.
  1691. llvm_unreachable("parser should not have allowed this");
  1692. break;
  1693. case Declarator::FileContext:
  1694. case Declarator::MemberContext:
  1695. case Declarator::BlockContext:
  1696. case Declarator::ForContext:
  1697. case Declarator::BlockLiteralContext:
  1698. case Declarator::LambdaExprContext:
  1699. // C++11 [dcl.type]p3:
  1700. // A type-specifier-seq shall not define a class or enumeration unless
  1701. // it appears in the type-id of an alias-declaration (7.1.3) that is not
  1702. // the declaration of a template-declaration.
  1703. case Declarator::AliasDeclContext:
  1704. break;
  1705. case Declarator::AliasTemplateContext:
  1706. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1707. diag::err_type_defined_in_alias_template)
  1708. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1709. break;
  1710. case Declarator::TypeNameContext:
  1711. case Declarator::TemplateParamContext:
  1712. case Declarator::CXXNewContext:
  1713. case Declarator::CXXCatchContext:
  1714. case Declarator::ObjCCatchContext:
  1715. case Declarator::TemplateTypeArgContext:
  1716. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1717. diag::err_type_defined_in_type_specifier)
  1718. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1719. break;
  1720. case Declarator::PrototypeContext:
  1721. case Declarator::ObjCParameterContext:
  1722. case Declarator::ObjCResultContext:
  1723. case Declarator::KNRTypeListContext:
  1724. // C++ [dcl.fct]p6:
  1725. // Types shall not be defined in return or parameter types.
  1726. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1727. diag::err_type_defined_in_param_type)
  1728. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  1729. break;
  1730. case Declarator::ConditionContext:
  1731. // C++ 6.4p2:
  1732. // The type-specifier-seq shall not contain typedef and shall not declare
  1733. // a new class or enumeration.
  1734. SemaRef.Diag(OwnedTagDecl->getLocation(),
  1735. diag::err_type_defined_in_condition);
  1736. break;
  1737. }
  1738. }
  1739. return T;
  1740. }
  1741. static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
  1742. std::string Quals =
  1743. Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
  1744. switch (FnTy->getRefQualifier()) {
  1745. case RQ_None:
  1746. break;
  1747. case RQ_LValue:
  1748. if (!Quals.empty())
  1749. Quals += ' ';
  1750. Quals += '&';
  1751. break;
  1752. case RQ_RValue:
  1753. if (!Quals.empty())
  1754. Quals += ' ';
  1755. Quals += "&&";
  1756. break;
  1757. }
  1758. return Quals;
  1759. }
  1760. /// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
  1761. /// can be contained within the declarator chunk DeclType, and produce an
  1762. /// appropriate diagnostic if not.
  1763. static void checkQualifiedFunction(Sema &S, QualType T,
  1764. DeclaratorChunk &DeclType) {
  1765. // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
  1766. // cv-qualifier or a ref-qualifier can only appear at the topmost level
  1767. // of a type.
  1768. int DiagKind = -1;
  1769. switch (DeclType.Kind) {
  1770. case DeclaratorChunk::Paren:
  1771. case DeclaratorChunk::MemberPointer:
  1772. // These cases are permitted.
  1773. return;
  1774. case DeclaratorChunk::Array:
  1775. case DeclaratorChunk::Function:
  1776. // These cases don't allow function types at all; no need to diagnose the
  1777. // qualifiers separately.
  1778. return;
  1779. case DeclaratorChunk::BlockPointer:
  1780. DiagKind = 0;
  1781. break;
  1782. case DeclaratorChunk::Pointer:
  1783. DiagKind = 1;
  1784. break;
  1785. case DeclaratorChunk::Reference:
  1786. DiagKind = 2;
  1787. break;
  1788. }
  1789. assert(DiagKind != -1);
  1790. S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
  1791. << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
  1792. << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
  1793. }
  1794. static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
  1795. QualType declSpecType,
  1796. TypeSourceInfo *TInfo) {
  1797. QualType T = declSpecType;
  1798. Declarator &D = state.getDeclarator();
  1799. Sema &S = state.getSema();
  1800. ASTContext &Context = S.Context;
  1801. const LangOptions &LangOpts = S.getLangOpts();
  1802. bool ImplicitlyNoexcept = false;
  1803. if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
  1804. LangOpts.CPlusPlus0x) {
  1805. OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
  1806. /// In C++0x, deallocation functions (normal and array operator delete)
  1807. /// are implicitly noexcept.
  1808. if (OO == OO_Delete || OO == OO_Array_Delete)
  1809. ImplicitlyNoexcept = true;
  1810. }
  1811. // The name we're declaring, if any.
  1812. DeclarationName Name;
  1813. if (D.getIdentifier())
  1814. Name = D.getIdentifier();
  1815. // Does this declaration declare a typedef-name?
  1816. bool IsTypedefName =
  1817. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
  1818. D.getContext() == Declarator::AliasDeclContext ||
  1819. D.getContext() == Declarator::AliasTemplateContext;
  1820. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  1821. bool IsQualifiedFunction = T->isFunctionProtoType() &&
  1822. (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
  1823. T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
  1824. // Walk the DeclTypeInfo, building the recursive type as we go.
  1825. // DeclTypeInfos are ordered from the identifier out, which is
  1826. // opposite of what we want :).
  1827. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  1828. unsigned chunkIndex = e - i - 1;
  1829. state.setCurrentChunkIndex(chunkIndex);
  1830. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  1831. if (IsQualifiedFunction) {
  1832. checkQualifiedFunction(S, T, DeclType);
  1833. IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
  1834. }
  1835. switch (DeclType.Kind) {
  1836. case DeclaratorChunk::Paren:
  1837. T = S.BuildParenType(T);
  1838. break;
  1839. case DeclaratorChunk::BlockPointer:
  1840. // If blocks are disabled, emit an error.
  1841. if (!LangOpts.Blocks)
  1842. S.Diag(DeclType.Loc, diag::err_blocks_disable);
  1843. T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
  1844. if (DeclType.Cls.TypeQuals)
  1845. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
  1846. break;
  1847. case DeclaratorChunk::Pointer:
  1848. // Verify that we're not building a pointer to pointer to function with
  1849. // exception specification.
  1850. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1851. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1852. D.setInvalidType(true);
  1853. // Build the type anyway.
  1854. }
  1855. if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
  1856. T = Context.getObjCObjectPointerType(T);
  1857. if (DeclType.Ptr.TypeQuals)
  1858. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  1859. break;
  1860. }
  1861. T = S.BuildPointerType(T, DeclType.Loc, Name);
  1862. if (DeclType.Ptr.TypeQuals)
  1863. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  1864. break;
  1865. case DeclaratorChunk::Reference: {
  1866. // Verify that we're not building a reference to pointer to function with
  1867. // exception specification.
  1868. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1869. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1870. D.setInvalidType(true);
  1871. // Build the type anyway.
  1872. }
  1873. T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
  1874. Qualifiers Quals;
  1875. if (DeclType.Ref.HasRestrict)
  1876. T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
  1877. break;
  1878. }
  1879. case DeclaratorChunk::Array: {
  1880. // Verify that we're not building an array of pointers to function with
  1881. // exception specification.
  1882. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  1883. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  1884. D.setInvalidType(true);
  1885. // Build the type anyway.
  1886. }
  1887. DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
  1888. Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
  1889. ArrayType::ArraySizeModifier ASM;
  1890. if (ATI.isStar)
  1891. ASM = ArrayType::Star;
  1892. else if (ATI.hasStatic)
  1893. ASM = ArrayType::Static;
  1894. else
  1895. ASM = ArrayType::Normal;
  1896. if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
  1897. // FIXME: This check isn't quite right: it allows star in prototypes
  1898. // for function definitions, and disallows some edge cases detailed
  1899. // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
  1900. S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
  1901. ASM = ArrayType::Normal;
  1902. D.setInvalidType(true);
  1903. }
  1904. T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
  1905. SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
  1906. break;
  1907. }
  1908. case DeclaratorChunk::Function: {
  1909. // If the function declarator has a prototype (i.e. it is not () and
  1910. // does not have a K&R-style identifier list), then the arguments are part
  1911. // of the type, otherwise the argument list is ().
  1912. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  1913. IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
  1914. // Check for auto functions and trailing return type and adjust the
  1915. // return type accordingly.
  1916. if (!D.isInvalidType()) {
  1917. // trailing-return-type is only required if we're declaring a function,
  1918. // and not, for instance, a pointer to a function.
  1919. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  1920. !FTI.TrailingReturnType && chunkIndex == 0) {
  1921. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1922. diag::err_auto_missing_trailing_return);
  1923. T = Context.IntTy;
  1924. D.setInvalidType(true);
  1925. } else if (FTI.TrailingReturnType) {
  1926. // T must be exactly 'auto' at this point. See CWG issue 681.
  1927. if (isa<ParenType>(T)) {
  1928. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1929. diag::err_trailing_return_in_parens)
  1930. << T << D.getDeclSpec().getSourceRange();
  1931. D.setInvalidType(true);
  1932. } else if (D.getContext() != Declarator::LambdaExprContext &&
  1933. (T.hasQualifiers() || !isa<AutoType>(T))) {
  1934. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  1935. diag::err_trailing_return_without_auto)
  1936. << T << D.getDeclSpec().getSourceRange();
  1937. D.setInvalidType(true);
  1938. }
  1939. T = S.GetTypeFromParser(
  1940. ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
  1941. &TInfo);
  1942. }
  1943. }
  1944. // C99 6.7.5.3p1: The return type may not be a function or array type.
  1945. // For conversion functions, we'll diagnose this particular error later.
  1946. if ((T->isArrayType() || T->isFunctionType()) &&
  1947. (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
  1948. unsigned diagID = diag::err_func_returning_array_function;
  1949. // Last processing chunk in block context means this function chunk
  1950. // represents the block.
  1951. if (chunkIndex == 0 &&
  1952. D.getContext() == Declarator::BlockLiteralContext)
  1953. diagID = diag::err_block_returning_array_function;
  1954. S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
  1955. T = Context.IntTy;
  1956. D.setInvalidType(true);
  1957. }
  1958. // Do not allow returning half FP value.
  1959. // FIXME: This really should be in BuildFunctionType.
  1960. if (T->isHalfType()) {
  1961. S.Diag(D.getIdentifierLoc(),
  1962. diag::err_parameters_retval_cannot_have_fp16_type) << 1
  1963. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  1964. D.setInvalidType(true);
  1965. }
  1966. // cv-qualifiers on return types are pointless except when the type is a
  1967. // class type in C++.
  1968. if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
  1969. (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
  1970. (!LangOpts.CPlusPlus || !T->isDependentType())) {
  1971. assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
  1972. DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
  1973. assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
  1974. DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
  1975. DiagnoseIgnoredQualifiers(PTI.TypeQuals,
  1976. SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
  1977. SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
  1978. SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
  1979. S);
  1980. } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
  1981. (!LangOpts.CPlusPlus ||
  1982. (!T->isDependentType() && !T->isRecordType()))) {
  1983. DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
  1984. D.getDeclSpec().getConstSpecLoc(),
  1985. D.getDeclSpec().getVolatileSpecLoc(),
  1986. D.getDeclSpec().getRestrictSpecLoc(),
  1987. S);
  1988. }
  1989. if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
  1990. // C++ [dcl.fct]p6:
  1991. // Types shall not be defined in return or parameter types.
  1992. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  1993. if (Tag->isCompleteDefinition())
  1994. S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
  1995. << Context.getTypeDeclType(Tag);
  1996. }
  1997. // Exception specs are not allowed in typedefs. Complain, but add it
  1998. // anyway.
  1999. if (IsTypedefName && FTI.getExceptionSpecType())
  2000. S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
  2001. << (D.getContext() == Declarator::AliasDeclContext ||
  2002. D.getContext() == Declarator::AliasTemplateContext);
  2003. if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
  2004. // Simple void foo(), where the incoming T is the result type.
  2005. T = Context.getFunctionNoProtoType(T);
  2006. } else {
  2007. // We allow a zero-parameter variadic function in C if the
  2008. // function is marked with the "overloadable" attribute. Scan
  2009. // for this attribute now.
  2010. if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
  2011. bool Overloadable = false;
  2012. for (const AttributeList *Attrs = D.getAttributes();
  2013. Attrs; Attrs = Attrs->getNext()) {
  2014. if (Attrs->getKind() == AttributeList::AT_overloadable) {
  2015. Overloadable = true;
  2016. break;
  2017. }
  2018. }
  2019. if (!Overloadable)
  2020. S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
  2021. }
  2022. if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
  2023. // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
  2024. // definition.
  2025. S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
  2026. D.setInvalidType(true);
  2027. break;
  2028. }
  2029. FunctionProtoType::ExtProtoInfo EPI;
  2030. EPI.Variadic = FTI.isVariadic;
  2031. EPI.HasTrailingReturn = FTI.TrailingReturnType;
  2032. EPI.TypeQuals = FTI.TypeQuals;
  2033. EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
  2034. : FTI.RefQualifierIsLValueRef? RQ_LValue
  2035. : RQ_RValue;
  2036. // Otherwise, we have a function with an argument list that is
  2037. // potentially variadic.
  2038. SmallVector<QualType, 16> ArgTys;
  2039. ArgTys.reserve(FTI.NumArgs);
  2040. SmallVector<bool, 16> ConsumedArguments;
  2041. ConsumedArguments.reserve(FTI.NumArgs);
  2042. bool HasAnyConsumedArguments = false;
  2043. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  2044. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  2045. QualType ArgTy = Param->getType();
  2046. assert(!ArgTy.isNull() && "Couldn't parse type?");
  2047. // Adjust the parameter type.
  2048. assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
  2049. "Unadjusted type?");
  2050. // Look for 'void'. void is allowed only as a single argument to a
  2051. // function with no other parameters (C99 6.7.5.3p10). We record
  2052. // int(void) as a FunctionProtoType with an empty argument list.
  2053. if (ArgTy->isVoidType()) {
  2054. // If this is something like 'float(int, void)', reject it. 'void'
  2055. // is an incomplete type (C99 6.2.5p19) and function decls cannot
  2056. // have arguments of incomplete type.
  2057. if (FTI.NumArgs != 1 || FTI.isVariadic) {
  2058. S.Diag(DeclType.Loc, diag::err_void_only_param);
  2059. ArgTy = Context.IntTy;
  2060. Param->setType(ArgTy);
  2061. } else if (FTI.ArgInfo[i].Ident) {
  2062. // Reject, but continue to parse 'int(void abc)'.
  2063. S.Diag(FTI.ArgInfo[i].IdentLoc,
  2064. diag::err_param_with_void_type);
  2065. ArgTy = Context.IntTy;
  2066. Param->setType(ArgTy);
  2067. } else {
  2068. // Reject, but continue to parse 'float(const void)'.
  2069. if (ArgTy.hasQualifiers())
  2070. S.Diag(DeclType.Loc, diag::err_void_param_qualified);
  2071. // Do not add 'void' to the ArgTys list.
  2072. break;
  2073. }
  2074. } else if (ArgTy->isHalfType()) {
  2075. // Disallow half FP arguments.
  2076. // FIXME: This really should be in BuildFunctionType.
  2077. S.Diag(Param->getLocation(),
  2078. diag::err_parameters_retval_cannot_have_fp16_type) << 0
  2079. << FixItHint::CreateInsertion(Param->getLocation(), "*");
  2080. D.setInvalidType();
  2081. } else if (!FTI.hasPrototype) {
  2082. if (ArgTy->isPromotableIntegerType()) {
  2083. ArgTy = Context.getPromotedIntegerType(ArgTy);
  2084. Param->setKNRPromoted(true);
  2085. } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
  2086. if (BTy->getKind() == BuiltinType::Float) {
  2087. ArgTy = Context.DoubleTy;
  2088. Param->setKNRPromoted(true);
  2089. }
  2090. }
  2091. }
  2092. if (LangOpts.ObjCAutoRefCount) {
  2093. bool Consumed = Param->hasAttr<NSConsumedAttr>();
  2094. ConsumedArguments.push_back(Consumed);
  2095. HasAnyConsumedArguments |= Consumed;
  2096. }
  2097. ArgTys.push_back(ArgTy);
  2098. }
  2099. if (HasAnyConsumedArguments)
  2100. EPI.ConsumedArguments = ConsumedArguments.data();
  2101. SmallVector<QualType, 4> Exceptions;
  2102. SmallVector<ParsedType, 2> DynamicExceptions;
  2103. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  2104. Expr *NoexceptExpr = 0;
  2105. if (FTI.getExceptionSpecType() == EST_Dynamic) {
  2106. // FIXME: It's rather inefficient to have to split into two vectors
  2107. // here.
  2108. unsigned N = FTI.NumExceptions;
  2109. DynamicExceptions.reserve(N);
  2110. DynamicExceptionRanges.reserve(N);
  2111. for (unsigned I = 0; I != N; ++I) {
  2112. DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
  2113. DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
  2114. }
  2115. } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
  2116. NoexceptExpr = FTI.NoexceptExpr;
  2117. }
  2118. S.checkExceptionSpecification(FTI.getExceptionSpecType(),
  2119. DynamicExceptions,
  2120. DynamicExceptionRanges,
  2121. NoexceptExpr,
  2122. Exceptions,
  2123. EPI);
  2124. if (FTI.getExceptionSpecType() == EST_None &&
  2125. ImplicitlyNoexcept && chunkIndex == 0) {
  2126. // Only the outermost chunk is marked noexcept, of course.
  2127. EPI.ExceptionSpecType = EST_BasicNoexcept;
  2128. }
  2129. T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
  2130. }
  2131. break;
  2132. }
  2133. case DeclaratorChunk::MemberPointer:
  2134. // The scope spec must refer to a class, or be dependent.
  2135. CXXScopeSpec &SS = DeclType.Mem.Scope();
  2136. QualType ClsType;
  2137. if (SS.isInvalid()) {
  2138. // Avoid emitting extra errors if we already errored on the scope.
  2139. D.setInvalidType(true);
  2140. } else if (S.isDependentScopeSpecifier(SS) ||
  2141. dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
  2142. NestedNameSpecifier *NNS
  2143. = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
  2144. NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
  2145. switch (NNS->getKind()) {
  2146. case NestedNameSpecifier::Identifier:
  2147. ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
  2148. NNS->getAsIdentifier());
  2149. break;
  2150. case NestedNameSpecifier::Namespace:
  2151. case NestedNameSpecifier::NamespaceAlias:
  2152. case NestedNameSpecifier::Global:
  2153. llvm_unreachable("Nested-name-specifier must name a type");
  2154. case NestedNameSpecifier::TypeSpec:
  2155. case NestedNameSpecifier::TypeSpecWithTemplate:
  2156. ClsType = QualType(NNS->getAsType(), 0);
  2157. // Note: if the NNS has a prefix and ClsType is a nondependent
  2158. // TemplateSpecializationType, then the NNS prefix is NOT included
  2159. // in ClsType; hence we wrap ClsType into an ElaboratedType.
  2160. // NOTE: in particular, no wrap occurs if ClsType already is an
  2161. // Elaborated, DependentName, or DependentTemplateSpecialization.
  2162. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
  2163. ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
  2164. break;
  2165. }
  2166. } else {
  2167. S.Diag(DeclType.Mem.Scope().getBeginLoc(),
  2168. diag::err_illegal_decl_mempointer_in_nonclass)
  2169. << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
  2170. << DeclType.Mem.Scope().getRange();
  2171. D.setInvalidType(true);
  2172. }
  2173. if (!ClsType.isNull())
  2174. T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
  2175. if (T.isNull()) {
  2176. T = Context.IntTy;
  2177. D.setInvalidType(true);
  2178. } else if (DeclType.Mem.TypeQuals) {
  2179. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
  2180. }
  2181. break;
  2182. }
  2183. if (T.isNull()) {
  2184. D.setInvalidType(true);
  2185. T = Context.IntTy;
  2186. }
  2187. // See if there are any attributes on this declarator chunk.
  2188. if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
  2189. processTypeAttrs(state, T, false, attrs);
  2190. }
  2191. if (LangOpts.CPlusPlus && T->isFunctionType()) {
  2192. const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
  2193. assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
  2194. // C++ 8.3.5p4:
  2195. // A cv-qualifier-seq shall only be part of the function type
  2196. // for a nonstatic member function, the function type to which a pointer
  2197. // to member refers, or the top-level function type of a function typedef
  2198. // declaration.
  2199. //
  2200. // Core issue 547 also allows cv-qualifiers on function types that are
  2201. // top-level template type arguments.
  2202. bool FreeFunction;
  2203. if (!D.getCXXScopeSpec().isSet()) {
  2204. FreeFunction = ((D.getContext() != Declarator::MemberContext &&
  2205. D.getContext() != Declarator::LambdaExprContext) ||
  2206. D.getDeclSpec().isFriendSpecified());
  2207. } else {
  2208. DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
  2209. FreeFunction = (DC && !DC->isRecord());
  2210. }
  2211. // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
  2212. // function that is not a constructor declares that function to be const.
  2213. if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
  2214. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
  2215. D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
  2216. D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
  2217. !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
  2218. // Rebuild function type adding a 'const' qualifier.
  2219. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  2220. EPI.TypeQuals |= DeclSpec::TQ_const;
  2221. T = Context.getFunctionType(FnTy->getResultType(),
  2222. FnTy->arg_type_begin(),
  2223. FnTy->getNumArgs(), EPI);
  2224. }
  2225. // C++11 [dcl.fct]p6 (w/DR1417):
  2226. // An attempt to specify a function type with a cv-qualifier-seq or a
  2227. // ref-qualifier (including by typedef-name) is ill-formed unless it is:
  2228. // - the function type for a non-static member function,
  2229. // - the function type to which a pointer to member refers,
  2230. // - the top-level function type of a function typedef declaration or
  2231. // alias-declaration,
  2232. // - the type-id in the default argument of a type-parameter, or
  2233. // - the type-id of a template-argument for a type-parameter
  2234. if (IsQualifiedFunction &&
  2235. !(!FreeFunction &&
  2236. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
  2237. !IsTypedefName &&
  2238. D.getContext() != Declarator::TemplateTypeArgContext) {
  2239. SourceLocation Loc = D.getLocStart();
  2240. SourceRange RemovalRange;
  2241. unsigned I;
  2242. if (D.isFunctionDeclarator(I)) {
  2243. SmallVector<SourceLocation, 4> RemovalLocs;
  2244. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  2245. assert(Chunk.Kind == DeclaratorChunk::Function);
  2246. if (Chunk.Fun.hasRefQualifier())
  2247. RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
  2248. if (Chunk.Fun.TypeQuals & Qualifiers::Const)
  2249. RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
  2250. if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
  2251. RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
  2252. // FIXME: We do not track the location of the __restrict qualifier.
  2253. //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
  2254. // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
  2255. if (!RemovalLocs.empty()) {
  2256. std::sort(RemovalLocs.begin(), RemovalLocs.end(),
  2257. SourceManager::LocBeforeThanCompare(S.getSourceManager()));
  2258. RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
  2259. Loc = RemovalLocs.front();
  2260. }
  2261. }
  2262. S.Diag(Loc, diag::err_invalid_qualified_function_type)
  2263. << FreeFunction << D.isFunctionDeclarator() << T
  2264. << getFunctionQualifiersAsString(FnTy)
  2265. << FixItHint::CreateRemoval(RemovalRange);
  2266. // Strip the cv-qualifiers and ref-qualifiers from the type.
  2267. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  2268. EPI.TypeQuals = 0;
  2269. EPI.RefQualifier = RQ_None;
  2270. T = Context.getFunctionType(FnTy->getResultType(),
  2271. FnTy->arg_type_begin(),
  2272. FnTy->getNumArgs(), EPI);
  2273. }
  2274. }
  2275. // Apply any undistributed attributes from the declarator.
  2276. if (!T.isNull())
  2277. if (AttributeList *attrs = D.getAttributes())
  2278. processTypeAttrs(state, T, false, attrs);
  2279. // Diagnose any ignored type attributes.
  2280. if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
  2281. // C++0x [dcl.constexpr]p9:
  2282. // A constexpr specifier used in an object declaration declares the object
  2283. // as const.
  2284. if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
  2285. T.addConst();
  2286. }
  2287. // If there was an ellipsis in the declarator, the declaration declares a
  2288. // parameter pack whose type may be a pack expansion type.
  2289. if (D.hasEllipsis() && !T.isNull()) {
  2290. // C++0x [dcl.fct]p13:
  2291. // A declarator-id or abstract-declarator containing an ellipsis shall
  2292. // only be used in a parameter-declaration. Such a parameter-declaration
  2293. // is a parameter pack (14.5.3). [...]
  2294. switch (D.getContext()) {
  2295. case Declarator::PrototypeContext:
  2296. // C++0x [dcl.fct]p13:
  2297. // [...] When it is part of a parameter-declaration-clause, the
  2298. // parameter pack is a function parameter pack (14.5.3). The type T
  2299. // of the declarator-id of the function parameter pack shall contain
  2300. // a template parameter pack; each template parameter pack in T is
  2301. // expanded by the function parameter pack.
  2302. //
  2303. // We represent function parameter packs as function parameters whose
  2304. // type is a pack expansion.
  2305. if (!T->containsUnexpandedParameterPack()) {
  2306. S.Diag(D.getEllipsisLoc(),
  2307. diag::err_function_parameter_pack_without_parameter_packs)
  2308. << T << D.getSourceRange();
  2309. D.setEllipsisLoc(SourceLocation());
  2310. } else {
  2311. T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
  2312. }
  2313. break;
  2314. case Declarator::TemplateParamContext:
  2315. // C++0x [temp.param]p15:
  2316. // If a template-parameter is a [...] is a parameter-declaration that
  2317. // declares a parameter pack (8.3.5), then the template-parameter is a
  2318. // template parameter pack (14.5.3).
  2319. //
  2320. // Note: core issue 778 clarifies that, if there are any unexpanded
  2321. // parameter packs in the type of the non-type template parameter, then
  2322. // it expands those parameter packs.
  2323. if (T->containsUnexpandedParameterPack())
  2324. T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
  2325. else
  2326. S.Diag(D.getEllipsisLoc(),
  2327. LangOpts.CPlusPlus0x
  2328. ? diag::warn_cxx98_compat_variadic_templates
  2329. : diag::ext_variadic_templates);
  2330. break;
  2331. case Declarator::FileContext:
  2332. case Declarator::KNRTypeListContext:
  2333. case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
  2334. case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
  2335. case Declarator::TypeNameContext:
  2336. case Declarator::CXXNewContext:
  2337. case Declarator::AliasDeclContext:
  2338. case Declarator::AliasTemplateContext:
  2339. case Declarator::MemberContext:
  2340. case Declarator::BlockContext:
  2341. case Declarator::ForContext:
  2342. case Declarator::ConditionContext:
  2343. case Declarator::CXXCatchContext:
  2344. case Declarator::ObjCCatchContext:
  2345. case Declarator::BlockLiteralContext:
  2346. case Declarator::LambdaExprContext:
  2347. case Declarator::TrailingReturnContext:
  2348. case Declarator::TemplateTypeArgContext:
  2349. // FIXME: We may want to allow parameter packs in block-literal contexts
  2350. // in the future.
  2351. S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
  2352. D.setEllipsisLoc(SourceLocation());
  2353. break;
  2354. }
  2355. }
  2356. if (T.isNull())
  2357. return Context.getNullTypeSourceInfo();
  2358. else if (D.isInvalidType())
  2359. return Context.getTrivialTypeSourceInfo(T);
  2360. return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
  2361. }
  2362. /// GetTypeForDeclarator - Convert the type for the specified
  2363. /// declarator to Type instances.
  2364. ///
  2365. /// The result of this call will never be null, but the associated
  2366. /// type may be a null type if there's an unrecoverable error.
  2367. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
  2368. // Determine the type of the declarator. Not all forms of declarator
  2369. // have a type.
  2370. TypeProcessingState state(*this, D);
  2371. TypeSourceInfo *ReturnTypeInfo = 0;
  2372. QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  2373. if (T.isNull())
  2374. return Context.getNullTypeSourceInfo();
  2375. if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
  2376. inferARCWriteback(state, T);
  2377. return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
  2378. }
  2379. static void transferARCOwnershipToDeclSpec(Sema &S,
  2380. QualType &declSpecTy,
  2381. Qualifiers::ObjCLifetime ownership) {
  2382. if (declSpecTy->isObjCRetainableType() &&
  2383. declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
  2384. Qualifiers qs;
  2385. qs.addObjCLifetime(ownership);
  2386. declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
  2387. }
  2388. }
  2389. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  2390. Qualifiers::ObjCLifetime ownership,
  2391. unsigned chunkIndex) {
  2392. Sema &S = state.getSema();
  2393. Declarator &D = state.getDeclarator();
  2394. // Look for an explicit lifetime attribute.
  2395. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
  2396. for (const AttributeList *attr = chunk.getAttrs(); attr;
  2397. attr = attr->getNext())
  2398. if (attr->getKind() == AttributeList::AT_objc_ownership)
  2399. return;
  2400. const char *attrStr = 0;
  2401. switch (ownership) {
  2402. case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
  2403. case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
  2404. case Qualifiers::OCL_Strong: attrStr = "strong"; break;
  2405. case Qualifiers::OCL_Weak: attrStr = "weak"; break;
  2406. case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
  2407. }
  2408. // If there wasn't one, add one (with an invalid source location
  2409. // so that we don't make an AttributedType for it).
  2410. AttributeList *attr = D.getAttributePool()
  2411. .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
  2412. /*scope*/ 0, SourceLocation(),
  2413. &S.Context.Idents.get(attrStr), SourceLocation(),
  2414. /*args*/ 0, 0,
  2415. /*declspec*/ false, /*C++0x*/ false);
  2416. spliceAttrIntoList(*attr, chunk.getAttrListRef());
  2417. // TODO: mark whether we did this inference?
  2418. }
  2419. /// \brief Used for transfering ownership in casts resulting in l-values.
  2420. static void transferARCOwnership(TypeProcessingState &state,
  2421. QualType &declSpecTy,
  2422. Qualifiers::ObjCLifetime ownership) {
  2423. Sema &S = state.getSema();
  2424. Declarator &D = state.getDeclarator();
  2425. int inner = -1;
  2426. bool hasIndirection = false;
  2427. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  2428. DeclaratorChunk &chunk = D.getTypeObject(i);
  2429. switch (chunk.Kind) {
  2430. case DeclaratorChunk::Paren:
  2431. // Ignore parens.
  2432. break;
  2433. case DeclaratorChunk::Array:
  2434. case DeclaratorChunk::Reference:
  2435. case DeclaratorChunk::Pointer:
  2436. if (inner != -1)
  2437. hasIndirection = true;
  2438. inner = i;
  2439. break;
  2440. case DeclaratorChunk::BlockPointer:
  2441. if (inner != -1)
  2442. transferARCOwnershipToDeclaratorChunk(state, ownership, i);
  2443. return;
  2444. case DeclaratorChunk::Function:
  2445. case DeclaratorChunk::MemberPointer:
  2446. return;
  2447. }
  2448. }
  2449. if (inner == -1)
  2450. return;
  2451. DeclaratorChunk &chunk = D.getTypeObject(inner);
  2452. if (chunk.Kind == DeclaratorChunk::Pointer) {
  2453. if (declSpecTy->isObjCRetainableType())
  2454. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  2455. if (declSpecTy->isObjCObjectType() && hasIndirection)
  2456. return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
  2457. } else {
  2458. assert(chunk.Kind == DeclaratorChunk::Array ||
  2459. chunk.Kind == DeclaratorChunk::Reference);
  2460. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  2461. }
  2462. }
  2463. TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
  2464. TypeProcessingState state(*this, D);
  2465. TypeSourceInfo *ReturnTypeInfo = 0;
  2466. QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  2467. if (declSpecTy.isNull())
  2468. return Context.getNullTypeSourceInfo();
  2469. if (getLangOpts().ObjCAutoRefCount) {
  2470. Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
  2471. if (ownership != Qualifiers::OCL_None)
  2472. transferARCOwnership(state, declSpecTy, ownership);
  2473. }
  2474. return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
  2475. }
  2476. /// Map an AttributedType::Kind to an AttributeList::Kind.
  2477. static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
  2478. switch (kind) {
  2479. case AttributedType::attr_address_space:
  2480. return AttributeList::AT_address_space;
  2481. case AttributedType::attr_regparm:
  2482. return AttributeList::AT_regparm;
  2483. case AttributedType::attr_vector_size:
  2484. return AttributeList::AT_vector_size;
  2485. case AttributedType::attr_neon_vector_type:
  2486. return AttributeList::AT_neon_vector_type;
  2487. case AttributedType::attr_neon_polyvector_type:
  2488. return AttributeList::AT_neon_polyvector_type;
  2489. case AttributedType::attr_objc_gc:
  2490. return AttributeList::AT_objc_gc;
  2491. case AttributedType::attr_objc_ownership:
  2492. return AttributeList::AT_objc_ownership;
  2493. case AttributedType::attr_noreturn:
  2494. return AttributeList::AT_noreturn;
  2495. case AttributedType::attr_cdecl:
  2496. return AttributeList::AT_cdecl;
  2497. case AttributedType::attr_fastcall:
  2498. return AttributeList::AT_fastcall;
  2499. case AttributedType::attr_stdcall:
  2500. return AttributeList::AT_stdcall;
  2501. case AttributedType::attr_thiscall:
  2502. return AttributeList::AT_thiscall;
  2503. case AttributedType::attr_pascal:
  2504. return AttributeList::AT_pascal;
  2505. case AttributedType::attr_pcs:
  2506. return AttributeList::AT_pcs;
  2507. }
  2508. llvm_unreachable("unexpected attribute kind!");
  2509. }
  2510. static void fillAttributedTypeLoc(AttributedTypeLoc TL,
  2511. const AttributeList *attrs) {
  2512. AttributedType::Kind kind = TL.getAttrKind();
  2513. assert(attrs && "no type attributes in the expected location!");
  2514. AttributeList::Kind parsedKind = getAttrListKind(kind);
  2515. while (attrs->getKind() != parsedKind) {
  2516. attrs = attrs->getNext();
  2517. assert(attrs && "no matching attribute in expected location!");
  2518. }
  2519. TL.setAttrNameLoc(attrs->getLoc());
  2520. if (TL.hasAttrExprOperand())
  2521. TL.setAttrExprOperand(attrs->getArg(0));
  2522. else if (TL.hasAttrEnumOperand())
  2523. TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
  2524. // FIXME: preserve this information to here.
  2525. if (TL.hasAttrOperand())
  2526. TL.setAttrOperandParensRange(SourceRange());
  2527. }
  2528. namespace {
  2529. class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
  2530. ASTContext &Context;
  2531. const DeclSpec &DS;
  2532. public:
  2533. TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
  2534. : Context(Context), DS(DS) {}
  2535. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  2536. fillAttributedTypeLoc(TL, DS.getAttributes().getList());
  2537. Visit(TL.getModifiedLoc());
  2538. }
  2539. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  2540. Visit(TL.getUnqualifiedLoc());
  2541. }
  2542. void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  2543. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  2544. }
  2545. void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  2546. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  2547. }
  2548. void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  2549. // Handle the base type, which might not have been written explicitly.
  2550. if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
  2551. TL.setHasBaseTypeAsWritten(false);
  2552. TL.getBaseLoc().initialize(Context, SourceLocation());
  2553. } else {
  2554. TL.setHasBaseTypeAsWritten(true);
  2555. Visit(TL.getBaseLoc());
  2556. }
  2557. // Protocol qualifiers.
  2558. if (DS.getProtocolQualifiers()) {
  2559. assert(TL.getNumProtocols() > 0);
  2560. assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
  2561. TL.setLAngleLoc(DS.getProtocolLAngleLoc());
  2562. TL.setRAngleLoc(DS.getSourceRange().getEnd());
  2563. for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
  2564. TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
  2565. } else {
  2566. assert(TL.getNumProtocols() == 0);
  2567. TL.setLAngleLoc(SourceLocation());
  2568. TL.setRAngleLoc(SourceLocation());
  2569. }
  2570. }
  2571. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  2572. TL.setStarLoc(SourceLocation());
  2573. Visit(TL.getPointeeLoc());
  2574. }
  2575. void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
  2576. TypeSourceInfo *TInfo = 0;
  2577. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2578. // If we got no declarator info from previous Sema routines,
  2579. // just fill with the typespec loc.
  2580. if (!TInfo) {
  2581. TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
  2582. return;
  2583. }
  2584. TypeLoc OldTL = TInfo->getTypeLoc();
  2585. if (TInfo->getType()->getAs<ElaboratedType>()) {
  2586. ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
  2587. TemplateSpecializationTypeLoc NamedTL =
  2588. cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
  2589. TL.copy(NamedTL);
  2590. }
  2591. else
  2592. TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
  2593. }
  2594. void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  2595. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
  2596. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  2597. TL.setParensRange(DS.getTypeofParensRange());
  2598. }
  2599. void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  2600. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
  2601. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  2602. TL.setParensRange(DS.getTypeofParensRange());
  2603. assert(DS.getRepAsType());
  2604. TypeSourceInfo *TInfo = 0;
  2605. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2606. TL.setUnderlyingTInfo(TInfo);
  2607. }
  2608. void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  2609. // FIXME: This holds only because we only have one unary transform.
  2610. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
  2611. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  2612. TL.setParensRange(DS.getTypeofParensRange());
  2613. assert(DS.getRepAsType());
  2614. TypeSourceInfo *TInfo = 0;
  2615. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2616. TL.setUnderlyingTInfo(TInfo);
  2617. }
  2618. void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  2619. // By default, use the source location of the type specifier.
  2620. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
  2621. if (TL.needsExtraLocalData()) {
  2622. // Set info for the written builtin specifiers.
  2623. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
  2624. // Try to have a meaningful source location.
  2625. if (TL.getWrittenSignSpec() != TSS_unspecified)
  2626. // Sign spec loc overrides the others (e.g., 'unsigned long').
  2627. TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
  2628. else if (TL.getWrittenWidthSpec() != TSW_unspecified)
  2629. // Width spec loc overrides type spec loc (e.g., 'short int').
  2630. TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
  2631. }
  2632. }
  2633. void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  2634. ElaboratedTypeKeyword Keyword
  2635. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  2636. if (DS.getTypeSpecType() == TST_typename) {
  2637. TypeSourceInfo *TInfo = 0;
  2638. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2639. if (TInfo) {
  2640. TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
  2641. return;
  2642. }
  2643. }
  2644. TL.setElaboratedKeywordLoc(Keyword != ETK_None
  2645. ? DS.getTypeSpecTypeLoc()
  2646. : SourceLocation());
  2647. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  2648. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  2649. Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
  2650. }
  2651. void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  2652. assert(DS.getTypeSpecType() == TST_typename);
  2653. TypeSourceInfo *TInfo = 0;
  2654. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2655. assert(TInfo);
  2656. TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
  2657. }
  2658. void VisitDependentTemplateSpecializationTypeLoc(
  2659. DependentTemplateSpecializationTypeLoc TL) {
  2660. assert(DS.getTypeSpecType() == TST_typename);
  2661. TypeSourceInfo *TInfo = 0;
  2662. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2663. assert(TInfo);
  2664. TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
  2665. TInfo->getTypeLoc()));
  2666. }
  2667. void VisitTagTypeLoc(TagTypeLoc TL) {
  2668. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  2669. }
  2670. void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  2671. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  2672. TL.setParensRange(DS.getTypeofParensRange());
  2673. TypeSourceInfo *TInfo = 0;
  2674. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  2675. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  2676. }
  2677. void VisitTypeLoc(TypeLoc TL) {
  2678. // FIXME: add other typespec types and change this to an assert.
  2679. TL.initialize(Context, DS.getTypeSpecTypeLoc());
  2680. }
  2681. };
  2682. class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
  2683. ASTContext &Context;
  2684. const DeclaratorChunk &Chunk;
  2685. public:
  2686. DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
  2687. : Context(Context), Chunk(Chunk) {}
  2688. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  2689. llvm_unreachable("qualified type locs not expected here!");
  2690. }
  2691. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  2692. fillAttributedTypeLoc(TL, Chunk.getAttrs());
  2693. }
  2694. void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  2695. assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
  2696. TL.setCaretLoc(Chunk.Loc);
  2697. }
  2698. void VisitPointerTypeLoc(PointerTypeLoc TL) {
  2699. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  2700. TL.setStarLoc(Chunk.Loc);
  2701. }
  2702. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  2703. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  2704. TL.setStarLoc(Chunk.Loc);
  2705. }
  2706. void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  2707. assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
  2708. const CXXScopeSpec& SS = Chunk.Mem.Scope();
  2709. NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
  2710. const Type* ClsTy = TL.getClass();
  2711. QualType ClsQT = QualType(ClsTy, 0);
  2712. TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
  2713. // Now copy source location info into the type loc component.
  2714. TypeLoc ClsTL = ClsTInfo->getTypeLoc();
  2715. switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
  2716. case NestedNameSpecifier::Identifier:
  2717. assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
  2718. {
  2719. DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
  2720. DNTLoc.setElaboratedKeywordLoc(SourceLocation());
  2721. DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
  2722. DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
  2723. }
  2724. break;
  2725. case NestedNameSpecifier::TypeSpec:
  2726. case NestedNameSpecifier::TypeSpecWithTemplate:
  2727. if (isa<ElaboratedType>(ClsTy)) {
  2728. ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
  2729. ETLoc.setElaboratedKeywordLoc(SourceLocation());
  2730. ETLoc.setQualifierLoc(NNSLoc.getPrefix());
  2731. TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
  2732. NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
  2733. } else {
  2734. ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
  2735. }
  2736. break;
  2737. case NestedNameSpecifier::Namespace:
  2738. case NestedNameSpecifier::NamespaceAlias:
  2739. case NestedNameSpecifier::Global:
  2740. llvm_unreachable("Nested-name-specifier must name a type");
  2741. }
  2742. // Finally fill in MemberPointerLocInfo fields.
  2743. TL.setStarLoc(Chunk.Loc);
  2744. TL.setClassTInfo(ClsTInfo);
  2745. }
  2746. void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  2747. assert(Chunk.Kind == DeclaratorChunk::Reference);
  2748. // 'Amp' is misleading: this might have been originally
  2749. /// spelled with AmpAmp.
  2750. TL.setAmpLoc(Chunk.Loc);
  2751. }
  2752. void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  2753. assert(Chunk.Kind == DeclaratorChunk::Reference);
  2754. assert(!Chunk.Ref.LValueRef);
  2755. TL.setAmpAmpLoc(Chunk.Loc);
  2756. }
  2757. void VisitArrayTypeLoc(ArrayTypeLoc TL) {
  2758. assert(Chunk.Kind == DeclaratorChunk::Array);
  2759. TL.setLBracketLoc(Chunk.Loc);
  2760. TL.setRBracketLoc(Chunk.EndLoc);
  2761. TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
  2762. }
  2763. void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  2764. assert(Chunk.Kind == DeclaratorChunk::Function);
  2765. TL.setLocalRangeBegin(Chunk.Loc);
  2766. TL.setLocalRangeEnd(Chunk.EndLoc);
  2767. TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
  2768. const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
  2769. for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
  2770. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  2771. TL.setArg(tpi++, Param);
  2772. }
  2773. // FIXME: exception specs
  2774. }
  2775. void VisitParenTypeLoc(ParenTypeLoc TL) {
  2776. assert(Chunk.Kind == DeclaratorChunk::Paren);
  2777. TL.setLParenLoc(Chunk.Loc);
  2778. TL.setRParenLoc(Chunk.EndLoc);
  2779. }
  2780. void VisitTypeLoc(TypeLoc TL) {
  2781. llvm_unreachable("unsupported TypeLoc kind in declarator!");
  2782. }
  2783. };
  2784. }
  2785. /// \brief Create and instantiate a TypeSourceInfo with type source information.
  2786. ///
  2787. /// \param T QualType referring to the type as written in source code.
  2788. ///
  2789. /// \param ReturnTypeInfo For declarators whose return type does not show
  2790. /// up in the normal place in the declaration specifiers (such as a C++
  2791. /// conversion function), this pointer will refer to a type source information
  2792. /// for that return type.
  2793. TypeSourceInfo *
  2794. Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
  2795. TypeSourceInfo *ReturnTypeInfo) {
  2796. TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
  2797. UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
  2798. // Handle parameter packs whose type is a pack expansion.
  2799. if (isa<PackExpansionType>(T)) {
  2800. cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
  2801. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  2802. }
  2803. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  2804. while (isa<AttributedTypeLoc>(CurrTL)) {
  2805. AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
  2806. fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
  2807. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  2808. }
  2809. DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
  2810. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  2811. }
  2812. // If we have different source information for the return type, use
  2813. // that. This really only applies to C++ conversion functions.
  2814. if (ReturnTypeInfo) {
  2815. TypeLoc TL = ReturnTypeInfo->getTypeLoc();
  2816. assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
  2817. memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
  2818. } else {
  2819. TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
  2820. }
  2821. return TInfo;
  2822. }
  2823. /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
  2824. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
  2825. // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
  2826. // and Sema during declaration parsing. Try deallocating/caching them when
  2827. // it's appropriate, instead of allocating them and keeping them around.
  2828. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
  2829. TypeAlignment);
  2830. new (LocT) LocInfoType(T, TInfo);
  2831. assert(LocT->getTypeClass() != T->getTypeClass() &&
  2832. "LocInfoType's TypeClass conflicts with an existing Type class");
  2833. return ParsedType::make(QualType(LocT, 0));
  2834. }
  2835. void LocInfoType::getAsStringInternal(std::string &Str,
  2836. const PrintingPolicy &Policy) const {
  2837. llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
  2838. " was used directly instead of getting the QualType through"
  2839. " GetTypeFromParser");
  2840. }
  2841. TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
  2842. // C99 6.7.6: Type names have no identifier. This is already validated by
  2843. // the parser.
  2844. assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
  2845. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  2846. QualType T = TInfo->getType();
  2847. if (D.isInvalidType())
  2848. return true;
  2849. // Make sure there are no unused decl attributes on the declarator.
  2850. // We don't want to do this for ObjC parameters because we're going
  2851. // to apply them to the actual parameter declaration.
  2852. if (D.getContext() != Declarator::ObjCParameterContext)
  2853. checkUnusedDeclAttributes(D);
  2854. if (getLangOpts().CPlusPlus) {
  2855. // Check that there are no default arguments (C++ only).
  2856. CheckExtraCXXDefaultArguments(D);
  2857. }
  2858. return CreateParsedType(T, TInfo);
  2859. }
  2860. ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
  2861. QualType T = Context.getObjCInstanceType();
  2862. TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  2863. return CreateParsedType(T, TInfo);
  2864. }
  2865. //===----------------------------------------------------------------------===//
  2866. // Type Attribute Processing
  2867. //===----------------------------------------------------------------------===//
  2868. /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
  2869. /// specified type. The attribute contains 1 argument, the id of the address
  2870. /// space for the type.
  2871. static void HandleAddressSpaceTypeAttribute(QualType &Type,
  2872. const AttributeList &Attr, Sema &S){
  2873. // If this type is already address space qualified, reject it.
  2874. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
  2875. // qualifiers for two or more different address spaces."
  2876. if (Type.getAddressSpace()) {
  2877. S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
  2878. Attr.setInvalid();
  2879. return;
  2880. }
  2881. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
  2882. // qualified by an address-space qualifier."
  2883. if (Type->isFunctionType()) {
  2884. S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
  2885. Attr.setInvalid();
  2886. return;
  2887. }
  2888. // Check the attribute arguments.
  2889. if (Attr.getNumArgs() != 1) {
  2890. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  2891. Attr.setInvalid();
  2892. return;
  2893. }
  2894. Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
  2895. llvm::APSInt addrSpace(32);
  2896. if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
  2897. !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
  2898. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
  2899. << ASArgExpr->getSourceRange();
  2900. Attr.setInvalid();
  2901. return;
  2902. }
  2903. // Bounds checking.
  2904. if (addrSpace.isSigned()) {
  2905. if (addrSpace.isNegative()) {
  2906. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
  2907. << ASArgExpr->getSourceRange();
  2908. Attr.setInvalid();
  2909. return;
  2910. }
  2911. addrSpace.setIsSigned(false);
  2912. }
  2913. llvm::APSInt max(addrSpace.getBitWidth());
  2914. max = Qualifiers::MaxAddressSpace;
  2915. if (addrSpace > max) {
  2916. S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
  2917. << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
  2918. Attr.setInvalid();
  2919. return;
  2920. }
  2921. unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
  2922. Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
  2923. }
  2924. /// Does this type have a "direct" ownership qualifier? That is,
  2925. /// is it written like "__strong id", as opposed to something like
  2926. /// "typeof(foo)", where that happens to be strong?
  2927. static bool hasDirectOwnershipQualifier(QualType type) {
  2928. // Fast path: no qualifier at all.
  2929. assert(type.getQualifiers().hasObjCLifetime());
  2930. while (true) {
  2931. // __strong id
  2932. if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
  2933. if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
  2934. return true;
  2935. type = attr->getModifiedType();
  2936. // X *__strong (...)
  2937. } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
  2938. type = paren->getInnerType();
  2939. // That's it for things we want to complain about. In particular,
  2940. // we do not want to look through typedefs, typeof(expr),
  2941. // typeof(type), or any other way that the type is somehow
  2942. // abstracted.
  2943. } else {
  2944. return false;
  2945. }
  2946. }
  2947. }
  2948. /// handleObjCOwnershipTypeAttr - Process an objc_ownership
  2949. /// attribute on the specified type.
  2950. ///
  2951. /// Returns 'true' if the attribute was handled.
  2952. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  2953. AttributeList &attr,
  2954. QualType &type) {
  2955. bool NonObjCPointer = false;
  2956. if (!type->isDependentType()) {
  2957. if (const PointerType *ptr = type->getAs<PointerType>()) {
  2958. QualType pointee = ptr->getPointeeType();
  2959. if (pointee->isObjCRetainableType() || pointee->isPointerType())
  2960. return false;
  2961. // It is important not to lose the source info that there was an attribute
  2962. // applied to non-objc pointer. We will create an attributed type but
  2963. // its type will be the same as the original type.
  2964. NonObjCPointer = true;
  2965. } else if (!type->isObjCRetainableType()) {
  2966. return false;
  2967. }
  2968. }
  2969. Sema &S = state.getSema();
  2970. SourceLocation AttrLoc = attr.getLoc();
  2971. if (AttrLoc.isMacroID())
  2972. AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
  2973. if (!attr.getParameterName()) {
  2974. S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
  2975. << "objc_ownership" << 1;
  2976. attr.setInvalid();
  2977. return true;
  2978. }
  2979. // Consume lifetime attributes without further comment outside of
  2980. // ARC mode.
  2981. if (!S.getLangOpts().ObjCAutoRefCount)
  2982. return true;
  2983. Qualifiers::ObjCLifetime lifetime;
  2984. if (attr.getParameterName()->isStr("none"))
  2985. lifetime = Qualifiers::OCL_ExplicitNone;
  2986. else if (attr.getParameterName()->isStr("strong"))
  2987. lifetime = Qualifiers::OCL_Strong;
  2988. else if (attr.getParameterName()->isStr("weak"))
  2989. lifetime = Qualifiers::OCL_Weak;
  2990. else if (attr.getParameterName()->isStr("autoreleasing"))
  2991. lifetime = Qualifiers::OCL_Autoreleasing;
  2992. else {
  2993. S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
  2994. << "objc_ownership" << attr.getParameterName();
  2995. attr.setInvalid();
  2996. return true;
  2997. }
  2998. SplitQualType underlyingType = type.split();
  2999. // Check for redundant/conflicting ownership qualifiers.
  3000. if (Qualifiers::ObjCLifetime previousLifetime
  3001. = type.getQualifiers().getObjCLifetime()) {
  3002. // If it's written directly, that's an error.
  3003. if (hasDirectOwnershipQualifier(type)) {
  3004. S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
  3005. << type;
  3006. return true;
  3007. }
  3008. // Otherwise, if the qualifiers actually conflict, pull sugar off
  3009. // until we reach a type that is directly qualified.
  3010. if (previousLifetime != lifetime) {
  3011. // This should always terminate: the canonical type is
  3012. // qualified, so some bit of sugar must be hiding it.
  3013. while (!underlyingType.Quals.hasObjCLifetime()) {
  3014. underlyingType = underlyingType.getSingleStepDesugaredType();
  3015. }
  3016. underlyingType.Quals.removeObjCLifetime();
  3017. }
  3018. }
  3019. underlyingType.Quals.addObjCLifetime(lifetime);
  3020. if (NonObjCPointer) {
  3021. StringRef name = attr.getName()->getName();
  3022. switch (lifetime) {
  3023. case Qualifiers::OCL_None:
  3024. case Qualifiers::OCL_ExplicitNone:
  3025. break;
  3026. case Qualifiers::OCL_Strong: name = "__strong"; break;
  3027. case Qualifiers::OCL_Weak: name = "__weak"; break;
  3028. case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
  3029. }
  3030. S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
  3031. << name << type;
  3032. }
  3033. QualType origType = type;
  3034. if (!NonObjCPointer)
  3035. type = S.Context.getQualifiedType(underlyingType);
  3036. // If we have a valid source location for the attribute, use an
  3037. // AttributedType instead.
  3038. if (AttrLoc.isValid())
  3039. type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
  3040. origType, type);
  3041. // Forbid __weak if the runtime doesn't support it.
  3042. if (lifetime == Qualifiers::OCL_Weak &&
  3043. !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) {
  3044. // Actually, delay this until we know what we're parsing.
  3045. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  3046. S.DelayedDiagnostics.add(
  3047. sema::DelayedDiagnostic::makeForbiddenType(
  3048. S.getSourceManager().getExpansionLoc(AttrLoc),
  3049. diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
  3050. } else {
  3051. S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
  3052. }
  3053. attr.setInvalid();
  3054. return true;
  3055. }
  3056. // Forbid __weak for class objects marked as
  3057. // objc_arc_weak_reference_unavailable
  3058. if (lifetime == Qualifiers::OCL_Weak) {
  3059. QualType T = type;
  3060. while (const PointerType *ptr = T->getAs<PointerType>())
  3061. T = ptr->getPointeeType();
  3062. if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
  3063. ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
  3064. if (Class->isArcWeakrefUnavailable()) {
  3065. S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
  3066. S.Diag(ObjT->getInterfaceDecl()->getLocation(),
  3067. diag::note_class_declared);
  3068. }
  3069. }
  3070. }
  3071. return true;
  3072. }
  3073. /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
  3074. /// attribute on the specified type. Returns true to indicate that
  3075. /// the attribute was handled, false to indicate that the type does
  3076. /// not permit the attribute.
  3077. static bool handleObjCGCTypeAttr(TypeProcessingState &state,
  3078. AttributeList &attr,
  3079. QualType &type) {
  3080. Sema &S = state.getSema();
  3081. // Delay if this isn't some kind of pointer.
  3082. if (!type->isPointerType() &&
  3083. !type->isObjCObjectPointerType() &&
  3084. !type->isBlockPointerType())
  3085. return false;
  3086. if (type.getObjCGCAttr() != Qualifiers::GCNone) {
  3087. S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
  3088. attr.setInvalid();
  3089. return true;
  3090. }
  3091. // Check the attribute arguments.
  3092. if (!attr.getParameterName()) {
  3093. S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
  3094. << "objc_gc" << 1;
  3095. attr.setInvalid();
  3096. return true;
  3097. }
  3098. Qualifiers::GC GCAttr;
  3099. if (attr.getNumArgs() != 0) {
  3100. S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3101. attr.setInvalid();
  3102. return true;
  3103. }
  3104. if (attr.getParameterName()->isStr("weak"))
  3105. GCAttr = Qualifiers::Weak;
  3106. else if (attr.getParameterName()->isStr("strong"))
  3107. GCAttr = Qualifiers::Strong;
  3108. else {
  3109. S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
  3110. << "objc_gc" << attr.getParameterName();
  3111. attr.setInvalid();
  3112. return true;
  3113. }
  3114. QualType origType = type;
  3115. type = S.Context.getObjCGCQualType(origType, GCAttr);
  3116. // Make an attributed type to preserve the source information.
  3117. if (attr.getLoc().isValid())
  3118. type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
  3119. origType, type);
  3120. return true;
  3121. }
  3122. namespace {
  3123. /// A helper class to unwrap a type down to a function for the
  3124. /// purposes of applying attributes there.
  3125. ///
  3126. /// Use:
  3127. /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
  3128. /// if (unwrapped.isFunctionType()) {
  3129. /// const FunctionType *fn = unwrapped.get();
  3130. /// // change fn somehow
  3131. /// T = unwrapped.wrap(fn);
  3132. /// }
  3133. struct FunctionTypeUnwrapper {
  3134. enum WrapKind {
  3135. Desugar,
  3136. Parens,
  3137. Pointer,
  3138. BlockPointer,
  3139. Reference,
  3140. MemberPointer
  3141. };
  3142. QualType Original;
  3143. const FunctionType *Fn;
  3144. SmallVector<unsigned char /*WrapKind*/, 8> Stack;
  3145. FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
  3146. while (true) {
  3147. const Type *Ty = T.getTypePtr();
  3148. if (isa<FunctionType>(Ty)) {
  3149. Fn = cast<FunctionType>(Ty);
  3150. return;
  3151. } else if (isa<ParenType>(Ty)) {
  3152. T = cast<ParenType>(Ty)->getInnerType();
  3153. Stack.push_back(Parens);
  3154. } else if (isa<PointerType>(Ty)) {
  3155. T = cast<PointerType>(Ty)->getPointeeType();
  3156. Stack.push_back(Pointer);
  3157. } else if (isa<BlockPointerType>(Ty)) {
  3158. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3159. Stack.push_back(BlockPointer);
  3160. } else if (isa<MemberPointerType>(Ty)) {
  3161. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3162. Stack.push_back(MemberPointer);
  3163. } else if (isa<ReferenceType>(Ty)) {
  3164. T = cast<ReferenceType>(Ty)->getPointeeType();
  3165. Stack.push_back(Reference);
  3166. } else {
  3167. const Type *DTy = Ty->getUnqualifiedDesugaredType();
  3168. if (Ty == DTy) {
  3169. Fn = 0;
  3170. return;
  3171. }
  3172. T = QualType(DTy, 0);
  3173. Stack.push_back(Desugar);
  3174. }
  3175. }
  3176. }
  3177. bool isFunctionType() const { return (Fn != 0); }
  3178. const FunctionType *get() const { return Fn; }
  3179. QualType wrap(Sema &S, const FunctionType *New) {
  3180. // If T wasn't modified from the unwrapped type, do nothing.
  3181. if (New == get()) return Original;
  3182. Fn = New;
  3183. return wrap(S.Context, Original, 0);
  3184. }
  3185. private:
  3186. QualType wrap(ASTContext &C, QualType Old, unsigned I) {
  3187. if (I == Stack.size())
  3188. return C.getQualifiedType(Fn, Old.getQualifiers());
  3189. // Build up the inner type, applying the qualifiers from the old
  3190. // type to the new type.
  3191. SplitQualType SplitOld = Old.split();
  3192. // As a special case, tail-recurse if there are no qualifiers.
  3193. if (SplitOld.Quals.empty())
  3194. return wrap(C, SplitOld.Ty, I);
  3195. return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
  3196. }
  3197. QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
  3198. if (I == Stack.size()) return QualType(Fn, 0);
  3199. switch (static_cast<WrapKind>(Stack[I++])) {
  3200. case Desugar:
  3201. // This is the point at which we potentially lose source
  3202. // information.
  3203. return wrap(C, Old->getUnqualifiedDesugaredType(), I);
  3204. case Parens: {
  3205. QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
  3206. return C.getParenType(New);
  3207. }
  3208. case Pointer: {
  3209. QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
  3210. return C.getPointerType(New);
  3211. }
  3212. case BlockPointer: {
  3213. QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
  3214. return C.getBlockPointerType(New);
  3215. }
  3216. case MemberPointer: {
  3217. const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
  3218. QualType New = wrap(C, OldMPT->getPointeeType(), I);
  3219. return C.getMemberPointerType(New, OldMPT->getClass());
  3220. }
  3221. case Reference: {
  3222. const ReferenceType *OldRef = cast<ReferenceType>(Old);
  3223. QualType New = wrap(C, OldRef->getPointeeType(), I);
  3224. if (isa<LValueReferenceType>(OldRef))
  3225. return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
  3226. else
  3227. return C.getRValueReferenceType(New);
  3228. }
  3229. }
  3230. llvm_unreachable("unknown wrapping kind");
  3231. }
  3232. };
  3233. }
  3234. /// Process an individual function attribute. Returns true to
  3235. /// indicate that the attribute was handled, false if it wasn't.
  3236. static bool handleFunctionTypeAttr(TypeProcessingState &state,
  3237. AttributeList &attr,
  3238. QualType &type) {
  3239. Sema &S = state.getSema();
  3240. FunctionTypeUnwrapper unwrapped(S, type);
  3241. if (attr.getKind() == AttributeList::AT_noreturn) {
  3242. if (S.CheckNoReturnAttr(attr))
  3243. return true;
  3244. // Delay if this is not a function type.
  3245. if (!unwrapped.isFunctionType())
  3246. return false;
  3247. // Otherwise we can process right away.
  3248. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
  3249. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3250. return true;
  3251. }
  3252. // ns_returns_retained is not always a type attribute, but if we got
  3253. // here, we're treating it as one right now.
  3254. if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
  3255. assert(S.getLangOpts().ObjCAutoRefCount &&
  3256. "ns_returns_retained treated as type attribute in non-ARC");
  3257. if (attr.getNumArgs()) return true;
  3258. // Delay if this is not a function type.
  3259. if (!unwrapped.isFunctionType())
  3260. return false;
  3261. FunctionType::ExtInfo EI
  3262. = unwrapped.get()->getExtInfo().withProducesResult(true);
  3263. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3264. return true;
  3265. }
  3266. if (attr.getKind() == AttributeList::AT_regparm) {
  3267. unsigned value;
  3268. if (S.CheckRegparmAttr(attr, value))
  3269. return true;
  3270. // Delay if this is not a function type.
  3271. if (!unwrapped.isFunctionType())
  3272. return false;
  3273. // Diagnose regparm with fastcall.
  3274. const FunctionType *fn = unwrapped.get();
  3275. CallingConv CC = fn->getCallConv();
  3276. if (CC == CC_X86FastCall) {
  3277. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3278. << FunctionType::getNameForCallConv(CC)
  3279. << "regparm";
  3280. attr.setInvalid();
  3281. return true;
  3282. }
  3283. FunctionType::ExtInfo EI =
  3284. unwrapped.get()->getExtInfo().withRegParm(value);
  3285. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3286. return true;
  3287. }
  3288. // Otherwise, a calling convention.
  3289. CallingConv CC;
  3290. if (S.CheckCallingConvAttr(attr, CC))
  3291. return true;
  3292. // Delay if the type didn't work out to a function.
  3293. if (!unwrapped.isFunctionType()) return false;
  3294. const FunctionType *fn = unwrapped.get();
  3295. CallingConv CCOld = fn->getCallConv();
  3296. if (S.Context.getCanonicalCallConv(CC) ==
  3297. S.Context.getCanonicalCallConv(CCOld)) {
  3298. FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
  3299. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3300. return true;
  3301. }
  3302. if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
  3303. // Should we diagnose reapplications of the same convention?
  3304. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3305. << FunctionType::getNameForCallConv(CC)
  3306. << FunctionType::getNameForCallConv(CCOld);
  3307. attr.setInvalid();
  3308. return true;
  3309. }
  3310. // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
  3311. if (CC == CC_X86FastCall) {
  3312. if (isa<FunctionNoProtoType>(fn)) {
  3313. S.Diag(attr.getLoc(), diag::err_cconv_knr)
  3314. << FunctionType::getNameForCallConv(CC);
  3315. attr.setInvalid();
  3316. return true;
  3317. }
  3318. const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
  3319. if (FnP->isVariadic()) {
  3320. S.Diag(attr.getLoc(), diag::err_cconv_varargs)
  3321. << FunctionType::getNameForCallConv(CC);
  3322. attr.setInvalid();
  3323. return true;
  3324. }
  3325. // Also diagnose fastcall with regparm.
  3326. if (fn->getHasRegParm()) {
  3327. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  3328. << "regparm"
  3329. << FunctionType::getNameForCallConv(CC);
  3330. attr.setInvalid();
  3331. return true;
  3332. }
  3333. }
  3334. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
  3335. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  3336. return true;
  3337. }
  3338. /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
  3339. static void HandleOpenCLImageAccessAttribute(QualType& CurType,
  3340. const AttributeList &Attr,
  3341. Sema &S) {
  3342. // Check the attribute arguments.
  3343. if (Attr.getNumArgs() != 1) {
  3344. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3345. Attr.setInvalid();
  3346. return;
  3347. }
  3348. Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
  3349. llvm::APSInt arg(32);
  3350. if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
  3351. !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
  3352. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3353. << "opencl_image_access" << sizeExpr->getSourceRange();
  3354. Attr.setInvalid();
  3355. return;
  3356. }
  3357. unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
  3358. switch (iarg) {
  3359. case CLIA_read_only:
  3360. case CLIA_write_only:
  3361. case CLIA_read_write:
  3362. // Implemented in a separate patch
  3363. break;
  3364. default:
  3365. // Implemented in a separate patch
  3366. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
  3367. << sizeExpr->getSourceRange();
  3368. Attr.setInvalid();
  3369. break;
  3370. }
  3371. }
  3372. /// HandleVectorSizeAttribute - this attribute is only applicable to integral
  3373. /// and float scalars, although arrays, pointers, and function return values are
  3374. /// allowed in conjunction with this construct. Aggregates with this attribute
  3375. /// are invalid, even if they are of the same size as a corresponding scalar.
  3376. /// The raw attribute should contain precisely 1 argument, the vector size for
  3377. /// the variable, measured in bytes. If curType and rawAttr are well formed,
  3378. /// this routine will return a new vector type.
  3379. static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
  3380. Sema &S) {
  3381. // Check the attribute arguments.
  3382. if (Attr.getNumArgs() != 1) {
  3383. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3384. Attr.setInvalid();
  3385. return;
  3386. }
  3387. Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
  3388. llvm::APSInt vecSize(32);
  3389. if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
  3390. !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
  3391. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3392. << "vector_size" << sizeExpr->getSourceRange();
  3393. Attr.setInvalid();
  3394. return;
  3395. }
  3396. // the base type must be integer or float, and can't already be a vector.
  3397. if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
  3398. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  3399. Attr.setInvalid();
  3400. return;
  3401. }
  3402. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  3403. // vecSize is specified in bytes - convert to bits.
  3404. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
  3405. // the vector size needs to be an integral multiple of the type size.
  3406. if (vectorSize % typeSize) {
  3407. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
  3408. << sizeExpr->getSourceRange();
  3409. Attr.setInvalid();
  3410. return;
  3411. }
  3412. if (vectorSize == 0) {
  3413. S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
  3414. << sizeExpr->getSourceRange();
  3415. Attr.setInvalid();
  3416. return;
  3417. }
  3418. // Success! Instantiate the vector type, the number of elements is > 0, and
  3419. // not required to be a power of 2, unlike GCC.
  3420. CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
  3421. VectorType::GenericVector);
  3422. }
  3423. /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
  3424. /// a type.
  3425. static void HandleExtVectorTypeAttr(QualType &CurType,
  3426. const AttributeList &Attr,
  3427. Sema &S) {
  3428. Expr *sizeExpr;
  3429. // Special case where the argument is a template id.
  3430. if (Attr.getParameterName()) {
  3431. CXXScopeSpec SS;
  3432. SourceLocation TemplateKWLoc;
  3433. UnqualifiedId id;
  3434. id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
  3435. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  3436. id, false, false);
  3437. if (Size.isInvalid())
  3438. return;
  3439. sizeExpr = Size.get();
  3440. } else {
  3441. // check the attribute arguments.
  3442. if (Attr.getNumArgs() != 1) {
  3443. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3444. return;
  3445. }
  3446. sizeExpr = Attr.getArg(0);
  3447. }
  3448. // Create the vector type.
  3449. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
  3450. if (!T.isNull())
  3451. CurType = T;
  3452. }
  3453. /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
  3454. /// "neon_polyvector_type" attributes are used to create vector types that
  3455. /// are mangled according to ARM's ABI. Otherwise, these types are identical
  3456. /// to those created with the "vector_size" attribute. Unlike "vector_size"
  3457. /// the argument to these Neon attributes is the number of vector elements,
  3458. /// not the vector size in bytes. The vector width and element type must
  3459. /// match one of the standard Neon vector types.
  3460. static void HandleNeonVectorTypeAttr(QualType& CurType,
  3461. const AttributeList &Attr, Sema &S,
  3462. VectorType::VectorKind VecKind,
  3463. const char *AttrName) {
  3464. // Check the attribute arguments.
  3465. if (Attr.getNumArgs() != 1) {
  3466. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
  3467. Attr.setInvalid();
  3468. return;
  3469. }
  3470. // The number of elements must be an ICE.
  3471. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
  3472. llvm::APSInt numEltsInt(32);
  3473. if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
  3474. !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
  3475. S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
  3476. << AttrName << numEltsExpr->getSourceRange();
  3477. Attr.setInvalid();
  3478. return;
  3479. }
  3480. // Only certain element types are supported for Neon vectors.
  3481. const BuiltinType* BTy = CurType->getAs<BuiltinType>();
  3482. if (!BTy ||
  3483. (VecKind == VectorType::NeonPolyVector &&
  3484. BTy->getKind() != BuiltinType::SChar &&
  3485. BTy->getKind() != BuiltinType::Short) ||
  3486. (BTy->getKind() != BuiltinType::SChar &&
  3487. BTy->getKind() != BuiltinType::UChar &&
  3488. BTy->getKind() != BuiltinType::Short &&
  3489. BTy->getKind() != BuiltinType::UShort &&
  3490. BTy->getKind() != BuiltinType::Int &&
  3491. BTy->getKind() != BuiltinType::UInt &&
  3492. BTy->getKind() != BuiltinType::LongLong &&
  3493. BTy->getKind() != BuiltinType::ULongLong &&
  3494. BTy->getKind() != BuiltinType::Float)) {
  3495. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
  3496. Attr.setInvalid();
  3497. return;
  3498. }
  3499. // The total size of the vector must be 64 or 128 bits.
  3500. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  3501. unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
  3502. unsigned vecSize = typeSize * numElts;
  3503. if (vecSize != 64 && vecSize != 128) {
  3504. S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
  3505. Attr.setInvalid();
  3506. return;
  3507. }
  3508. CurType = S.Context.getVectorType(CurType, numElts, VecKind);
  3509. }
  3510. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  3511. bool isDeclSpec, AttributeList *attrs) {
  3512. // Scan through and apply attributes to this type where it makes sense. Some
  3513. // attributes (such as __address_space__, __vector_size__, etc) apply to the
  3514. // type, but others can be present in the type specifiers even though they
  3515. // apply to the decl. Here we apply type attributes and ignore the rest.
  3516. AttributeList *next;
  3517. do {
  3518. AttributeList &attr = *attrs;
  3519. next = attr.getNext();
  3520. // Skip attributes that were marked to be invalid.
  3521. if (attr.isInvalid())
  3522. continue;
  3523. // If this is an attribute we can handle, do so now,
  3524. // otherwise, add it to the FnAttrs list for rechaining.
  3525. switch (attr.getKind()) {
  3526. default: break;
  3527. case AttributeList::AT_may_alias:
  3528. // FIXME: This attribute needs to actually be handled, but if we ignore
  3529. // it it breaks large amounts of Linux software.
  3530. attr.setUsedAsTypeAttr();
  3531. break;
  3532. case AttributeList::AT_address_space:
  3533. HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
  3534. attr.setUsedAsTypeAttr();
  3535. break;
  3536. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  3537. if (!handleObjCPointerTypeAttr(state, attr, type))
  3538. distributeObjCPointerTypeAttr(state, attr, type);
  3539. attr.setUsedAsTypeAttr();
  3540. break;
  3541. case AttributeList::AT_vector_size:
  3542. HandleVectorSizeAttr(type, attr, state.getSema());
  3543. attr.setUsedAsTypeAttr();
  3544. break;
  3545. case AttributeList::AT_ext_vector_type:
  3546. if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
  3547. != DeclSpec::SCS_typedef)
  3548. HandleExtVectorTypeAttr(type, attr, state.getSema());
  3549. attr.setUsedAsTypeAttr();
  3550. break;
  3551. case AttributeList::AT_neon_vector_type:
  3552. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  3553. VectorType::NeonVector, "neon_vector_type");
  3554. attr.setUsedAsTypeAttr();
  3555. break;
  3556. case AttributeList::AT_neon_polyvector_type:
  3557. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  3558. VectorType::NeonPolyVector,
  3559. "neon_polyvector_type");
  3560. attr.setUsedAsTypeAttr();
  3561. break;
  3562. case AttributeList::AT_opencl_image_access:
  3563. HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
  3564. attr.setUsedAsTypeAttr();
  3565. break;
  3566. case AttributeList::AT_ns_returns_retained:
  3567. if (!state.getSema().getLangOpts().ObjCAutoRefCount)
  3568. break;
  3569. // fallthrough into the function attrs
  3570. FUNCTION_TYPE_ATTRS_CASELIST:
  3571. attr.setUsedAsTypeAttr();
  3572. // Never process function type attributes as part of the
  3573. // declaration-specifiers.
  3574. if (isDeclSpec)
  3575. distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
  3576. // Otherwise, handle the possible delays.
  3577. else if (!handleFunctionTypeAttr(state, attr, type))
  3578. distributeFunctionTypeAttr(state, attr, type);
  3579. break;
  3580. }
  3581. } while ((attrs = next));
  3582. }
  3583. /// \brief Ensure that the type of the given expression is complete.
  3584. ///
  3585. /// This routine checks whether the expression \p E has a complete type. If the
  3586. /// expression refers to an instantiable construct, that instantiation is
  3587. /// performed as needed to complete its type. Furthermore
  3588. /// Sema::RequireCompleteType is called for the expression's type (or in the
  3589. /// case of a reference type, the referred-to type).
  3590. ///
  3591. /// \param E The expression whose type is required to be complete.
  3592. /// \param PD The partial diagnostic that will be printed out if the type cannot
  3593. /// be completed.
  3594. ///
  3595. /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
  3596. /// otherwise.
  3597. bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
  3598. std::pair<SourceLocation,
  3599. PartialDiagnostic> Note) {
  3600. QualType T = E->getType();
  3601. // Fast path the case where the type is already complete.
  3602. if (!T->isIncompleteType())
  3603. return false;
  3604. // Incomplete array types may be completed by the initializer attached to
  3605. // their definitions. For static data members of class templates we need to
  3606. // instantiate the definition to get this initializer and complete the type.
  3607. if (T->isIncompleteArrayType()) {
  3608. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3609. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  3610. if (Var->isStaticDataMember() &&
  3611. Var->getInstantiatedFromStaticDataMember()) {
  3612. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  3613. assert(MSInfo && "Missing member specialization information?");
  3614. if (MSInfo->getTemplateSpecializationKind()
  3615. != TSK_ExplicitSpecialization) {
  3616. // If we don't already have a point of instantiation, this is it.
  3617. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  3618. MSInfo->setPointOfInstantiation(E->getLocStart());
  3619. // This is a modification of an existing AST node. Notify
  3620. // listeners.
  3621. if (ASTMutationListener *L = getASTMutationListener())
  3622. L->StaticDataMemberInstantiated(Var);
  3623. }
  3624. InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
  3625. // Update the type to the newly instantiated definition's type both
  3626. // here and within the expression.
  3627. if (VarDecl *Def = Var->getDefinition()) {
  3628. DRE->setDecl(Def);
  3629. T = Def->getType();
  3630. DRE->setType(T);
  3631. E->setType(T);
  3632. }
  3633. }
  3634. // We still go on to try to complete the type independently, as it
  3635. // may also require instantiations or diagnostics if it remains
  3636. // incomplete.
  3637. }
  3638. }
  3639. }
  3640. }
  3641. // FIXME: Are there other cases which require instantiating something other
  3642. // than the type to complete the type of an expression?
  3643. // Look through reference types and complete the referred type.
  3644. if (const ReferenceType *Ref = T->getAs<ReferenceType>())
  3645. T = Ref->getPointeeType();
  3646. return RequireCompleteType(E->getExprLoc(), T, PD, Note);
  3647. }
  3648. /// @brief Ensure that the type T is a complete type.
  3649. ///
  3650. /// This routine checks whether the type @p T is complete in any
  3651. /// context where a complete type is required. If @p T is a complete
  3652. /// type, returns false. If @p T is a class template specialization,
  3653. /// this routine then attempts to perform class template
  3654. /// instantiation. If instantiation fails, or if @p T is incomplete
  3655. /// and cannot be completed, issues the diagnostic @p diag (giving it
  3656. /// the type @p T) and returns true.
  3657. ///
  3658. /// @param Loc The location in the source that the incomplete type
  3659. /// diagnostic should refer to.
  3660. ///
  3661. /// @param T The type that this routine is examining for completeness.
  3662. ///
  3663. /// @param PD The partial diagnostic that will be printed out if T is not a
  3664. /// complete type.
  3665. ///
  3666. /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
  3667. /// @c false otherwise.
  3668. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3669. const PartialDiagnostic &PD,
  3670. std::pair<SourceLocation,
  3671. PartialDiagnostic> Note) {
  3672. unsigned diag = PD.getDiagID();
  3673. // FIXME: Add this assertion to make sure we always get instantiation points.
  3674. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
  3675. // FIXME: Add this assertion to help us flush out problems with
  3676. // checking for dependent types and type-dependent expressions.
  3677. //
  3678. // assert(!T->isDependentType() &&
  3679. // "Can't ask whether a dependent type is complete");
  3680. // If we have a complete type, we're done.
  3681. NamedDecl *Def = 0;
  3682. if (!T->isIncompleteType(&Def)) {
  3683. // If we know about the definition but it is not visible, complain.
  3684. if (diag != 0 && Def && !LookupResult::isVisible(Def)) {
  3685. // Suppress this error outside of a SFINAE context if we've already
  3686. // emitted the error once for this type. There's no usefulness in
  3687. // repeating the diagnostic.
  3688. // FIXME: Add a Fix-It that imports the corresponding module or includes
  3689. // the header.
  3690. if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
  3691. Diag(Loc, diag::err_module_private_definition) << T;
  3692. Diag(Def->getLocation(), diag::note_previous_definition);
  3693. }
  3694. }
  3695. return false;
  3696. }
  3697. const TagType *Tag = T->getAs<TagType>();
  3698. const ObjCInterfaceType *IFace = 0;
  3699. if (Tag) {
  3700. // Avoid diagnosing invalid decls as incomplete.
  3701. if (Tag->getDecl()->isInvalidDecl())
  3702. return true;
  3703. // Give the external AST source a chance to complete the type.
  3704. if (Tag->getDecl()->hasExternalLexicalStorage()) {
  3705. Context.getExternalSource()->CompleteType(Tag->getDecl());
  3706. if (!Tag->isIncompleteType())
  3707. return false;
  3708. }
  3709. }
  3710. else if ((IFace = T->getAs<ObjCInterfaceType>())) {
  3711. // Avoid diagnosing invalid decls as incomplete.
  3712. if (IFace->getDecl()->isInvalidDecl())
  3713. return true;
  3714. // Give the external AST source a chance to complete the type.
  3715. if (IFace->getDecl()->hasExternalLexicalStorage()) {
  3716. Context.getExternalSource()->CompleteType(IFace->getDecl());
  3717. if (!IFace->isIncompleteType())
  3718. return false;
  3719. }
  3720. }
  3721. // If we have a class template specialization or a class member of a
  3722. // class template specialization, or an array with known size of such,
  3723. // try to instantiate it.
  3724. QualType MaybeTemplate = T;
  3725. while (const ConstantArrayType *Array
  3726. = Context.getAsConstantArrayType(MaybeTemplate))
  3727. MaybeTemplate = Array->getElementType();
  3728. if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
  3729. if (ClassTemplateSpecializationDecl *ClassTemplateSpec
  3730. = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
  3731. if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
  3732. return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
  3733. TSK_ImplicitInstantiation,
  3734. /*Complain=*/diag != 0);
  3735. } else if (CXXRecordDecl *Rec
  3736. = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
  3737. CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
  3738. if (!Rec->isBeingDefined() && Pattern) {
  3739. MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
  3740. assert(MSI && "Missing member specialization information?");
  3741. // This record was instantiated from a class within a template.
  3742. if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  3743. return InstantiateClass(Loc, Rec, Pattern,
  3744. getTemplateInstantiationArgs(Rec),
  3745. TSK_ImplicitInstantiation,
  3746. /*Complain=*/diag != 0);
  3747. }
  3748. }
  3749. }
  3750. if (diag == 0)
  3751. return true;
  3752. // We have an incomplete type. Produce a diagnostic.
  3753. Diag(Loc, PD) << T;
  3754. // If we have a note, produce it.
  3755. if (!Note.first.isInvalid())
  3756. Diag(Note.first, Note.second);
  3757. // If the type was a forward declaration of a class/struct/union
  3758. // type, produce a note.
  3759. if (Tag && !Tag->getDecl()->isInvalidDecl())
  3760. Diag(Tag->getDecl()->getLocation(),
  3761. Tag->isBeingDefined() ? diag::note_type_being_defined
  3762. : diag::note_forward_declaration)
  3763. << QualType(Tag, 0);
  3764. // If the Objective-C class was a forward declaration, produce a note.
  3765. if (IFace && !IFace->getDecl()->isInvalidDecl())
  3766. Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
  3767. return true;
  3768. }
  3769. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3770. const PartialDiagnostic &PD) {
  3771. return RequireCompleteType(Loc, T, PD,
  3772. std::make_pair(SourceLocation(), PDiag(0)));
  3773. }
  3774. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  3775. unsigned DiagID) {
  3776. return RequireCompleteType(Loc, T, PDiag(DiagID),
  3777. std::make_pair(SourceLocation(), PDiag(0)));
  3778. }
  3779. /// @brief Ensure that the type T is a literal type.
  3780. ///
  3781. /// This routine checks whether the type @p T is a literal type. If @p T is an
  3782. /// incomplete type, an attempt is made to complete it. If @p T is a literal
  3783. /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
  3784. /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
  3785. /// it the type @p T), along with notes explaining why the type is not a
  3786. /// literal type, and returns true.
  3787. ///
  3788. /// @param Loc The location in the source that the non-literal type
  3789. /// diagnostic should refer to.
  3790. ///
  3791. /// @param T The type that this routine is examining for literalness.
  3792. ///
  3793. /// @param PD The partial diagnostic that will be printed out if T is not a
  3794. /// literal type.
  3795. ///
  3796. /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
  3797. /// @c false otherwise.
  3798. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
  3799. const PartialDiagnostic &PD) {
  3800. assert(!T->isDependentType() && "type should not be dependent");
  3801. QualType ElemType = Context.getBaseElementType(T);
  3802. RequireCompleteType(Loc, ElemType, 0);
  3803. if (T->isLiteralType())
  3804. return false;
  3805. if (PD.getDiagID() == 0)
  3806. return true;
  3807. Diag(Loc, PD) << T;
  3808. if (T->isVariableArrayType())
  3809. return true;
  3810. const RecordType *RT = ElemType->getAs<RecordType>();
  3811. if (!RT)
  3812. return true;
  3813. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3814. // A partially-defined class type can't be a literal type, because a literal
  3815. // class type must have a trivial destructor (which can't be checked until
  3816. // the class definition is complete).
  3817. if (!RD->isCompleteDefinition()) {
  3818. RequireCompleteType(Loc, ElemType,
  3819. PDiag(diag::note_non_literal_incomplete) << T);
  3820. return true;
  3821. }
  3822. // If the class has virtual base classes, then it's not an aggregate, and
  3823. // cannot have any constexpr constructors or a trivial default constructor,
  3824. // so is non-literal. This is better to diagnose than the resulting absence
  3825. // of constexpr constructors.
  3826. if (RD->getNumVBases()) {
  3827. Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
  3828. << RD->isStruct() << RD->getNumVBases();
  3829. for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
  3830. E = RD->vbases_end(); I != E; ++I)
  3831. Diag(I->getLocStart(),
  3832. diag::note_constexpr_virtual_base_here) << I->getSourceRange();
  3833. } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
  3834. !RD->hasTrivialDefaultConstructor()) {
  3835. Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
  3836. } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
  3837. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  3838. E = RD->bases_end(); I != E; ++I) {
  3839. if (!I->getType()->isLiteralType()) {
  3840. Diag(I->getLocStart(),
  3841. diag::note_non_literal_base_class)
  3842. << RD << I->getType() << I->getSourceRange();
  3843. return true;
  3844. }
  3845. }
  3846. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  3847. E = RD->field_end(); I != E; ++I) {
  3848. if (!I->getType()->isLiteralType() ||
  3849. I->getType().isVolatileQualified()) {
  3850. Diag(I->getLocation(), diag::note_non_literal_field)
  3851. << RD << &*I << I->getType()
  3852. << I->getType().isVolatileQualified();
  3853. return true;
  3854. }
  3855. }
  3856. } else if (!RD->hasTrivialDestructor()) {
  3857. // All fields and bases are of literal types, so have trivial destructors.
  3858. // If this class's destructor is non-trivial it must be user-declared.
  3859. CXXDestructorDecl *Dtor = RD->getDestructor();
  3860. assert(Dtor && "class has literal fields and bases but no dtor?");
  3861. if (!Dtor)
  3862. return true;
  3863. Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
  3864. diag::note_non_literal_user_provided_dtor :
  3865. diag::note_non_literal_nontrivial_dtor) << RD;
  3866. }
  3867. return true;
  3868. }
  3869. /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
  3870. /// and qualified by the nested-name-specifier contained in SS.
  3871. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3872. const CXXScopeSpec &SS, QualType T) {
  3873. if (T.isNull())
  3874. return T;
  3875. NestedNameSpecifier *NNS;
  3876. if (SS.isValid())
  3877. NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  3878. else {
  3879. if (Keyword == ETK_None)
  3880. return T;
  3881. NNS = 0;
  3882. }
  3883. return Context.getElaboratedType(Keyword, NNS, T);
  3884. }
  3885. QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
  3886. ExprResult ER = CheckPlaceholderExpr(E);
  3887. if (ER.isInvalid()) return QualType();
  3888. E = ER.take();
  3889. if (!E->isTypeDependent()) {
  3890. QualType T = E->getType();
  3891. if (const TagType *TT = T->getAs<TagType>())
  3892. DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
  3893. }
  3894. return Context.getTypeOfExprType(E);
  3895. }
  3896. /// getDecltypeForExpr - Given an expr, will return the decltype for
  3897. /// that expression, according to the rules in C++11
  3898. /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
  3899. static QualType getDecltypeForExpr(Sema &S, Expr *E) {
  3900. if (E->isTypeDependent())
  3901. return S.Context.DependentTy;
  3902. // C++11 [dcl.type.simple]p4:
  3903. // The type denoted by decltype(e) is defined as follows:
  3904. //
  3905. // - if e is an unparenthesized id-expression or an unparenthesized class
  3906. // member access (5.2.5), decltype(e) is the type of the entity named
  3907. // by e. If there is no such entity, or if e names a set of overloaded
  3908. // functions, the program is ill-formed;
  3909. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3910. if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
  3911. return VD->getType();
  3912. }
  3913. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3914. if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3915. return FD->getType();
  3916. }
  3917. // C++11 [expr.lambda.prim]p18:
  3918. // Every occurrence of decltype((x)) where x is a possibly
  3919. // parenthesized id-expression that names an entity of automatic
  3920. // storage duration is treated as if x were transformed into an
  3921. // access to a corresponding data member of the closure type that
  3922. // would have been declared if x were an odr-use of the denoted
  3923. // entity.
  3924. using namespace sema;
  3925. if (S.getCurLambda()) {
  3926. if (isa<ParenExpr>(E)) {
  3927. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3928. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  3929. QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
  3930. if (!T.isNull())
  3931. return S.Context.getLValueReferenceType(T);
  3932. }
  3933. }
  3934. }
  3935. }
  3936. // C++11 [dcl.type.simple]p4:
  3937. // [...]
  3938. QualType T = E->getType();
  3939. switch (E->getValueKind()) {
  3940. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  3941. // type of e;
  3942. case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
  3943. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  3944. // type of e;
  3945. case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
  3946. // - otherwise, decltype(e) is the type of e.
  3947. case VK_RValue: break;
  3948. }
  3949. return T;
  3950. }
  3951. QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
  3952. ExprResult ER = CheckPlaceholderExpr(E);
  3953. if (ER.isInvalid()) return QualType();
  3954. E = ER.take();
  3955. return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
  3956. }
  3957. QualType Sema::BuildUnaryTransformType(QualType BaseType,
  3958. UnaryTransformType::UTTKind UKind,
  3959. SourceLocation Loc) {
  3960. switch (UKind) {
  3961. case UnaryTransformType::EnumUnderlyingType:
  3962. if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
  3963. Diag(Loc, diag::err_only_enums_have_underlying_types);
  3964. return QualType();
  3965. } else {
  3966. QualType Underlying = BaseType;
  3967. if (!BaseType->isDependentType()) {
  3968. EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
  3969. assert(ED && "EnumType has no EnumDecl");
  3970. DiagnoseUseOfDecl(ED, Loc);
  3971. Underlying = ED->getIntegerType();
  3972. }
  3973. assert(!Underlying.isNull());
  3974. return Context.getUnaryTransformType(BaseType, Underlying,
  3975. UnaryTransformType::EnumUnderlyingType);
  3976. }
  3977. }
  3978. llvm_unreachable("unknown unary transform type");
  3979. }
  3980. QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
  3981. if (!T->isDependentType()) {
  3982. // FIXME: It isn't entirely clear whether incomplete atomic types
  3983. // are allowed or not; for simplicity, ban them for the moment.
  3984. if (RequireCompleteType(Loc, T,
  3985. PDiag(diag::err_atomic_specifier_bad_type) << 0))
  3986. return QualType();
  3987. int DisallowedKind = -1;
  3988. if (T->isArrayType())
  3989. DisallowedKind = 1;
  3990. else if (T->isFunctionType())
  3991. DisallowedKind = 2;
  3992. else if (T->isReferenceType())
  3993. DisallowedKind = 3;
  3994. else if (T->isAtomicType())
  3995. DisallowedKind = 4;
  3996. else if (T.hasQualifiers())
  3997. DisallowedKind = 5;
  3998. else if (!T.isTriviallyCopyableType(Context))
  3999. // Some other non-trivially-copyable type (probably a C++ class)
  4000. DisallowedKind = 6;
  4001. if (DisallowedKind != -1) {
  4002. Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
  4003. return QualType();
  4004. }
  4005. // FIXME: Do we need any handling for ARC here?
  4006. }
  4007. // Build the pointer type.
  4008. return Context.getAtomicType(T);
  4009. }