ItaniumCXXABI.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381
  1. //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides C++ code generation targeting the Itanium C++ ABI. The class
  10. // in this file generates structures that follow the Itanium C++ ABI, which is
  11. // documented at:
  12. // http://www.codesourcery.com/public/cxx-abi/abi.html
  13. // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
  14. //
  15. // It also supports the closely-related ARM ABI, documented at:
  16. // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "CGCXXABI.h"
  20. #include "CGCleanup.h"
  21. #include "CGRecordLayout.h"
  22. #include "CGVTables.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenModule.h"
  25. #include "TargetInfo.h"
  26. #include "clang/CodeGen/ConstantInitBuilder.h"
  27. #include "clang/AST/Mangle.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/AST/StmtCXX.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/GlobalValue.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/Value.h"
  35. #include "llvm/Support/ScopedPrinter.h"
  36. using namespace clang;
  37. using namespace CodeGen;
  38. namespace {
  39. class ItaniumCXXABI : public CodeGen::CGCXXABI {
  40. /// VTables - All the vtables which have been defined.
  41. llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
  42. /// All the thread wrapper functions that have been used.
  43. llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
  44. ThreadWrappers;
  45. protected:
  46. bool UseARMMethodPtrABI;
  47. bool UseARMGuardVarABI;
  48. bool Use32BitVTableOffsetABI;
  49. ItaniumMangleContext &getMangleContext() {
  50. return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
  51. }
  52. public:
  53. ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
  54. bool UseARMMethodPtrABI = false,
  55. bool UseARMGuardVarABI = false) :
  56. CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
  57. UseARMGuardVarABI(UseARMGuardVarABI),
  58. Use32BitVTableOffsetABI(false) { }
  59. bool classifyReturnType(CGFunctionInfo &FI) const override;
  60. RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
  61. // If C++ prohibits us from making a copy, pass by address.
  62. if (!RD->canPassInRegisters())
  63. return RAA_Indirect;
  64. return RAA_Default;
  65. }
  66. bool isThisCompleteObject(GlobalDecl GD) const override {
  67. // The Itanium ABI has separate complete-object vs. base-object
  68. // variants of both constructors and destructors.
  69. if (isa<CXXDestructorDecl>(GD.getDecl())) {
  70. switch (GD.getDtorType()) {
  71. case Dtor_Complete:
  72. case Dtor_Deleting:
  73. return true;
  74. case Dtor_Base:
  75. return false;
  76. case Dtor_Comdat:
  77. llvm_unreachable("emitting dtor comdat as function?");
  78. }
  79. llvm_unreachable("bad dtor kind");
  80. }
  81. if (isa<CXXConstructorDecl>(GD.getDecl())) {
  82. switch (GD.getCtorType()) {
  83. case Ctor_Complete:
  84. return true;
  85. case Ctor_Base:
  86. return false;
  87. case Ctor_CopyingClosure:
  88. case Ctor_DefaultClosure:
  89. llvm_unreachable("closure ctors in Itanium ABI?");
  90. case Ctor_Comdat:
  91. llvm_unreachable("emitting ctor comdat as function?");
  92. }
  93. llvm_unreachable("bad dtor kind");
  94. }
  95. // No other kinds.
  96. return false;
  97. }
  98. bool isZeroInitializable(const MemberPointerType *MPT) override;
  99. llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
  100. CGCallee
  101. EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
  102. const Expr *E,
  103. Address This,
  104. llvm::Value *&ThisPtrForCall,
  105. llvm::Value *MemFnPtr,
  106. const MemberPointerType *MPT) override;
  107. llvm::Value *
  108. EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
  109. Address Base,
  110. llvm::Value *MemPtr,
  111. const MemberPointerType *MPT) override;
  112. llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
  113. const CastExpr *E,
  114. llvm::Value *Src) override;
  115. llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
  116. llvm::Constant *Src) override;
  117. llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
  118. llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
  119. llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
  120. CharUnits offset) override;
  121. llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
  122. llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
  123. CharUnits ThisAdjustment);
  124. llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
  125. llvm::Value *L, llvm::Value *R,
  126. const MemberPointerType *MPT,
  127. bool Inequality) override;
  128. llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  129. llvm::Value *Addr,
  130. const MemberPointerType *MPT) override;
  131. void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
  132. Address Ptr, QualType ElementType,
  133. const CXXDestructorDecl *Dtor) override;
  134. void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
  135. void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
  136. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  137. llvm::CallInst *
  138. emitTerminateForUnexpectedException(CodeGenFunction &CGF,
  139. llvm::Value *Exn) override;
  140. void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
  141. llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
  142. CatchTypeInfo
  143. getAddrOfCXXCatchHandlerType(QualType Ty,
  144. QualType CatchHandlerType) override {
  145. return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
  146. }
  147. bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
  148. void EmitBadTypeidCall(CodeGenFunction &CGF) override;
  149. llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
  150. Address ThisPtr,
  151. llvm::Type *StdTypeInfoPtrTy) override;
  152. bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  153. QualType SrcRecordTy) override;
  154. llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
  155. QualType SrcRecordTy, QualType DestTy,
  156. QualType DestRecordTy,
  157. llvm::BasicBlock *CastEnd) override;
  158. llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
  159. QualType SrcRecordTy,
  160. QualType DestTy) override;
  161. bool EmitBadCastCall(CodeGenFunction &CGF) override;
  162. llvm::Value *
  163. GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
  164. const CXXRecordDecl *ClassDecl,
  165. const CXXRecordDecl *BaseClassDecl) override;
  166. void EmitCXXConstructors(const CXXConstructorDecl *D) override;
  167. AddedStructorArgs
  168. buildStructorSignature(GlobalDecl GD,
  169. SmallVectorImpl<CanQualType> &ArgTys) override;
  170. bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
  171. CXXDtorType DT) const override {
  172. // Itanium does not emit any destructor variant as an inline thunk.
  173. // Delegating may occur as an optimization, but all variants are either
  174. // emitted with external linkage or as linkonce if they are inline and used.
  175. return false;
  176. }
  177. void EmitCXXDestructors(const CXXDestructorDecl *D) override;
  178. void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
  179. FunctionArgList &Params) override;
  180. void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
  181. AddedStructorArgs
  182. addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
  183. CXXCtorType Type, bool ForVirtualBase,
  184. bool Delegating, CallArgList &Args) override;
  185. void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
  186. CXXDtorType Type, bool ForVirtualBase,
  187. bool Delegating, Address This,
  188. QualType ThisTy) override;
  189. void emitVTableDefinitions(CodeGenVTables &CGVT,
  190. const CXXRecordDecl *RD) override;
  191. bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
  192. CodeGenFunction::VPtr Vptr) override;
  193. bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
  194. return true;
  195. }
  196. llvm::Constant *
  197. getVTableAddressPoint(BaseSubobject Base,
  198. const CXXRecordDecl *VTableClass) override;
  199. llvm::Value *getVTableAddressPointInStructor(
  200. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  201. BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
  202. llvm::Value *getVTableAddressPointInStructorWithVTT(
  203. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
  204. BaseSubobject Base, const CXXRecordDecl *NearestVBase);
  205. llvm::Constant *
  206. getVTableAddressPointForConstExpr(BaseSubobject Base,
  207. const CXXRecordDecl *VTableClass) override;
  208. llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
  209. CharUnits VPtrOffset) override;
  210. CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
  211. Address This, llvm::Type *Ty,
  212. SourceLocation Loc) override;
  213. llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
  214. const CXXDestructorDecl *Dtor,
  215. CXXDtorType DtorType, Address This,
  216. DeleteOrMemberCallExpr E) override;
  217. void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
  218. bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
  219. bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
  220. void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
  221. bool ReturnAdjustment) override {
  222. // Allow inlining of thunks by emitting them with available_externally
  223. // linkage together with vtables when needed.
  224. if (ForVTable && !Thunk->hasLocalLinkage())
  225. Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  226. CGM.setGVProperties(Thunk, GD);
  227. }
  228. bool exportThunk() override { return true; }
  229. llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
  230. const ThisAdjustment &TA) override;
  231. llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  232. const ReturnAdjustment &RA) override;
  233. size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
  234. FunctionArgList &Args) const override {
  235. assert(!Args.empty() && "expected the arglist to not be empty!");
  236. return Args.size() - 1;
  237. }
  238. StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
  239. StringRef GetDeletedVirtualCallName() override
  240. { return "__cxa_deleted_virtual"; }
  241. CharUnits getArrayCookieSizeImpl(QualType elementType) override;
  242. Address InitializeArrayCookie(CodeGenFunction &CGF,
  243. Address NewPtr,
  244. llvm::Value *NumElements,
  245. const CXXNewExpr *expr,
  246. QualType ElementType) override;
  247. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
  248. Address allocPtr,
  249. CharUnits cookieSize) override;
  250. void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
  251. llvm::GlobalVariable *DeclPtr,
  252. bool PerformInit) override;
  253. void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  254. llvm::FunctionCallee dtor,
  255. llvm::Constant *addr) override;
  256. llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
  257. llvm::Value *Val);
  258. void EmitThreadLocalInitFuncs(
  259. CodeGenModule &CGM,
  260. ArrayRef<const VarDecl *> CXXThreadLocals,
  261. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  262. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
  263. /// Determine whether we will definitely emit this variable with a constant
  264. /// initializer, either because the language semantics demand it or because
  265. /// we know that the initializer is a constant.
  266. bool isEmittedWithConstantInitializer(const VarDecl *VD) const {
  267. VD = VD->getMostRecentDecl();
  268. if (VD->hasAttr<ConstInitAttr>())
  269. return true;
  270. // All later checks examine the initializer specified on the variable. If
  271. // the variable is weak, such examination would not be correct.
  272. if (VD->isWeak() || VD->hasAttr<SelectAnyAttr>())
  273. return false;
  274. const VarDecl *InitDecl = VD->getInitializingDeclaration();
  275. if (!InitDecl)
  276. return false;
  277. // If there's no initializer to run, this is constant initialization.
  278. if (!InitDecl->hasInit())
  279. return true;
  280. // If we have the only definition, we don't need a thread wrapper if we
  281. // will emit the value as a constant.
  282. if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
  283. return !VD->needsDestruction(getContext()) && InitDecl->evaluateValue();
  284. // Otherwise, we need a thread wrapper unless we know that every
  285. // translation unit will emit the value as a constant. We rely on
  286. // ICE-ness not varying between translation units, which isn't actually
  287. // guaranteed by the standard but is necessary for sanity.
  288. return InitDecl->isInitKnownICE() && InitDecl->isInitICE();
  289. }
  290. bool usesThreadWrapperFunction(const VarDecl *VD) const override {
  291. return !isEmittedWithConstantInitializer(VD) ||
  292. VD->needsDestruction(getContext());
  293. }
  294. LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
  295. QualType LValType) override;
  296. bool NeedsVTTParameter(GlobalDecl GD) override;
  297. /**************************** RTTI Uniqueness ******************************/
  298. protected:
  299. /// Returns true if the ABI requires RTTI type_info objects to be unique
  300. /// across a program.
  301. virtual bool shouldRTTIBeUnique() const { return true; }
  302. public:
  303. /// What sort of unique-RTTI behavior should we use?
  304. enum RTTIUniquenessKind {
  305. /// We are guaranteeing, or need to guarantee, that the RTTI string
  306. /// is unique.
  307. RUK_Unique,
  308. /// We are not guaranteeing uniqueness for the RTTI string, so we
  309. /// can demote to hidden visibility but must use string comparisons.
  310. RUK_NonUniqueHidden,
  311. /// We are not guaranteeing uniqueness for the RTTI string, so we
  312. /// have to use string comparisons, but we also have to emit it with
  313. /// non-hidden visibility.
  314. RUK_NonUniqueVisible
  315. };
  316. /// Return the required visibility status for the given type and linkage in
  317. /// the current ABI.
  318. RTTIUniquenessKind
  319. classifyRTTIUniqueness(QualType CanTy,
  320. llvm::GlobalValue::LinkageTypes Linkage) const;
  321. friend class ItaniumRTTIBuilder;
  322. void emitCXXStructor(GlobalDecl GD) override;
  323. std::pair<llvm::Value *, const CXXRecordDecl *>
  324. LoadVTablePtr(CodeGenFunction &CGF, Address This,
  325. const CXXRecordDecl *RD) override;
  326. private:
  327. bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
  328. const auto &VtableLayout =
  329. CGM.getItaniumVTableContext().getVTableLayout(RD);
  330. for (const auto &VtableComponent : VtableLayout.vtable_components()) {
  331. // Skip empty slot.
  332. if (!VtableComponent.isUsedFunctionPointerKind())
  333. continue;
  334. const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
  335. if (!Method->getCanonicalDecl()->isInlined())
  336. continue;
  337. StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
  338. auto *Entry = CGM.GetGlobalValue(Name);
  339. // This checks if virtual inline function has already been emitted.
  340. // Note that it is possible that this inline function would be emitted
  341. // after trying to emit vtable speculatively. Because of this we do
  342. // an extra pass after emitting all deferred vtables to find and emit
  343. // these vtables opportunistically.
  344. if (!Entry || Entry->isDeclaration())
  345. return true;
  346. }
  347. return false;
  348. }
  349. bool isVTableHidden(const CXXRecordDecl *RD) const {
  350. const auto &VtableLayout =
  351. CGM.getItaniumVTableContext().getVTableLayout(RD);
  352. for (const auto &VtableComponent : VtableLayout.vtable_components()) {
  353. if (VtableComponent.isRTTIKind()) {
  354. const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
  355. if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
  356. return true;
  357. } else if (VtableComponent.isUsedFunctionPointerKind()) {
  358. const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
  359. if (Method->getVisibility() == Visibility::HiddenVisibility &&
  360. !Method->isDefined())
  361. return true;
  362. }
  363. }
  364. return false;
  365. }
  366. };
  367. class ARMCXXABI : public ItaniumCXXABI {
  368. public:
  369. ARMCXXABI(CodeGen::CodeGenModule &CGM) :
  370. ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
  371. /*UseARMGuardVarABI=*/true) {}
  372. bool HasThisReturn(GlobalDecl GD) const override {
  373. return (isa<CXXConstructorDecl>(GD.getDecl()) || (
  374. isa<CXXDestructorDecl>(GD.getDecl()) &&
  375. GD.getDtorType() != Dtor_Deleting));
  376. }
  377. void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
  378. QualType ResTy) override;
  379. CharUnits getArrayCookieSizeImpl(QualType elementType) override;
  380. Address InitializeArrayCookie(CodeGenFunction &CGF,
  381. Address NewPtr,
  382. llvm::Value *NumElements,
  383. const CXXNewExpr *expr,
  384. QualType ElementType) override;
  385. llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
  386. CharUnits cookieSize) override;
  387. };
  388. class iOS64CXXABI : public ARMCXXABI {
  389. public:
  390. iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
  391. Use32BitVTableOffsetABI = true;
  392. }
  393. // ARM64 libraries are prepared for non-unique RTTI.
  394. bool shouldRTTIBeUnique() const override { return false; }
  395. };
  396. class WebAssemblyCXXABI final : public ItaniumCXXABI {
  397. public:
  398. explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
  399. : ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
  400. /*UseARMGuardVarABI=*/true) {}
  401. void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
  402. private:
  403. bool HasThisReturn(GlobalDecl GD) const override {
  404. return isa<CXXConstructorDecl>(GD.getDecl()) ||
  405. (isa<CXXDestructorDecl>(GD.getDecl()) &&
  406. GD.getDtorType() != Dtor_Deleting);
  407. }
  408. bool canCallMismatchedFunctionType() const override { return false; }
  409. };
  410. }
  411. CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
  412. switch (CGM.getTarget().getCXXABI().getKind()) {
  413. // For IR-generation purposes, there's no significant difference
  414. // between the ARM and iOS ABIs.
  415. case TargetCXXABI::GenericARM:
  416. case TargetCXXABI::iOS:
  417. case TargetCXXABI::WatchOS:
  418. return new ARMCXXABI(CGM);
  419. case TargetCXXABI::iOS64:
  420. return new iOS64CXXABI(CGM);
  421. // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
  422. // include the other 32-bit ARM oddities: constructor/destructor return values
  423. // and array cookies.
  424. case TargetCXXABI::GenericAArch64:
  425. return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
  426. /*UseARMGuardVarABI=*/true);
  427. case TargetCXXABI::GenericMIPS:
  428. return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
  429. case TargetCXXABI::WebAssembly:
  430. return new WebAssemblyCXXABI(CGM);
  431. case TargetCXXABI::GenericItanium:
  432. if (CGM.getContext().getTargetInfo().getTriple().getArch()
  433. == llvm::Triple::le32) {
  434. // For PNaCl, use ARM-style method pointers so that PNaCl code
  435. // does not assume anything about the alignment of function
  436. // pointers.
  437. return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
  438. }
  439. return new ItaniumCXXABI(CGM);
  440. case TargetCXXABI::Microsoft:
  441. llvm_unreachable("Microsoft ABI is not Itanium-based");
  442. }
  443. llvm_unreachable("bad ABI kind");
  444. }
  445. llvm::Type *
  446. ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
  447. if (MPT->isMemberDataPointer())
  448. return CGM.PtrDiffTy;
  449. return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
  450. }
  451. /// In the Itanium and ARM ABIs, method pointers have the form:
  452. /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
  453. ///
  454. /// In the Itanium ABI:
  455. /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
  456. /// - the this-adjustment is (memptr.adj)
  457. /// - the virtual offset is (memptr.ptr - 1)
  458. ///
  459. /// In the ARM ABI:
  460. /// - method pointers are virtual if (memptr.adj & 1) is nonzero
  461. /// - the this-adjustment is (memptr.adj >> 1)
  462. /// - the virtual offset is (memptr.ptr)
  463. /// ARM uses 'adj' for the virtual flag because Thumb functions
  464. /// may be only single-byte aligned.
  465. ///
  466. /// If the member is virtual, the adjusted 'this' pointer points
  467. /// to a vtable pointer from which the virtual offset is applied.
  468. ///
  469. /// If the member is non-virtual, memptr.ptr is the address of
  470. /// the function to call.
  471. CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
  472. CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
  473. llvm::Value *&ThisPtrForCall,
  474. llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
  475. CGBuilderTy &Builder = CGF.Builder;
  476. const FunctionProtoType *FPT =
  477. MPT->getPointeeType()->getAs<FunctionProtoType>();
  478. auto *RD =
  479. cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
  480. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
  481. CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
  482. llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
  483. llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
  484. llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
  485. llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
  486. // Extract memptr.adj, which is in the second field.
  487. llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
  488. // Compute the true adjustment.
  489. llvm::Value *Adj = RawAdj;
  490. if (UseARMMethodPtrABI)
  491. Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
  492. // Apply the adjustment and cast back to the original struct type
  493. // for consistency.
  494. llvm::Value *This = ThisAddr.getPointer();
  495. llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
  496. Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
  497. This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
  498. ThisPtrForCall = This;
  499. // Load the function pointer.
  500. llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
  501. // If the LSB in the function pointer is 1, the function pointer points to
  502. // a virtual function.
  503. llvm::Value *IsVirtual;
  504. if (UseARMMethodPtrABI)
  505. IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
  506. else
  507. IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
  508. IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
  509. Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
  510. // In the virtual path, the adjustment left 'This' pointing to the
  511. // vtable of the correct base subobject. The "function pointer" is an
  512. // offset within the vtable (+1 for the virtual flag on non-ARM).
  513. CGF.EmitBlock(FnVirtual);
  514. // Cast the adjusted this to a pointer to vtable pointer and load.
  515. llvm::Type *VTableTy = Builder.getInt8PtrTy();
  516. CharUnits VTablePtrAlign =
  517. CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
  518. CGF.getPointerAlign());
  519. llvm::Value *VTable =
  520. CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
  521. // Apply the offset.
  522. // On ARM64, to reserve extra space in virtual member function pointers,
  523. // we only pay attention to the low 32 bits of the offset.
  524. llvm::Value *VTableOffset = FnAsInt;
  525. if (!UseARMMethodPtrABI)
  526. VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
  527. if (Use32BitVTableOffsetABI) {
  528. VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
  529. VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
  530. }
  531. // Check the address of the function pointer if CFI on member function
  532. // pointers is enabled.
  533. llvm::Constant *CheckSourceLocation;
  534. llvm::Constant *CheckTypeDesc;
  535. bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
  536. CGM.HasHiddenLTOVisibility(RD);
  537. bool ShouldEmitVFEInfo = CGM.getCodeGenOpts().VirtualFunctionElimination &&
  538. CGM.HasHiddenLTOVisibility(RD);
  539. llvm::Value *VirtualFn = nullptr;
  540. {
  541. CodeGenFunction::SanitizerScope SanScope(&CGF);
  542. llvm::Value *TypeId = nullptr;
  543. llvm::Value *CheckResult = nullptr;
  544. if (ShouldEmitCFICheck || ShouldEmitVFEInfo) {
  545. // If doing CFI or VFE, we will need the metadata node to check against.
  546. llvm::Metadata *MD =
  547. CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
  548. TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
  549. }
  550. llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
  551. if (ShouldEmitVFEInfo) {
  552. // If doing VFE, load from the vtable with a type.checked.load intrinsic
  553. // call. Note that we use the GEP to calculate the address to load from
  554. // and pass 0 as the offset to the intrinsic. This is because every
  555. // vtable slot of the correct type is marked with matching metadata, and
  556. // we know that the load must be from one of these slots.
  557. llvm::Value *CheckedLoad = Builder.CreateCall(
  558. CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
  559. {VFPAddr, llvm::ConstantInt::get(CGM.Int32Ty, 0), TypeId});
  560. CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
  561. VirtualFn = Builder.CreateExtractValue(CheckedLoad, 0);
  562. VirtualFn = Builder.CreateBitCast(VirtualFn, FTy->getPointerTo(),
  563. "memptr.virtualfn");
  564. } else {
  565. // When not doing VFE, emit a normal load, as it allows more
  566. // optimisations than type.checked.load.
  567. if (ShouldEmitCFICheck) {
  568. CheckResult = Builder.CreateCall(
  569. CGM.getIntrinsic(llvm::Intrinsic::type_test),
  570. {Builder.CreateBitCast(VFPAddr, CGF.Int8PtrTy), TypeId});
  571. }
  572. VFPAddr =
  573. Builder.CreateBitCast(VFPAddr, FTy->getPointerTo()->getPointerTo());
  574. VirtualFn = Builder.CreateAlignedLoad(VFPAddr, CGF.getPointerAlign(),
  575. "memptr.virtualfn");
  576. }
  577. assert(VirtualFn && "Virtual fuction pointer not created!");
  578. assert((!ShouldEmitCFICheck || !ShouldEmitVFEInfo || CheckResult) &&
  579. "Check result required but not created!");
  580. if (ShouldEmitCFICheck) {
  581. // If doing CFI, emit the check.
  582. CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
  583. CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
  584. llvm::Constant *StaticData[] = {
  585. llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
  586. CheckSourceLocation,
  587. CheckTypeDesc,
  588. };
  589. if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
  590. CGF.EmitTrapCheck(CheckResult);
  591. } else {
  592. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  593. CGM.getLLVMContext(),
  594. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  595. llvm::Value *ValidVtable = Builder.CreateCall(
  596. CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
  597. CGF.EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIMFCall),
  598. SanitizerHandler::CFICheckFail, StaticData,
  599. {VTable, ValidVtable});
  600. }
  601. FnVirtual = Builder.GetInsertBlock();
  602. }
  603. } // End of sanitizer scope
  604. CGF.EmitBranch(FnEnd);
  605. // In the non-virtual path, the function pointer is actually a
  606. // function pointer.
  607. CGF.EmitBlock(FnNonVirtual);
  608. llvm::Value *NonVirtualFn =
  609. Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
  610. // Check the function pointer if CFI on member function pointers is enabled.
  611. if (ShouldEmitCFICheck) {
  612. CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
  613. if (RD->hasDefinition()) {
  614. CodeGenFunction::SanitizerScope SanScope(&CGF);
  615. llvm::Constant *StaticData[] = {
  616. llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
  617. CheckSourceLocation,
  618. CheckTypeDesc,
  619. };
  620. llvm::Value *Bit = Builder.getFalse();
  621. llvm::Value *CastedNonVirtualFn =
  622. Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
  623. for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
  624. llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
  625. getContext().getMemberPointerType(
  626. MPT->getPointeeType(),
  627. getContext().getRecordType(Base).getTypePtr()));
  628. llvm::Value *TypeId =
  629. llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
  630. llvm::Value *TypeTest =
  631. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  632. {CastedNonVirtualFn, TypeId});
  633. Bit = Builder.CreateOr(Bit, TypeTest);
  634. }
  635. CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
  636. SanitizerHandler::CFICheckFail, StaticData,
  637. {CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
  638. FnNonVirtual = Builder.GetInsertBlock();
  639. }
  640. }
  641. // We're done.
  642. CGF.EmitBlock(FnEnd);
  643. llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
  644. CalleePtr->addIncoming(VirtualFn, FnVirtual);
  645. CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
  646. CGCallee Callee(FPT, CalleePtr);
  647. return Callee;
  648. }
  649. /// Compute an l-value by applying the given pointer-to-member to a
  650. /// base object.
  651. llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
  652. CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
  653. const MemberPointerType *MPT) {
  654. assert(MemPtr->getType() == CGM.PtrDiffTy);
  655. CGBuilderTy &Builder = CGF.Builder;
  656. // Cast to char*.
  657. Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
  658. // Apply the offset, which we assume is non-null.
  659. llvm::Value *Addr =
  660. Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
  661. // Cast the address to the appropriate pointer type, adopting the
  662. // address space of the base pointer.
  663. llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
  664. ->getPointerTo(Base.getAddressSpace());
  665. return Builder.CreateBitCast(Addr, PType);
  666. }
  667. /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
  668. /// conversion.
  669. ///
  670. /// Bitcast conversions are always a no-op under Itanium.
  671. ///
  672. /// Obligatory offset/adjustment diagram:
  673. /// <-- offset --> <-- adjustment -->
  674. /// |--------------------------|----------------------|--------------------|
  675. /// ^Derived address point ^Base address point ^Member address point
  676. ///
  677. /// So when converting a base member pointer to a derived member pointer,
  678. /// we add the offset to the adjustment because the address point has
  679. /// decreased; and conversely, when converting a derived MP to a base MP
  680. /// we subtract the offset from the adjustment because the address point
  681. /// has increased.
  682. ///
  683. /// The standard forbids (at compile time) conversion to and from
  684. /// virtual bases, which is why we don't have to consider them here.
  685. ///
  686. /// The standard forbids (at run time) casting a derived MP to a base
  687. /// MP when the derived MP does not point to a member of the base.
  688. /// This is why -1 is a reasonable choice for null data member
  689. /// pointers.
  690. llvm::Value *
  691. ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
  692. const CastExpr *E,
  693. llvm::Value *src) {
  694. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  695. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  696. E->getCastKind() == CK_ReinterpretMemberPointer);
  697. // Under Itanium, reinterprets don't require any additional processing.
  698. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  699. // Use constant emission if we can.
  700. if (isa<llvm::Constant>(src))
  701. return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
  702. llvm::Constant *adj = getMemberPointerAdjustment(E);
  703. if (!adj) return src;
  704. CGBuilderTy &Builder = CGF.Builder;
  705. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  706. const MemberPointerType *destTy =
  707. E->getType()->castAs<MemberPointerType>();
  708. // For member data pointers, this is just a matter of adding the
  709. // offset if the source is non-null.
  710. if (destTy->isMemberDataPointer()) {
  711. llvm::Value *dst;
  712. if (isDerivedToBase)
  713. dst = Builder.CreateNSWSub(src, adj, "adj");
  714. else
  715. dst = Builder.CreateNSWAdd(src, adj, "adj");
  716. // Null check.
  717. llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
  718. llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
  719. return Builder.CreateSelect(isNull, src, dst);
  720. }
  721. // The this-adjustment is left-shifted by 1 on ARM.
  722. if (UseARMMethodPtrABI) {
  723. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  724. offset <<= 1;
  725. adj = llvm::ConstantInt::get(adj->getType(), offset);
  726. }
  727. llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
  728. llvm::Value *dstAdj;
  729. if (isDerivedToBase)
  730. dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
  731. else
  732. dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
  733. return Builder.CreateInsertValue(src, dstAdj, 1);
  734. }
  735. llvm::Constant *
  736. ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
  737. llvm::Constant *src) {
  738. assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
  739. E->getCastKind() == CK_BaseToDerivedMemberPointer ||
  740. E->getCastKind() == CK_ReinterpretMemberPointer);
  741. // Under Itanium, reinterprets don't require any additional processing.
  742. if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
  743. // If the adjustment is trivial, we don't need to do anything.
  744. llvm::Constant *adj = getMemberPointerAdjustment(E);
  745. if (!adj) return src;
  746. bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
  747. const MemberPointerType *destTy =
  748. E->getType()->castAs<MemberPointerType>();
  749. // For member data pointers, this is just a matter of adding the
  750. // offset if the source is non-null.
  751. if (destTy->isMemberDataPointer()) {
  752. // null maps to null.
  753. if (src->isAllOnesValue()) return src;
  754. if (isDerivedToBase)
  755. return llvm::ConstantExpr::getNSWSub(src, adj);
  756. else
  757. return llvm::ConstantExpr::getNSWAdd(src, adj);
  758. }
  759. // The this-adjustment is left-shifted by 1 on ARM.
  760. if (UseARMMethodPtrABI) {
  761. uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
  762. offset <<= 1;
  763. adj = llvm::ConstantInt::get(adj->getType(), offset);
  764. }
  765. llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
  766. llvm::Constant *dstAdj;
  767. if (isDerivedToBase)
  768. dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
  769. else
  770. dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
  771. return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
  772. }
  773. llvm::Constant *
  774. ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
  775. // Itanium C++ ABI 2.3:
  776. // A NULL pointer is represented as -1.
  777. if (MPT->isMemberDataPointer())
  778. return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
  779. llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
  780. llvm::Constant *Values[2] = { Zero, Zero };
  781. return llvm::ConstantStruct::getAnon(Values);
  782. }
  783. llvm::Constant *
  784. ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
  785. CharUnits offset) {
  786. // Itanium C++ ABI 2.3:
  787. // A pointer to data member is an offset from the base address of
  788. // the class object containing it, represented as a ptrdiff_t
  789. return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
  790. }
  791. llvm::Constant *
  792. ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
  793. return BuildMemberPointer(MD, CharUnits::Zero());
  794. }
  795. llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
  796. CharUnits ThisAdjustment) {
  797. assert(MD->isInstance() && "Member function must not be static!");
  798. CodeGenTypes &Types = CGM.getTypes();
  799. // Get the function pointer (or index if this is a virtual function).
  800. llvm::Constant *MemPtr[2];
  801. if (MD->isVirtual()) {
  802. uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
  803. const ASTContext &Context = getContext();
  804. CharUnits PointerWidth =
  805. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  806. uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
  807. if (UseARMMethodPtrABI) {
  808. // ARM C++ ABI 3.2.1:
  809. // This ABI specifies that adj contains twice the this
  810. // adjustment, plus 1 if the member function is virtual. The
  811. // least significant bit of adj then makes exactly the same
  812. // discrimination as the least significant bit of ptr does for
  813. // Itanium.
  814. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
  815. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  816. 2 * ThisAdjustment.getQuantity() + 1);
  817. } else {
  818. // Itanium C++ ABI 2.3:
  819. // For a virtual function, [the pointer field] is 1 plus the
  820. // virtual table offset (in bytes) of the function,
  821. // represented as a ptrdiff_t.
  822. MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
  823. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  824. ThisAdjustment.getQuantity());
  825. }
  826. } else {
  827. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  828. llvm::Type *Ty;
  829. // Check whether the function has a computable LLVM signature.
  830. if (Types.isFuncTypeConvertible(FPT)) {
  831. // The function has a computable LLVM signature; use the correct type.
  832. Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
  833. } else {
  834. // Use an arbitrary non-function type to tell GetAddrOfFunction that the
  835. // function type is incomplete.
  836. Ty = CGM.PtrDiffTy;
  837. }
  838. llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
  839. MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
  840. MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
  841. (UseARMMethodPtrABI ? 2 : 1) *
  842. ThisAdjustment.getQuantity());
  843. }
  844. return llvm::ConstantStruct::getAnon(MemPtr);
  845. }
  846. llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
  847. QualType MPType) {
  848. const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
  849. const ValueDecl *MPD = MP.getMemberPointerDecl();
  850. if (!MPD)
  851. return EmitNullMemberPointer(MPT);
  852. CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
  853. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
  854. return BuildMemberPointer(MD, ThisAdjustment);
  855. CharUnits FieldOffset =
  856. getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
  857. return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
  858. }
  859. /// The comparison algorithm is pretty easy: the member pointers are
  860. /// the same if they're either bitwise identical *or* both null.
  861. ///
  862. /// ARM is different here only because null-ness is more complicated.
  863. llvm::Value *
  864. ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
  865. llvm::Value *L,
  866. llvm::Value *R,
  867. const MemberPointerType *MPT,
  868. bool Inequality) {
  869. CGBuilderTy &Builder = CGF.Builder;
  870. llvm::ICmpInst::Predicate Eq;
  871. llvm::Instruction::BinaryOps And, Or;
  872. if (Inequality) {
  873. Eq = llvm::ICmpInst::ICMP_NE;
  874. And = llvm::Instruction::Or;
  875. Or = llvm::Instruction::And;
  876. } else {
  877. Eq = llvm::ICmpInst::ICMP_EQ;
  878. And = llvm::Instruction::And;
  879. Or = llvm::Instruction::Or;
  880. }
  881. // Member data pointers are easy because there's a unique null
  882. // value, so it just comes down to bitwise equality.
  883. if (MPT->isMemberDataPointer())
  884. return Builder.CreateICmp(Eq, L, R);
  885. // For member function pointers, the tautologies are more complex.
  886. // The Itanium tautology is:
  887. // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
  888. // The ARM tautology is:
  889. // (L == R) <==> (L.ptr == R.ptr &&
  890. // (L.adj == R.adj ||
  891. // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
  892. // The inequality tautologies have exactly the same structure, except
  893. // applying De Morgan's laws.
  894. llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
  895. llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
  896. // This condition tests whether L.ptr == R.ptr. This must always be
  897. // true for equality to hold.
  898. llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
  899. // This condition, together with the assumption that L.ptr == R.ptr,
  900. // tests whether the pointers are both null. ARM imposes an extra
  901. // condition.
  902. llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
  903. llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
  904. // This condition tests whether L.adj == R.adj. If this isn't
  905. // true, the pointers are unequal unless they're both null.
  906. llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
  907. llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
  908. llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
  909. // Null member function pointers on ARM clear the low bit of Adj,
  910. // so the zero condition has to check that neither low bit is set.
  911. if (UseARMMethodPtrABI) {
  912. llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
  913. // Compute (l.adj | r.adj) & 1 and test it against zero.
  914. llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
  915. llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
  916. llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
  917. "cmp.or.adj");
  918. EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
  919. }
  920. // Tie together all our conditions.
  921. llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
  922. Result = Builder.CreateBinOp(And, PtrEq, Result,
  923. Inequality ? "memptr.ne" : "memptr.eq");
  924. return Result;
  925. }
  926. llvm::Value *
  927. ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
  928. llvm::Value *MemPtr,
  929. const MemberPointerType *MPT) {
  930. CGBuilderTy &Builder = CGF.Builder;
  931. /// For member data pointers, this is just a check against -1.
  932. if (MPT->isMemberDataPointer()) {
  933. assert(MemPtr->getType() == CGM.PtrDiffTy);
  934. llvm::Value *NegativeOne =
  935. llvm::Constant::getAllOnesValue(MemPtr->getType());
  936. return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
  937. }
  938. // In Itanium, a member function pointer is not null if 'ptr' is not null.
  939. llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
  940. llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
  941. llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
  942. // On ARM, a member function pointer is also non-null if the low bit of 'adj'
  943. // (the virtual bit) is set.
  944. if (UseARMMethodPtrABI) {
  945. llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
  946. llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
  947. llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
  948. llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
  949. "memptr.isvirtual");
  950. Result = Builder.CreateOr(Result, IsVirtual);
  951. }
  952. return Result;
  953. }
  954. bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
  955. const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
  956. if (!RD)
  957. return false;
  958. // If C++ prohibits us from making a copy, return by address.
  959. if (!RD->canPassInRegisters()) {
  960. auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
  961. FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  962. return true;
  963. }
  964. return false;
  965. }
  966. /// The Itanium ABI requires non-zero initialization only for data
  967. /// member pointers, for which '0' is a valid offset.
  968. bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
  969. return MPT->isMemberFunctionPointer();
  970. }
  971. /// The Itanium ABI always places an offset to the complete object
  972. /// at entry -2 in the vtable.
  973. void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
  974. const CXXDeleteExpr *DE,
  975. Address Ptr,
  976. QualType ElementType,
  977. const CXXDestructorDecl *Dtor) {
  978. bool UseGlobalDelete = DE->isGlobalDelete();
  979. if (UseGlobalDelete) {
  980. // Derive the complete-object pointer, which is what we need
  981. // to pass to the deallocation function.
  982. // Grab the vtable pointer as an intptr_t*.
  983. auto *ClassDecl =
  984. cast<CXXRecordDecl>(ElementType->castAs<RecordType>()->getDecl());
  985. llvm::Value *VTable =
  986. CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
  987. // Track back to entry -2 and pull out the offset there.
  988. llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
  989. VTable, -2, "complete-offset.ptr");
  990. llvm::Value *Offset =
  991. CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
  992. // Apply the offset.
  993. llvm::Value *CompletePtr =
  994. CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
  995. CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
  996. // If we're supposed to call the global delete, make sure we do so
  997. // even if the destructor throws.
  998. CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
  999. ElementType);
  1000. }
  1001. // FIXME: Provide a source location here even though there's no
  1002. // CXXMemberCallExpr for dtor call.
  1003. CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
  1004. EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
  1005. if (UseGlobalDelete)
  1006. CGF.PopCleanupBlock();
  1007. }
  1008. void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
  1009. // void __cxa_rethrow();
  1010. llvm::FunctionType *FTy =
  1011. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  1012. llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
  1013. if (isNoReturn)
  1014. CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
  1015. else
  1016. CGF.EmitRuntimeCallOrInvoke(Fn);
  1017. }
  1018. static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
  1019. // void *__cxa_allocate_exception(size_t thrown_size);
  1020. llvm::FunctionType *FTy =
  1021. llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
  1022. return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
  1023. }
  1024. static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
  1025. // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
  1026. // void (*dest) (void *));
  1027. llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
  1028. llvm::FunctionType *FTy =
  1029. llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
  1030. return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
  1031. }
  1032. void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
  1033. QualType ThrowType = E->getSubExpr()->getType();
  1034. // Now allocate the exception object.
  1035. llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
  1036. uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
  1037. llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
  1038. llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
  1039. AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
  1040. CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
  1041. CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
  1042. // Now throw the exception.
  1043. llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
  1044. /*ForEH=*/true);
  1045. // The address of the destructor. If the exception type has a
  1046. // trivial destructor (or isn't a record), we just pass null.
  1047. llvm::Constant *Dtor = nullptr;
  1048. if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
  1049. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
  1050. if (!Record->hasTrivialDestructor()) {
  1051. CXXDestructorDecl *DtorD = Record->getDestructor();
  1052. Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
  1053. Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
  1054. }
  1055. }
  1056. if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  1057. llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
  1058. CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
  1059. }
  1060. static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
  1061. // void *__dynamic_cast(const void *sub,
  1062. // const abi::__class_type_info *src,
  1063. // const abi::__class_type_info *dst,
  1064. // std::ptrdiff_t src2dst_offset);
  1065. llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
  1066. llvm::Type *PtrDiffTy =
  1067. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1068. llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
  1069. llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
  1070. // Mark the function as nounwind readonly.
  1071. llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
  1072. llvm::Attribute::ReadOnly };
  1073. llvm::AttributeList Attrs = llvm::AttributeList::get(
  1074. CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
  1075. return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
  1076. }
  1077. static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
  1078. // void __cxa_bad_cast();
  1079. llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
  1080. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
  1081. }
  1082. /// Compute the src2dst_offset hint as described in the
  1083. /// Itanium C++ ABI [2.9.7]
  1084. static CharUnits computeOffsetHint(ASTContext &Context,
  1085. const CXXRecordDecl *Src,
  1086. const CXXRecordDecl *Dst) {
  1087. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1088. /*DetectVirtual=*/false);
  1089. // If Dst is not derived from Src we can skip the whole computation below and
  1090. // return that Src is not a public base of Dst. Record all inheritance paths.
  1091. if (!Dst->isDerivedFrom(Src, Paths))
  1092. return CharUnits::fromQuantity(-2ULL);
  1093. unsigned NumPublicPaths = 0;
  1094. CharUnits Offset;
  1095. // Now walk all possible inheritance paths.
  1096. for (const CXXBasePath &Path : Paths) {
  1097. if (Path.Access != AS_public) // Ignore non-public inheritance.
  1098. continue;
  1099. ++NumPublicPaths;
  1100. for (const CXXBasePathElement &PathElement : Path) {
  1101. // If the path contains a virtual base class we can't give any hint.
  1102. // -1: no hint.
  1103. if (PathElement.Base->isVirtual())
  1104. return CharUnits::fromQuantity(-1ULL);
  1105. if (NumPublicPaths > 1) // Won't use offsets, skip computation.
  1106. continue;
  1107. // Accumulate the base class offsets.
  1108. const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
  1109. Offset += L.getBaseClassOffset(
  1110. PathElement.Base->getType()->getAsCXXRecordDecl());
  1111. }
  1112. }
  1113. // -2: Src is not a public base of Dst.
  1114. if (NumPublicPaths == 0)
  1115. return CharUnits::fromQuantity(-2ULL);
  1116. // -3: Src is a multiple public base type but never a virtual base type.
  1117. if (NumPublicPaths > 1)
  1118. return CharUnits::fromQuantity(-3ULL);
  1119. // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
  1120. // Return the offset of Src from the origin of Dst.
  1121. return Offset;
  1122. }
  1123. static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
  1124. // void __cxa_bad_typeid();
  1125. llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
  1126. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
  1127. }
  1128. bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
  1129. QualType SrcRecordTy) {
  1130. return IsDeref;
  1131. }
  1132. void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
  1133. llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
  1134. llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
  1135. Call->setDoesNotReturn();
  1136. CGF.Builder.CreateUnreachable();
  1137. }
  1138. llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
  1139. QualType SrcRecordTy,
  1140. Address ThisPtr,
  1141. llvm::Type *StdTypeInfoPtrTy) {
  1142. auto *ClassDecl =
  1143. cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
  1144. llvm::Value *Value =
  1145. CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
  1146. // Load the type info.
  1147. Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
  1148. return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
  1149. }
  1150. bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
  1151. QualType SrcRecordTy) {
  1152. return SrcIsPtr;
  1153. }
  1154. llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
  1155. CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
  1156. QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
  1157. llvm::Type *PtrDiffLTy =
  1158. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1159. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  1160. llvm::Value *SrcRTTI =
  1161. CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
  1162. llvm::Value *DestRTTI =
  1163. CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
  1164. // Compute the offset hint.
  1165. const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
  1166. const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
  1167. llvm::Value *OffsetHint = llvm::ConstantInt::get(
  1168. PtrDiffLTy,
  1169. computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
  1170. // Emit the call to __dynamic_cast.
  1171. llvm::Value *Value = ThisAddr.getPointer();
  1172. Value = CGF.EmitCastToVoidPtr(Value);
  1173. llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
  1174. Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
  1175. Value = CGF.Builder.CreateBitCast(Value, DestLTy);
  1176. /// C++ [expr.dynamic.cast]p9:
  1177. /// A failed cast to reference type throws std::bad_cast
  1178. if (DestTy->isReferenceType()) {
  1179. llvm::BasicBlock *BadCastBlock =
  1180. CGF.createBasicBlock("dynamic_cast.bad_cast");
  1181. llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
  1182. CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
  1183. CGF.EmitBlock(BadCastBlock);
  1184. EmitBadCastCall(CGF);
  1185. }
  1186. return Value;
  1187. }
  1188. llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
  1189. Address ThisAddr,
  1190. QualType SrcRecordTy,
  1191. QualType DestTy) {
  1192. llvm::Type *PtrDiffLTy =
  1193. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1194. llvm::Type *DestLTy = CGF.ConvertType(DestTy);
  1195. auto *ClassDecl =
  1196. cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
  1197. // Get the vtable pointer.
  1198. llvm::Value *VTable = CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(),
  1199. ClassDecl);
  1200. // Get the offset-to-top from the vtable.
  1201. llvm::Value *OffsetToTop =
  1202. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
  1203. OffsetToTop =
  1204. CGF.Builder.CreateAlignedLoad(OffsetToTop, CGF.getPointerAlign(),
  1205. "offset.to.top");
  1206. // Finally, add the offset to the pointer.
  1207. llvm::Value *Value = ThisAddr.getPointer();
  1208. Value = CGF.EmitCastToVoidPtr(Value);
  1209. Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
  1210. return CGF.Builder.CreateBitCast(Value, DestLTy);
  1211. }
  1212. bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
  1213. llvm::FunctionCallee Fn = getBadCastFn(CGF);
  1214. llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
  1215. Call->setDoesNotReturn();
  1216. CGF.Builder.CreateUnreachable();
  1217. return true;
  1218. }
  1219. llvm::Value *
  1220. ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
  1221. Address This,
  1222. const CXXRecordDecl *ClassDecl,
  1223. const CXXRecordDecl *BaseClassDecl) {
  1224. llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
  1225. CharUnits VBaseOffsetOffset =
  1226. CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
  1227. BaseClassDecl);
  1228. llvm::Value *VBaseOffsetPtr =
  1229. CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1230. "vbase.offset.ptr");
  1231. VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
  1232. CGM.PtrDiffTy->getPointerTo());
  1233. llvm::Value *VBaseOffset =
  1234. CGF.Builder.CreateAlignedLoad(VBaseOffsetPtr, CGF.getPointerAlign(),
  1235. "vbase.offset");
  1236. return VBaseOffset;
  1237. }
  1238. void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
  1239. // Just make sure we're in sync with TargetCXXABI.
  1240. assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
  1241. // The constructor used for constructing this as a base class;
  1242. // ignores virtual bases.
  1243. CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
  1244. // The constructor used for constructing this as a complete class;
  1245. // constructs the virtual bases, then calls the base constructor.
  1246. if (!D->getParent()->isAbstract()) {
  1247. // We don't need to emit the complete ctor if the class is abstract.
  1248. CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
  1249. }
  1250. }
  1251. CGCXXABI::AddedStructorArgs
  1252. ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
  1253. SmallVectorImpl<CanQualType> &ArgTys) {
  1254. ASTContext &Context = getContext();
  1255. // All parameters are already in place except VTT, which goes after 'this'.
  1256. // These are Clang types, so we don't need to worry about sret yet.
  1257. // Check if we need to add a VTT parameter (which has type void **).
  1258. if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
  1259. : GD.getDtorType() == Dtor_Base) &&
  1260. cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
  1261. ArgTys.insert(ArgTys.begin() + 1,
  1262. Context.getPointerType(Context.VoidPtrTy));
  1263. return AddedStructorArgs::prefix(1);
  1264. }
  1265. return AddedStructorArgs{};
  1266. }
  1267. void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
  1268. // The destructor used for destructing this as a base class; ignores
  1269. // virtual bases.
  1270. CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
  1271. // The destructor used for destructing this as a most-derived class;
  1272. // call the base destructor and then destructs any virtual bases.
  1273. CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
  1274. // The destructor in a virtual table is always a 'deleting'
  1275. // destructor, which calls the complete destructor and then uses the
  1276. // appropriate operator delete.
  1277. if (D->isVirtual())
  1278. CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
  1279. }
  1280. void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
  1281. QualType &ResTy,
  1282. FunctionArgList &Params) {
  1283. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
  1284. assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
  1285. // Check if we need a VTT parameter as well.
  1286. if (NeedsVTTParameter(CGF.CurGD)) {
  1287. ASTContext &Context = getContext();
  1288. // FIXME: avoid the fake decl
  1289. QualType T = Context.getPointerType(Context.VoidPtrTy);
  1290. auto *VTTDecl = ImplicitParamDecl::Create(
  1291. Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
  1292. T, ImplicitParamDecl::CXXVTT);
  1293. Params.insert(Params.begin() + 1, VTTDecl);
  1294. getStructorImplicitParamDecl(CGF) = VTTDecl;
  1295. }
  1296. }
  1297. void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
  1298. // Naked functions have no prolog.
  1299. if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
  1300. return;
  1301. /// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
  1302. /// adjustments are required, because they are all handled by thunks.
  1303. setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
  1304. /// Initialize the 'vtt' slot if needed.
  1305. if (getStructorImplicitParamDecl(CGF)) {
  1306. getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
  1307. CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
  1308. }
  1309. /// If this is a function that the ABI specifies returns 'this', initialize
  1310. /// the return slot to 'this' at the start of the function.
  1311. ///
  1312. /// Unlike the setting of return types, this is done within the ABI
  1313. /// implementation instead of by clients of CGCXXABI because:
  1314. /// 1) getThisValue is currently protected
  1315. /// 2) in theory, an ABI could implement 'this' returns some other way;
  1316. /// HasThisReturn only specifies a contract, not the implementation
  1317. if (HasThisReturn(CGF.CurGD))
  1318. CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
  1319. }
  1320. CGCXXABI::AddedStructorArgs ItaniumCXXABI::addImplicitConstructorArgs(
  1321. CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
  1322. bool ForVirtualBase, bool Delegating, CallArgList &Args) {
  1323. if (!NeedsVTTParameter(GlobalDecl(D, Type)))
  1324. return AddedStructorArgs{};
  1325. // Insert the implicit 'vtt' argument as the second argument.
  1326. llvm::Value *VTT =
  1327. CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
  1328. QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
  1329. Args.insert(Args.begin() + 1, CallArg(RValue::get(VTT), VTTTy));
  1330. return AddedStructorArgs::prefix(1); // Added one arg.
  1331. }
  1332. void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
  1333. const CXXDestructorDecl *DD,
  1334. CXXDtorType Type, bool ForVirtualBase,
  1335. bool Delegating, Address This,
  1336. QualType ThisTy) {
  1337. GlobalDecl GD(DD, Type);
  1338. llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
  1339. QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
  1340. CGCallee Callee;
  1341. if (getContext().getLangOpts().AppleKext &&
  1342. Type != Dtor_Base && DD->isVirtual())
  1343. Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
  1344. else
  1345. Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
  1346. CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
  1347. nullptr);
  1348. }
  1349. void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
  1350. const CXXRecordDecl *RD) {
  1351. llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
  1352. if (VTable->hasInitializer())
  1353. return;
  1354. ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
  1355. const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
  1356. llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
  1357. llvm::Constant *RTTI =
  1358. CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
  1359. // Create and set the initializer.
  1360. ConstantInitBuilder Builder(CGM);
  1361. auto Components = Builder.beginStruct();
  1362. CGVT.createVTableInitializer(Components, VTLayout, RTTI);
  1363. Components.finishAndSetAsInitializer(VTable);
  1364. // Set the correct linkage.
  1365. VTable->setLinkage(Linkage);
  1366. if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
  1367. VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
  1368. // Set the right visibility.
  1369. CGM.setGVProperties(VTable, RD);
  1370. // If this is the magic class __cxxabiv1::__fundamental_type_info,
  1371. // we will emit the typeinfo for the fundamental types. This is the
  1372. // same behaviour as GCC.
  1373. const DeclContext *DC = RD->getDeclContext();
  1374. if (RD->getIdentifier() &&
  1375. RD->getIdentifier()->isStr("__fundamental_type_info") &&
  1376. isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
  1377. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
  1378. DC->getParent()->isTranslationUnit())
  1379. EmitFundamentalRTTIDescriptors(RD);
  1380. if (!VTable->isDeclarationForLinker())
  1381. CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
  1382. }
  1383. bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
  1384. CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
  1385. if (Vptr.NearestVBase == nullptr)
  1386. return false;
  1387. return NeedsVTTParameter(CGF.CurGD);
  1388. }
  1389. llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
  1390. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1391. const CXXRecordDecl *NearestVBase) {
  1392. if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
  1393. NeedsVTTParameter(CGF.CurGD)) {
  1394. return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
  1395. NearestVBase);
  1396. }
  1397. return getVTableAddressPoint(Base, VTableClass);
  1398. }
  1399. llvm::Constant *
  1400. ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
  1401. const CXXRecordDecl *VTableClass) {
  1402. llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
  1403. // Find the appropriate vtable within the vtable group, and the address point
  1404. // within that vtable.
  1405. VTableLayout::AddressPointLocation AddressPoint =
  1406. CGM.getItaniumVTableContext()
  1407. .getVTableLayout(VTableClass)
  1408. .getAddressPoint(Base);
  1409. llvm::Value *Indices[] = {
  1410. llvm::ConstantInt::get(CGM.Int32Ty, 0),
  1411. llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
  1412. llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
  1413. };
  1414. return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
  1415. Indices, /*InBounds=*/true,
  1416. /*InRangeIndex=*/1);
  1417. }
  1418. llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
  1419. CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
  1420. const CXXRecordDecl *NearestVBase) {
  1421. assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
  1422. NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
  1423. // Get the secondary vpointer index.
  1424. uint64_t VirtualPointerIndex =
  1425. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1426. /// Load the VTT.
  1427. llvm::Value *VTT = CGF.LoadCXXVTT();
  1428. if (VirtualPointerIndex)
  1429. VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1430. // And load the address point from the VTT.
  1431. return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
  1432. }
  1433. llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
  1434. BaseSubobject Base, const CXXRecordDecl *VTableClass) {
  1435. return getVTableAddressPoint(Base, VTableClass);
  1436. }
  1437. llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
  1438. CharUnits VPtrOffset) {
  1439. assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
  1440. llvm::GlobalVariable *&VTable = VTables[RD];
  1441. if (VTable)
  1442. return VTable;
  1443. // Queue up this vtable for possible deferred emission.
  1444. CGM.addDeferredVTable(RD);
  1445. SmallString<256> Name;
  1446. llvm::raw_svector_ostream Out(Name);
  1447. getMangleContext().mangleCXXVTable(RD, Out);
  1448. const VTableLayout &VTLayout =
  1449. CGM.getItaniumVTableContext().getVTableLayout(RD);
  1450. llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
  1451. // Use pointer alignment for the vtable. Otherwise we would align them based
  1452. // on the size of the initializer which doesn't make sense as only single
  1453. // values are read.
  1454. unsigned PAlign = CGM.getTarget().getPointerAlign(0);
  1455. VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
  1456. Name, VTableType, llvm::GlobalValue::ExternalLinkage,
  1457. getContext().toCharUnitsFromBits(PAlign).getQuantity());
  1458. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1459. CGM.setGVProperties(VTable, RD);
  1460. return VTable;
  1461. }
  1462. CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
  1463. GlobalDecl GD,
  1464. Address This,
  1465. llvm::Type *Ty,
  1466. SourceLocation Loc) {
  1467. Ty = Ty->getPointerTo()->getPointerTo();
  1468. auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
  1469. llvm::Value *VTable = CGF.GetVTablePtr(This, Ty, MethodDecl->getParent());
  1470. uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  1471. llvm::Value *VFunc;
  1472. if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
  1473. VFunc = CGF.EmitVTableTypeCheckedLoad(
  1474. MethodDecl->getParent(), VTable,
  1475. VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
  1476. } else {
  1477. CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
  1478. llvm::Value *VFuncPtr =
  1479. CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
  1480. auto *VFuncLoad =
  1481. CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
  1482. // Add !invariant.load md to virtual function load to indicate that
  1483. // function didn't change inside vtable.
  1484. // It's safe to add it without -fstrict-vtable-pointers, but it would not
  1485. // help in devirtualization because it will only matter if we will have 2
  1486. // the same virtual function loads from the same vtable load, which won't
  1487. // happen without enabled devirtualization with -fstrict-vtable-pointers.
  1488. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1489. CGM.getCodeGenOpts().StrictVTablePointers)
  1490. VFuncLoad->setMetadata(
  1491. llvm::LLVMContext::MD_invariant_load,
  1492. llvm::MDNode::get(CGM.getLLVMContext(),
  1493. llvm::ArrayRef<llvm::Metadata *>()));
  1494. VFunc = VFuncLoad;
  1495. }
  1496. CGCallee Callee(GD, VFunc);
  1497. return Callee;
  1498. }
  1499. llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
  1500. CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
  1501. Address This, DeleteOrMemberCallExpr E) {
  1502. auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
  1503. auto *D = E.dyn_cast<const CXXDeleteExpr *>();
  1504. assert((CE != nullptr) ^ (D != nullptr));
  1505. assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
  1506. assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
  1507. GlobalDecl GD(Dtor, DtorType);
  1508. const CGFunctionInfo *FInfo =
  1509. &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
  1510. llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
  1511. CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
  1512. QualType ThisTy;
  1513. if (CE) {
  1514. ThisTy = CE->getObjectType();
  1515. } else {
  1516. ThisTy = D->getDestroyedType();
  1517. }
  1518. CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
  1519. QualType(), nullptr);
  1520. return nullptr;
  1521. }
  1522. void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
  1523. CodeGenVTables &VTables = CGM.getVTables();
  1524. llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
  1525. VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
  1526. }
  1527. bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
  1528. const CXXRecordDecl *RD) const {
  1529. // We don't emit available_externally vtables if we are in -fapple-kext mode
  1530. // because kext mode does not permit devirtualization.
  1531. if (CGM.getLangOpts().AppleKext)
  1532. return false;
  1533. // If the vtable is hidden then it is not safe to emit an available_externally
  1534. // copy of vtable.
  1535. if (isVTableHidden(RD))
  1536. return false;
  1537. if (CGM.getCodeGenOpts().ForceEmitVTables)
  1538. return true;
  1539. // If we don't have any not emitted inline virtual function then we are safe
  1540. // to emit an available_externally copy of vtable.
  1541. // FIXME we can still emit a copy of the vtable if we
  1542. // can emit definition of the inline functions.
  1543. if (hasAnyUnusedVirtualInlineFunction(RD))
  1544. return false;
  1545. // For a class with virtual bases, we must also be able to speculatively
  1546. // emit the VTT, because CodeGen doesn't have separate notions of "can emit
  1547. // the vtable" and "can emit the VTT". For a base subobject, this means we
  1548. // need to be able to emit non-virtual base vtables.
  1549. if (RD->getNumVBases()) {
  1550. for (const auto &B : RD->bases()) {
  1551. auto *BRD = B.getType()->getAsCXXRecordDecl();
  1552. assert(BRD && "no class for base specifier");
  1553. if (B.isVirtual() || !BRD->isDynamicClass())
  1554. continue;
  1555. if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
  1556. return false;
  1557. }
  1558. }
  1559. return true;
  1560. }
  1561. bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
  1562. if (!canSpeculativelyEmitVTableAsBaseClass(RD))
  1563. return false;
  1564. // For a complete-object vtable (or more specifically, for the VTT), we need
  1565. // to be able to speculatively emit the vtables of all dynamic virtual bases.
  1566. for (const auto &B : RD->vbases()) {
  1567. auto *BRD = B.getType()->getAsCXXRecordDecl();
  1568. assert(BRD && "no class for base specifier");
  1569. if (!BRD->isDynamicClass())
  1570. continue;
  1571. if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
  1572. return false;
  1573. }
  1574. return true;
  1575. }
  1576. static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
  1577. Address InitialPtr,
  1578. int64_t NonVirtualAdjustment,
  1579. int64_t VirtualAdjustment,
  1580. bool IsReturnAdjustment) {
  1581. if (!NonVirtualAdjustment && !VirtualAdjustment)
  1582. return InitialPtr.getPointer();
  1583. Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
  1584. // In a base-to-derived cast, the non-virtual adjustment is applied first.
  1585. if (NonVirtualAdjustment && !IsReturnAdjustment) {
  1586. V = CGF.Builder.CreateConstInBoundsByteGEP(V,
  1587. CharUnits::fromQuantity(NonVirtualAdjustment));
  1588. }
  1589. // Perform the virtual adjustment if we have one.
  1590. llvm::Value *ResultPtr;
  1591. if (VirtualAdjustment) {
  1592. llvm::Type *PtrDiffTy =
  1593. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  1594. Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
  1595. llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
  1596. llvm::Value *OffsetPtr =
  1597. CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
  1598. OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
  1599. // Load the adjustment offset from the vtable.
  1600. llvm::Value *Offset =
  1601. CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
  1602. // Adjust our pointer.
  1603. ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
  1604. } else {
  1605. ResultPtr = V.getPointer();
  1606. }
  1607. // In a derived-to-base conversion, the non-virtual adjustment is
  1608. // applied second.
  1609. if (NonVirtualAdjustment && IsReturnAdjustment) {
  1610. ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
  1611. NonVirtualAdjustment);
  1612. }
  1613. // Cast back to the original type.
  1614. return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
  1615. }
  1616. llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
  1617. Address This,
  1618. const ThisAdjustment &TA) {
  1619. return performTypeAdjustment(CGF, This, TA.NonVirtual,
  1620. TA.Virtual.Itanium.VCallOffsetOffset,
  1621. /*IsReturnAdjustment=*/false);
  1622. }
  1623. llvm::Value *
  1624. ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
  1625. const ReturnAdjustment &RA) {
  1626. return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
  1627. RA.Virtual.Itanium.VBaseOffsetOffset,
  1628. /*IsReturnAdjustment=*/true);
  1629. }
  1630. void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
  1631. RValue RV, QualType ResultType) {
  1632. if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
  1633. return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
  1634. // Destructor thunks in the ARM ABI have indeterminate results.
  1635. llvm::Type *T = CGF.ReturnValue.getElementType();
  1636. RValue Undef = RValue::get(llvm::UndefValue::get(T));
  1637. return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
  1638. }
  1639. /************************** Array allocation cookies **************************/
  1640. CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
  1641. // The array cookie is a size_t; pad that up to the element alignment.
  1642. // The cookie is actually right-justified in that space.
  1643. return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
  1644. CGM.getContext().getTypeAlignInChars(elementType));
  1645. }
  1646. Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1647. Address NewPtr,
  1648. llvm::Value *NumElements,
  1649. const CXXNewExpr *expr,
  1650. QualType ElementType) {
  1651. assert(requiresArrayCookie(expr));
  1652. unsigned AS = NewPtr.getAddressSpace();
  1653. ASTContext &Ctx = getContext();
  1654. CharUnits SizeSize = CGF.getSizeSize();
  1655. // The size of the cookie.
  1656. CharUnits CookieSize =
  1657. std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
  1658. assert(CookieSize == getArrayCookieSizeImpl(ElementType));
  1659. // Compute an offset to the cookie.
  1660. Address CookiePtr = NewPtr;
  1661. CharUnits CookieOffset = CookieSize - SizeSize;
  1662. if (!CookieOffset.isZero())
  1663. CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
  1664. // Write the number of elements into the appropriate slot.
  1665. Address NumElementsPtr =
  1666. CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
  1667. llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
  1668. // Handle the array cookie specially in ASan.
  1669. if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
  1670. (expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
  1671. CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
  1672. // The store to the CookiePtr does not need to be instrumented.
  1673. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
  1674. llvm::FunctionType *FTy =
  1675. llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
  1676. llvm::FunctionCallee F =
  1677. CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
  1678. CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
  1679. }
  1680. // Finally, compute a pointer to the actual data buffer by skipping
  1681. // over the cookie completely.
  1682. return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
  1683. }
  1684. llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1685. Address allocPtr,
  1686. CharUnits cookieSize) {
  1687. // The element size is right-justified in the cookie.
  1688. Address numElementsPtr = allocPtr;
  1689. CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
  1690. if (!numElementsOffset.isZero())
  1691. numElementsPtr =
  1692. CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
  1693. unsigned AS = allocPtr.getAddressSpace();
  1694. numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
  1695. if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
  1696. return CGF.Builder.CreateLoad(numElementsPtr);
  1697. // In asan mode emit a function call instead of a regular load and let the
  1698. // run-time deal with it: if the shadow is properly poisoned return the
  1699. // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
  1700. // We can't simply ignore this load using nosanitize metadata because
  1701. // the metadata may be lost.
  1702. llvm::FunctionType *FTy =
  1703. llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
  1704. llvm::FunctionCallee F =
  1705. CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
  1706. return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
  1707. }
  1708. CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
  1709. // ARM says that the cookie is always:
  1710. // struct array_cookie {
  1711. // std::size_t element_size; // element_size != 0
  1712. // std::size_t element_count;
  1713. // };
  1714. // But the base ABI doesn't give anything an alignment greater than
  1715. // 8, so we can dismiss this as typical ABI-author blindness to
  1716. // actual language complexity and round up to the element alignment.
  1717. return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
  1718. CGM.getContext().getTypeAlignInChars(elementType));
  1719. }
  1720. Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
  1721. Address newPtr,
  1722. llvm::Value *numElements,
  1723. const CXXNewExpr *expr,
  1724. QualType elementType) {
  1725. assert(requiresArrayCookie(expr));
  1726. // The cookie is always at the start of the buffer.
  1727. Address cookie = newPtr;
  1728. // The first element is the element size.
  1729. cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
  1730. llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
  1731. getContext().getTypeSizeInChars(elementType).getQuantity());
  1732. CGF.Builder.CreateStore(elementSize, cookie);
  1733. // The second element is the element count.
  1734. cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
  1735. CGF.Builder.CreateStore(numElements, cookie);
  1736. // Finally, compute a pointer to the actual data buffer by skipping
  1737. // over the cookie completely.
  1738. CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
  1739. return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
  1740. }
  1741. llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
  1742. Address allocPtr,
  1743. CharUnits cookieSize) {
  1744. // The number of elements is at offset sizeof(size_t) relative to
  1745. // the allocated pointer.
  1746. Address numElementsPtr
  1747. = CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
  1748. numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
  1749. return CGF.Builder.CreateLoad(numElementsPtr);
  1750. }
  1751. /*********************** Static local initialization **************************/
  1752. static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
  1753. llvm::PointerType *GuardPtrTy) {
  1754. // int __cxa_guard_acquire(__guard *guard_object);
  1755. llvm::FunctionType *FTy =
  1756. llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
  1757. GuardPtrTy, /*isVarArg=*/false);
  1758. return CGM.CreateRuntimeFunction(
  1759. FTy, "__cxa_guard_acquire",
  1760. llvm::AttributeList::get(CGM.getLLVMContext(),
  1761. llvm::AttributeList::FunctionIndex,
  1762. llvm::Attribute::NoUnwind));
  1763. }
  1764. static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
  1765. llvm::PointerType *GuardPtrTy) {
  1766. // void __cxa_guard_release(__guard *guard_object);
  1767. llvm::FunctionType *FTy =
  1768. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  1769. return CGM.CreateRuntimeFunction(
  1770. FTy, "__cxa_guard_release",
  1771. llvm::AttributeList::get(CGM.getLLVMContext(),
  1772. llvm::AttributeList::FunctionIndex,
  1773. llvm::Attribute::NoUnwind));
  1774. }
  1775. static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
  1776. llvm::PointerType *GuardPtrTy) {
  1777. // void __cxa_guard_abort(__guard *guard_object);
  1778. llvm::FunctionType *FTy =
  1779. llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
  1780. return CGM.CreateRuntimeFunction(
  1781. FTy, "__cxa_guard_abort",
  1782. llvm::AttributeList::get(CGM.getLLVMContext(),
  1783. llvm::AttributeList::FunctionIndex,
  1784. llvm::Attribute::NoUnwind));
  1785. }
  1786. namespace {
  1787. struct CallGuardAbort final : EHScopeStack::Cleanup {
  1788. llvm::GlobalVariable *Guard;
  1789. CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
  1790. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1791. CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
  1792. Guard);
  1793. }
  1794. };
  1795. }
  1796. /// The ARM code here follows the Itanium code closely enough that we
  1797. /// just special-case it at particular places.
  1798. void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
  1799. const VarDecl &D,
  1800. llvm::GlobalVariable *var,
  1801. bool shouldPerformInit) {
  1802. CGBuilderTy &Builder = CGF.Builder;
  1803. // Inline variables that weren't instantiated from variable templates have
  1804. // partially-ordered initialization within their translation unit.
  1805. bool NonTemplateInline =
  1806. D.isInline() &&
  1807. !isTemplateInstantiation(D.getTemplateSpecializationKind());
  1808. // We only need to use thread-safe statics for local non-TLS variables and
  1809. // inline variables; other global initialization is always single-threaded
  1810. // or (through lazy dynamic loading in multiple threads) unsequenced.
  1811. bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
  1812. (D.isLocalVarDecl() || NonTemplateInline) &&
  1813. !D.getTLSKind();
  1814. // If we have a global variable with internal linkage and thread-safe statics
  1815. // are disabled, we can just let the guard variable be of type i8.
  1816. bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
  1817. llvm::IntegerType *guardTy;
  1818. CharUnits guardAlignment;
  1819. if (useInt8GuardVariable) {
  1820. guardTy = CGF.Int8Ty;
  1821. guardAlignment = CharUnits::One();
  1822. } else {
  1823. // Guard variables are 64 bits in the generic ABI and size width on ARM
  1824. // (i.e. 32-bit on AArch32, 64-bit on AArch64).
  1825. if (UseARMGuardVarABI) {
  1826. guardTy = CGF.SizeTy;
  1827. guardAlignment = CGF.getSizeAlign();
  1828. } else {
  1829. guardTy = CGF.Int64Ty;
  1830. guardAlignment = CharUnits::fromQuantity(
  1831. CGM.getDataLayout().getABITypeAlignment(guardTy));
  1832. }
  1833. }
  1834. llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
  1835. // Create the guard variable if we don't already have it (as we
  1836. // might if we're double-emitting this function body).
  1837. llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
  1838. if (!guard) {
  1839. // Mangle the name for the guard.
  1840. SmallString<256> guardName;
  1841. {
  1842. llvm::raw_svector_ostream out(guardName);
  1843. getMangleContext().mangleStaticGuardVariable(&D, out);
  1844. }
  1845. // Create the guard variable with a zero-initializer.
  1846. // Just absorb linkage and visibility from the guarded variable.
  1847. guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
  1848. false, var->getLinkage(),
  1849. llvm::ConstantInt::get(guardTy, 0),
  1850. guardName.str());
  1851. guard->setDSOLocal(var->isDSOLocal());
  1852. guard->setVisibility(var->getVisibility());
  1853. // If the variable is thread-local, so is its guard variable.
  1854. guard->setThreadLocalMode(var->getThreadLocalMode());
  1855. guard->setAlignment(guardAlignment.getAsAlign());
  1856. // The ABI says: "It is suggested that it be emitted in the same COMDAT
  1857. // group as the associated data object." In practice, this doesn't work for
  1858. // non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
  1859. llvm::Comdat *C = var->getComdat();
  1860. if (!D.isLocalVarDecl() && C &&
  1861. (CGM.getTarget().getTriple().isOSBinFormatELF() ||
  1862. CGM.getTarget().getTriple().isOSBinFormatWasm())) {
  1863. guard->setComdat(C);
  1864. // An inline variable's guard function is run from the per-TU
  1865. // initialization function, not via a dedicated global ctor function, so
  1866. // we can't put it in a comdat.
  1867. if (!NonTemplateInline)
  1868. CGF.CurFn->setComdat(C);
  1869. } else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
  1870. guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
  1871. }
  1872. CGM.setStaticLocalDeclGuardAddress(&D, guard);
  1873. }
  1874. Address guardAddr = Address(guard, guardAlignment);
  1875. // Test whether the variable has completed initialization.
  1876. //
  1877. // Itanium C++ ABI 3.3.2:
  1878. // The following is pseudo-code showing how these functions can be used:
  1879. // if (obj_guard.first_byte == 0) {
  1880. // if ( __cxa_guard_acquire (&obj_guard) ) {
  1881. // try {
  1882. // ... initialize the object ...;
  1883. // } catch (...) {
  1884. // __cxa_guard_abort (&obj_guard);
  1885. // throw;
  1886. // }
  1887. // ... queue object destructor with __cxa_atexit() ...;
  1888. // __cxa_guard_release (&obj_guard);
  1889. // }
  1890. // }
  1891. // Load the first byte of the guard variable.
  1892. llvm::LoadInst *LI =
  1893. Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
  1894. // Itanium ABI:
  1895. // An implementation supporting thread-safety on multiprocessor
  1896. // systems must also guarantee that references to the initialized
  1897. // object do not occur before the load of the initialization flag.
  1898. //
  1899. // In LLVM, we do this by marking the load Acquire.
  1900. if (threadsafe)
  1901. LI->setAtomic(llvm::AtomicOrdering::Acquire);
  1902. // For ARM, we should only check the first bit, rather than the entire byte:
  1903. //
  1904. // ARM C++ ABI 3.2.3.1:
  1905. // To support the potential use of initialization guard variables
  1906. // as semaphores that are the target of ARM SWP and LDREX/STREX
  1907. // synchronizing instructions we define a static initialization
  1908. // guard variable to be a 4-byte aligned, 4-byte word with the
  1909. // following inline access protocol.
  1910. // #define INITIALIZED 1
  1911. // if ((obj_guard & INITIALIZED) != INITIALIZED) {
  1912. // if (__cxa_guard_acquire(&obj_guard))
  1913. // ...
  1914. // }
  1915. //
  1916. // and similarly for ARM64:
  1917. //
  1918. // ARM64 C++ ABI 3.2.2:
  1919. // This ABI instead only specifies the value bit 0 of the static guard
  1920. // variable; all other bits are platform defined. Bit 0 shall be 0 when the
  1921. // variable is not initialized and 1 when it is.
  1922. llvm::Value *V =
  1923. (UseARMGuardVarABI && !useInt8GuardVariable)
  1924. ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
  1925. : LI;
  1926. llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
  1927. llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
  1928. llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
  1929. // Check if the first byte of the guard variable is zero.
  1930. CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
  1931. CodeGenFunction::GuardKind::VariableGuard, &D);
  1932. CGF.EmitBlock(InitCheckBlock);
  1933. // Variables used when coping with thread-safe statics and exceptions.
  1934. if (threadsafe) {
  1935. // Call __cxa_guard_acquire.
  1936. llvm::Value *V
  1937. = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
  1938. llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
  1939. Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
  1940. InitBlock, EndBlock);
  1941. // Call __cxa_guard_abort along the exceptional edge.
  1942. CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
  1943. CGF.EmitBlock(InitBlock);
  1944. }
  1945. // Emit the initializer and add a global destructor if appropriate.
  1946. CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
  1947. if (threadsafe) {
  1948. // Pop the guard-abort cleanup if we pushed one.
  1949. CGF.PopCleanupBlock();
  1950. // Call __cxa_guard_release. This cannot throw.
  1951. CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
  1952. guardAddr.getPointer());
  1953. } else {
  1954. Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
  1955. }
  1956. CGF.EmitBlock(EndBlock);
  1957. }
  1958. /// Register a global destructor using __cxa_atexit.
  1959. static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
  1960. llvm::FunctionCallee dtor,
  1961. llvm::Constant *addr, bool TLS) {
  1962. assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
  1963. "__cxa_atexit is disabled");
  1964. const char *Name = "__cxa_atexit";
  1965. if (TLS) {
  1966. const llvm::Triple &T = CGF.getTarget().getTriple();
  1967. Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
  1968. }
  1969. // We're assuming that the destructor function is something we can
  1970. // reasonably call with the default CC. Go ahead and cast it to the
  1971. // right prototype.
  1972. llvm::Type *dtorTy =
  1973. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
  1974. // Preserve address space of addr.
  1975. auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
  1976. auto AddrInt8PtrTy =
  1977. AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
  1978. // Create a variable that binds the atexit to this shared object.
  1979. llvm::Constant *handle =
  1980. CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
  1981. auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
  1982. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1983. // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
  1984. llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
  1985. llvm::FunctionType *atexitTy =
  1986. llvm::FunctionType::get(CGF.IntTy, paramTys, false);
  1987. // Fetch the actual function.
  1988. llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
  1989. if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
  1990. fn->setDoesNotThrow();
  1991. if (!addr)
  1992. // addr is null when we are trying to register a dtor annotated with
  1993. // __attribute__((destructor)) in a constructor function. Using null here is
  1994. // okay because this argument is just passed back to the destructor
  1995. // function.
  1996. addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  1997. llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
  1998. cast<llvm::Constant>(dtor.getCallee()), dtorTy),
  1999. llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
  2000. handle};
  2001. CGF.EmitNounwindRuntimeCall(atexit, args);
  2002. }
  2003. void CodeGenModule::registerGlobalDtorsWithAtExit() {
  2004. for (const auto I : DtorsUsingAtExit) {
  2005. int Priority = I.first;
  2006. const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
  2007. // Create a function that registers destructors that have the same priority.
  2008. //
  2009. // Since constructor functions are run in non-descending order of their
  2010. // priorities, destructors are registered in non-descending order of their
  2011. // priorities, and since destructor functions are run in the reverse order
  2012. // of their registration, destructor functions are run in non-ascending
  2013. // order of their priorities.
  2014. CodeGenFunction CGF(*this);
  2015. std::string GlobalInitFnName =
  2016. std::string("__GLOBAL_init_") + llvm::to_string(Priority);
  2017. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  2018. llvm::Function *GlobalInitFn = CreateGlobalInitOrDestructFunction(
  2019. FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
  2020. SourceLocation());
  2021. ASTContext &Ctx = getContext();
  2022. QualType ReturnTy = Ctx.VoidTy;
  2023. QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
  2024. FunctionDecl *FD = FunctionDecl::Create(
  2025. Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
  2026. &Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
  2027. false, false);
  2028. CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
  2029. getTypes().arrangeNullaryFunction(), FunctionArgList(),
  2030. SourceLocation(), SourceLocation());
  2031. for (auto *Dtor : Dtors) {
  2032. // Register the destructor function calling __cxa_atexit if it is
  2033. // available. Otherwise fall back on calling atexit.
  2034. if (getCodeGenOpts().CXAAtExit)
  2035. emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
  2036. else
  2037. CGF.registerGlobalDtorWithAtExit(Dtor);
  2038. }
  2039. CGF.FinishFunction();
  2040. AddGlobalCtor(GlobalInitFn, Priority, nullptr);
  2041. }
  2042. }
  2043. /// Register a global destructor as best as we know how.
  2044. void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
  2045. llvm::FunctionCallee dtor,
  2046. llvm::Constant *addr) {
  2047. if (D.isNoDestroy(CGM.getContext()))
  2048. return;
  2049. // emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
  2050. // or __cxa_atexit depending on whether this VarDecl is a thread-local storage
  2051. // or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
  2052. // We can always use __cxa_thread_atexit.
  2053. if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
  2054. return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
  2055. // In Apple kexts, we want to add a global destructor entry.
  2056. // FIXME: shouldn't this be guarded by some variable?
  2057. if (CGM.getLangOpts().AppleKext) {
  2058. // Generate a global destructor entry.
  2059. return CGM.AddCXXDtorEntry(dtor, addr);
  2060. }
  2061. CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
  2062. }
  2063. static bool isThreadWrapperReplaceable(const VarDecl *VD,
  2064. CodeGen::CodeGenModule &CGM) {
  2065. assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
  2066. // Darwin prefers to have references to thread local variables to go through
  2067. // the thread wrapper instead of directly referencing the backing variable.
  2068. return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  2069. CGM.getTarget().getTriple().isOSDarwin();
  2070. }
  2071. /// Get the appropriate linkage for the wrapper function. This is essentially
  2072. /// the weak form of the variable's linkage; every translation unit which needs
  2073. /// the wrapper emits a copy, and we want the linker to merge them.
  2074. static llvm::GlobalValue::LinkageTypes
  2075. getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
  2076. llvm::GlobalValue::LinkageTypes VarLinkage =
  2077. CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
  2078. // For internal linkage variables, we don't need an external or weak wrapper.
  2079. if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
  2080. return VarLinkage;
  2081. // If the thread wrapper is replaceable, give it appropriate linkage.
  2082. if (isThreadWrapperReplaceable(VD, CGM))
  2083. if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
  2084. !llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
  2085. return VarLinkage;
  2086. return llvm::GlobalValue::WeakODRLinkage;
  2087. }
  2088. llvm::Function *
  2089. ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
  2090. llvm::Value *Val) {
  2091. // Mangle the name for the thread_local wrapper function.
  2092. SmallString<256> WrapperName;
  2093. {
  2094. llvm::raw_svector_ostream Out(WrapperName);
  2095. getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
  2096. }
  2097. // FIXME: If VD is a definition, we should regenerate the function attributes
  2098. // before returning.
  2099. if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
  2100. return cast<llvm::Function>(V);
  2101. QualType RetQT = VD->getType();
  2102. if (RetQT->isReferenceType())
  2103. RetQT = RetQT.getNonReferenceType();
  2104. const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2105. getContext().getPointerType(RetQT), FunctionArgList());
  2106. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
  2107. llvm::Function *Wrapper =
  2108. llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
  2109. WrapperName.str(), &CGM.getModule());
  2110. CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
  2111. // Always resolve references to the wrapper at link time.
  2112. if (!Wrapper->hasLocalLinkage())
  2113. if (!isThreadWrapperReplaceable(VD, CGM) ||
  2114. llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
  2115. llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
  2116. VD->getVisibility() == HiddenVisibility)
  2117. Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2118. if (isThreadWrapperReplaceable(VD, CGM)) {
  2119. Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2120. Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
  2121. }
  2122. ThreadWrappers.push_back({VD, Wrapper});
  2123. return Wrapper;
  2124. }
  2125. void ItaniumCXXABI::EmitThreadLocalInitFuncs(
  2126. CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
  2127. ArrayRef<llvm::Function *> CXXThreadLocalInits,
  2128. ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
  2129. llvm::Function *InitFunc = nullptr;
  2130. // Separate initializers into those with ordered (or partially-ordered)
  2131. // initialization and those with unordered initialization.
  2132. llvm::SmallVector<llvm::Function *, 8> OrderedInits;
  2133. llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
  2134. for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
  2135. if (isTemplateInstantiation(
  2136. CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
  2137. UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
  2138. CXXThreadLocalInits[I];
  2139. else
  2140. OrderedInits.push_back(CXXThreadLocalInits[I]);
  2141. }
  2142. if (!OrderedInits.empty()) {
  2143. // Generate a guarded initialization function.
  2144. llvm::FunctionType *FTy =
  2145. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  2146. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2147. InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", FI,
  2148. SourceLocation(),
  2149. /*TLS=*/true);
  2150. llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
  2151. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
  2152. llvm::GlobalVariable::InternalLinkage,
  2153. llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
  2154. Guard->setThreadLocal(true);
  2155. CharUnits GuardAlign = CharUnits::One();
  2156. Guard->setAlignment(GuardAlign.getAsAlign());
  2157. CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
  2158. InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
  2159. // On Darwin platforms, use CXX_FAST_TLS calling convention.
  2160. if (CGM.getTarget().getTriple().isOSDarwin()) {
  2161. InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2162. InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
  2163. }
  2164. }
  2165. // Create declarations for thread wrappers for all thread-local variables
  2166. // with non-discardable definitions in this translation unit.
  2167. for (const VarDecl *VD : CXXThreadLocals) {
  2168. if (VD->hasDefinition() &&
  2169. !isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
  2170. llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
  2171. getOrCreateThreadLocalWrapper(VD, GV);
  2172. }
  2173. }
  2174. // Emit all referenced thread wrappers.
  2175. for (auto VDAndWrapper : ThreadWrappers) {
  2176. const VarDecl *VD = VDAndWrapper.first;
  2177. llvm::GlobalVariable *Var =
  2178. cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
  2179. llvm::Function *Wrapper = VDAndWrapper.second;
  2180. // Some targets require that all access to thread local variables go through
  2181. // the thread wrapper. This means that we cannot attempt to create a thread
  2182. // wrapper or a thread helper.
  2183. if (!VD->hasDefinition()) {
  2184. if (isThreadWrapperReplaceable(VD, CGM)) {
  2185. Wrapper->setLinkage(llvm::Function::ExternalLinkage);
  2186. continue;
  2187. }
  2188. // If this isn't a TU in which this variable is defined, the thread
  2189. // wrapper is discardable.
  2190. if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
  2191. Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
  2192. }
  2193. CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
  2194. // Mangle the name for the thread_local initialization function.
  2195. SmallString<256> InitFnName;
  2196. {
  2197. llvm::raw_svector_ostream Out(InitFnName);
  2198. getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
  2199. }
  2200. llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
  2201. // If we have a definition for the variable, emit the initialization
  2202. // function as an alias to the global Init function (if any). Otherwise,
  2203. // produce a declaration of the initialization function.
  2204. llvm::GlobalValue *Init = nullptr;
  2205. bool InitIsInitFunc = false;
  2206. bool HasConstantInitialization = false;
  2207. if (!usesThreadWrapperFunction(VD)) {
  2208. HasConstantInitialization = true;
  2209. } else if (VD->hasDefinition()) {
  2210. InitIsInitFunc = true;
  2211. llvm::Function *InitFuncToUse = InitFunc;
  2212. if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
  2213. InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
  2214. if (InitFuncToUse)
  2215. Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
  2216. InitFuncToUse);
  2217. } else {
  2218. // Emit a weak global function referring to the initialization function.
  2219. // This function will not exist if the TU defining the thread_local
  2220. // variable in question does not need any dynamic initialization for
  2221. // its thread_local variables.
  2222. Init = llvm::Function::Create(InitFnTy,
  2223. llvm::GlobalVariable::ExternalWeakLinkage,
  2224. InitFnName.str(), &CGM.getModule());
  2225. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2226. CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
  2227. cast<llvm::Function>(Init));
  2228. }
  2229. if (Init) {
  2230. Init->setVisibility(Var->getVisibility());
  2231. Init->setDSOLocal(Var->isDSOLocal());
  2232. }
  2233. llvm::LLVMContext &Context = CGM.getModule().getContext();
  2234. llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
  2235. CGBuilderTy Builder(CGM, Entry);
  2236. if (HasConstantInitialization) {
  2237. // No dynamic initialization to invoke.
  2238. } else if (InitIsInitFunc) {
  2239. if (Init) {
  2240. llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
  2241. if (isThreadWrapperReplaceable(VD, CGM)) {
  2242. CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2243. llvm::Function *Fn =
  2244. cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
  2245. Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
  2246. }
  2247. }
  2248. } else {
  2249. // Don't know whether we have an init function. Call it if it exists.
  2250. llvm::Value *Have = Builder.CreateIsNotNull(Init);
  2251. llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
  2252. llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
  2253. Builder.CreateCondBr(Have, InitBB, ExitBB);
  2254. Builder.SetInsertPoint(InitBB);
  2255. Builder.CreateCall(InitFnTy, Init);
  2256. Builder.CreateBr(ExitBB);
  2257. Builder.SetInsertPoint(ExitBB);
  2258. }
  2259. // For a reference, the result of the wrapper function is a pointer to
  2260. // the referenced object.
  2261. llvm::Value *Val = Var;
  2262. if (VD->getType()->isReferenceType()) {
  2263. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  2264. Val = Builder.CreateAlignedLoad(Val, Align);
  2265. }
  2266. if (Val->getType() != Wrapper->getReturnType())
  2267. Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
  2268. Val, Wrapper->getReturnType(), "");
  2269. Builder.CreateRet(Val);
  2270. }
  2271. }
  2272. LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
  2273. const VarDecl *VD,
  2274. QualType LValType) {
  2275. llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
  2276. llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
  2277. llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
  2278. CallVal->setCallingConv(Wrapper->getCallingConv());
  2279. LValue LV;
  2280. if (VD->getType()->isReferenceType())
  2281. LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
  2282. else
  2283. LV = CGF.MakeAddrLValue(CallVal, LValType,
  2284. CGF.getContext().getDeclAlign(VD));
  2285. // FIXME: need setObjCGCLValueClass?
  2286. return LV;
  2287. }
  2288. /// Return whether the given global decl needs a VTT parameter, which it does
  2289. /// if it's a base constructor or destructor with virtual bases.
  2290. bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
  2291. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  2292. // We don't have any virtual bases, just return early.
  2293. if (!MD->getParent()->getNumVBases())
  2294. return false;
  2295. // Check if we have a base constructor.
  2296. if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
  2297. return true;
  2298. // Check if we have a base destructor.
  2299. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  2300. return true;
  2301. return false;
  2302. }
  2303. namespace {
  2304. class ItaniumRTTIBuilder {
  2305. CodeGenModule &CGM; // Per-module state.
  2306. llvm::LLVMContext &VMContext;
  2307. const ItaniumCXXABI &CXXABI; // Per-module state.
  2308. /// Fields - The fields of the RTTI descriptor currently being built.
  2309. SmallVector<llvm::Constant *, 16> Fields;
  2310. /// GetAddrOfTypeName - Returns the mangled type name of the given type.
  2311. llvm::GlobalVariable *
  2312. GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
  2313. /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
  2314. /// descriptor of the given type.
  2315. llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
  2316. /// BuildVTablePointer - Build the vtable pointer for the given type.
  2317. void BuildVTablePointer(const Type *Ty);
  2318. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  2319. /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
  2320. void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
  2321. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  2322. /// classes with bases that do not satisfy the abi::__si_class_type_info
  2323. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  2324. void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
  2325. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
  2326. /// for pointer types.
  2327. void BuildPointerTypeInfo(QualType PointeeTy);
  2328. /// BuildObjCObjectTypeInfo - Build the appropriate kind of
  2329. /// type_info for an object type.
  2330. void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
  2331. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  2332. /// struct, used for member pointer types.
  2333. void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
  2334. public:
  2335. ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
  2336. : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
  2337. // Pointer type info flags.
  2338. enum {
  2339. /// PTI_Const - Type has const qualifier.
  2340. PTI_Const = 0x1,
  2341. /// PTI_Volatile - Type has volatile qualifier.
  2342. PTI_Volatile = 0x2,
  2343. /// PTI_Restrict - Type has restrict qualifier.
  2344. PTI_Restrict = 0x4,
  2345. /// PTI_Incomplete - Type is incomplete.
  2346. PTI_Incomplete = 0x8,
  2347. /// PTI_ContainingClassIncomplete - Containing class is incomplete.
  2348. /// (in pointer to member).
  2349. PTI_ContainingClassIncomplete = 0x10,
  2350. /// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
  2351. //PTI_TransactionSafe = 0x20,
  2352. /// PTI_Noexcept - Pointee is noexcept function (C++1z).
  2353. PTI_Noexcept = 0x40,
  2354. };
  2355. // VMI type info flags.
  2356. enum {
  2357. /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
  2358. VMI_NonDiamondRepeat = 0x1,
  2359. /// VMI_DiamondShaped - Class is diamond shaped.
  2360. VMI_DiamondShaped = 0x2
  2361. };
  2362. // Base class type info flags.
  2363. enum {
  2364. /// BCTI_Virtual - Base class is virtual.
  2365. BCTI_Virtual = 0x1,
  2366. /// BCTI_Public - Base class is public.
  2367. BCTI_Public = 0x2
  2368. };
  2369. /// BuildTypeInfo - Build the RTTI type info struct for the given type, or
  2370. /// link to an existing RTTI descriptor if one already exists.
  2371. llvm::Constant *BuildTypeInfo(QualType Ty);
  2372. /// BuildTypeInfo - Build the RTTI type info struct for the given type.
  2373. llvm::Constant *BuildTypeInfo(
  2374. QualType Ty,
  2375. llvm::GlobalVariable::LinkageTypes Linkage,
  2376. llvm::GlobalValue::VisibilityTypes Visibility,
  2377. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
  2378. };
  2379. }
  2380. llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
  2381. QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
  2382. SmallString<256> Name;
  2383. llvm::raw_svector_ostream Out(Name);
  2384. CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
  2385. // We know that the mangled name of the type starts at index 4 of the
  2386. // mangled name of the typename, so we can just index into it in order to
  2387. // get the mangled name of the type.
  2388. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
  2389. Name.substr(4));
  2390. auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
  2391. llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
  2392. Name, Init->getType(), Linkage, Align.getQuantity());
  2393. GV->setInitializer(Init);
  2394. return GV;
  2395. }
  2396. llvm::Constant *
  2397. ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
  2398. // Mangle the RTTI name.
  2399. SmallString<256> Name;
  2400. llvm::raw_svector_ostream Out(Name);
  2401. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2402. // Look for an existing global.
  2403. llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
  2404. if (!GV) {
  2405. // Create a new global variable.
  2406. // Note for the future: If we would ever like to do deferred emission of
  2407. // RTTI, check if emitting vtables opportunistically need any adjustment.
  2408. GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
  2409. /*isConstant=*/true,
  2410. llvm::GlobalValue::ExternalLinkage, nullptr,
  2411. Name);
  2412. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  2413. CGM.setGVProperties(GV, RD);
  2414. }
  2415. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  2416. }
  2417. /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
  2418. /// info for that type is defined in the standard library.
  2419. static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
  2420. // Itanium C++ ABI 2.9.2:
  2421. // Basic type information (e.g. for "int", "bool", etc.) will be kept in
  2422. // the run-time support library. Specifically, the run-time support
  2423. // library should contain type_info objects for the types X, X* and
  2424. // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
  2425. // unsigned char, signed char, short, unsigned short, int, unsigned int,
  2426. // long, unsigned long, long long, unsigned long long, float, double,
  2427. // long double, char16_t, char32_t, and the IEEE 754r decimal and
  2428. // half-precision floating point types.
  2429. //
  2430. // GCC also emits RTTI for __int128.
  2431. // FIXME: We do not emit RTTI information for decimal types here.
  2432. // Types added here must also be added to EmitFundamentalRTTIDescriptors.
  2433. switch (Ty->getKind()) {
  2434. case BuiltinType::Void:
  2435. case BuiltinType::NullPtr:
  2436. case BuiltinType::Bool:
  2437. case BuiltinType::WChar_S:
  2438. case BuiltinType::WChar_U:
  2439. case BuiltinType::Char_U:
  2440. case BuiltinType::Char_S:
  2441. case BuiltinType::UChar:
  2442. case BuiltinType::SChar:
  2443. case BuiltinType::Short:
  2444. case BuiltinType::UShort:
  2445. case BuiltinType::Int:
  2446. case BuiltinType::UInt:
  2447. case BuiltinType::Long:
  2448. case BuiltinType::ULong:
  2449. case BuiltinType::LongLong:
  2450. case BuiltinType::ULongLong:
  2451. case BuiltinType::Half:
  2452. case BuiltinType::Float:
  2453. case BuiltinType::Double:
  2454. case BuiltinType::LongDouble:
  2455. case BuiltinType::Float16:
  2456. case BuiltinType::Float128:
  2457. case BuiltinType::Char8:
  2458. case BuiltinType::Char16:
  2459. case BuiltinType::Char32:
  2460. case BuiltinType::Int128:
  2461. case BuiltinType::UInt128:
  2462. return true;
  2463. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2464. case BuiltinType::Id:
  2465. #include "clang/Basic/OpenCLImageTypes.def"
  2466. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  2467. case BuiltinType::Id:
  2468. #include "clang/Basic/OpenCLExtensionTypes.def"
  2469. case BuiltinType::OCLSampler:
  2470. case BuiltinType::OCLEvent:
  2471. case BuiltinType::OCLClkEvent:
  2472. case BuiltinType::OCLQueue:
  2473. case BuiltinType::OCLReserveID:
  2474. #define SVE_TYPE(Name, Id, SingletonId) \
  2475. case BuiltinType::Id:
  2476. #include "clang/Basic/AArch64SVEACLETypes.def"
  2477. case BuiltinType::ShortAccum:
  2478. case BuiltinType::Accum:
  2479. case BuiltinType::LongAccum:
  2480. case BuiltinType::UShortAccum:
  2481. case BuiltinType::UAccum:
  2482. case BuiltinType::ULongAccum:
  2483. case BuiltinType::ShortFract:
  2484. case BuiltinType::Fract:
  2485. case BuiltinType::LongFract:
  2486. case BuiltinType::UShortFract:
  2487. case BuiltinType::UFract:
  2488. case BuiltinType::ULongFract:
  2489. case BuiltinType::SatShortAccum:
  2490. case BuiltinType::SatAccum:
  2491. case BuiltinType::SatLongAccum:
  2492. case BuiltinType::SatUShortAccum:
  2493. case BuiltinType::SatUAccum:
  2494. case BuiltinType::SatULongAccum:
  2495. case BuiltinType::SatShortFract:
  2496. case BuiltinType::SatFract:
  2497. case BuiltinType::SatLongFract:
  2498. case BuiltinType::SatUShortFract:
  2499. case BuiltinType::SatUFract:
  2500. case BuiltinType::SatULongFract:
  2501. return false;
  2502. case BuiltinType::Dependent:
  2503. #define BUILTIN_TYPE(Id, SingletonId)
  2504. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  2505. case BuiltinType::Id:
  2506. #include "clang/AST/BuiltinTypes.def"
  2507. llvm_unreachable("asking for RRTI for a placeholder type!");
  2508. case BuiltinType::ObjCId:
  2509. case BuiltinType::ObjCClass:
  2510. case BuiltinType::ObjCSel:
  2511. llvm_unreachable("FIXME: Objective-C types are unsupported!");
  2512. }
  2513. llvm_unreachable("Invalid BuiltinType Kind!");
  2514. }
  2515. static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
  2516. QualType PointeeTy = PointerTy->getPointeeType();
  2517. const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
  2518. if (!BuiltinTy)
  2519. return false;
  2520. // Check the qualifiers.
  2521. Qualifiers Quals = PointeeTy.getQualifiers();
  2522. Quals.removeConst();
  2523. if (!Quals.empty())
  2524. return false;
  2525. return TypeInfoIsInStandardLibrary(BuiltinTy);
  2526. }
  2527. /// IsStandardLibraryRTTIDescriptor - Returns whether the type
  2528. /// information for the given type exists in the standard library.
  2529. static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
  2530. // Type info for builtin types is defined in the standard library.
  2531. if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
  2532. return TypeInfoIsInStandardLibrary(BuiltinTy);
  2533. // Type info for some pointer types to builtin types is defined in the
  2534. // standard library.
  2535. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  2536. return TypeInfoIsInStandardLibrary(PointerTy);
  2537. return false;
  2538. }
  2539. /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
  2540. /// the given type exists somewhere else, and that we should not emit the type
  2541. /// information in this translation unit. Assumes that it is not a
  2542. /// standard-library type.
  2543. static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
  2544. QualType Ty) {
  2545. ASTContext &Context = CGM.getContext();
  2546. // If RTTI is disabled, assume it might be disabled in the
  2547. // translation unit that defines any potential key function, too.
  2548. if (!Context.getLangOpts().RTTI) return false;
  2549. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  2550. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  2551. if (!RD->hasDefinition())
  2552. return false;
  2553. if (!RD->isDynamicClass())
  2554. return false;
  2555. // FIXME: this may need to be reconsidered if the key function
  2556. // changes.
  2557. // N.B. We must always emit the RTTI data ourselves if there exists a key
  2558. // function.
  2559. bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
  2560. // Don't import the RTTI but emit it locally.
  2561. if (CGM.getTriple().isWindowsGNUEnvironment())
  2562. return false;
  2563. if (CGM.getVTables().isVTableExternal(RD))
  2564. return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
  2565. ? false
  2566. : true;
  2567. if (IsDLLImport)
  2568. return true;
  2569. }
  2570. return false;
  2571. }
  2572. /// IsIncompleteClassType - Returns whether the given record type is incomplete.
  2573. static bool IsIncompleteClassType(const RecordType *RecordTy) {
  2574. return !RecordTy->getDecl()->isCompleteDefinition();
  2575. }
  2576. /// ContainsIncompleteClassType - Returns whether the given type contains an
  2577. /// incomplete class type. This is true if
  2578. ///
  2579. /// * The given type is an incomplete class type.
  2580. /// * The given type is a pointer type whose pointee type contains an
  2581. /// incomplete class type.
  2582. /// * The given type is a member pointer type whose class is an incomplete
  2583. /// class type.
  2584. /// * The given type is a member pointer type whoise pointee type contains an
  2585. /// incomplete class type.
  2586. /// is an indirect or direct pointer to an incomplete class type.
  2587. static bool ContainsIncompleteClassType(QualType Ty) {
  2588. if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
  2589. if (IsIncompleteClassType(RecordTy))
  2590. return true;
  2591. }
  2592. if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
  2593. return ContainsIncompleteClassType(PointerTy->getPointeeType());
  2594. if (const MemberPointerType *MemberPointerTy =
  2595. dyn_cast<MemberPointerType>(Ty)) {
  2596. // Check if the class type is incomplete.
  2597. const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
  2598. if (IsIncompleteClassType(ClassType))
  2599. return true;
  2600. return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
  2601. }
  2602. return false;
  2603. }
  2604. // CanUseSingleInheritance - Return whether the given record decl has a "single,
  2605. // public, non-virtual base at offset zero (i.e. the derived class is dynamic
  2606. // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
  2607. static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
  2608. // Check the number of bases.
  2609. if (RD->getNumBases() != 1)
  2610. return false;
  2611. // Get the base.
  2612. CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
  2613. // Check that the base is not virtual.
  2614. if (Base->isVirtual())
  2615. return false;
  2616. // Check that the base is public.
  2617. if (Base->getAccessSpecifier() != AS_public)
  2618. return false;
  2619. // Check that the class is dynamic iff the base is.
  2620. auto *BaseDecl =
  2621. cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
  2622. if (!BaseDecl->isEmpty() &&
  2623. BaseDecl->isDynamicClass() != RD->isDynamicClass())
  2624. return false;
  2625. return true;
  2626. }
  2627. void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
  2628. // abi::__class_type_info.
  2629. static const char * const ClassTypeInfo =
  2630. "_ZTVN10__cxxabiv117__class_type_infoE";
  2631. // abi::__si_class_type_info.
  2632. static const char * const SIClassTypeInfo =
  2633. "_ZTVN10__cxxabiv120__si_class_type_infoE";
  2634. // abi::__vmi_class_type_info.
  2635. static const char * const VMIClassTypeInfo =
  2636. "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
  2637. const char *VTableName = nullptr;
  2638. switch (Ty->getTypeClass()) {
  2639. #define TYPE(Class, Base)
  2640. #define ABSTRACT_TYPE(Class, Base)
  2641. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2642. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2643. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2644. #include "clang/AST/TypeNodes.inc"
  2645. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  2646. case Type::LValueReference:
  2647. case Type::RValueReference:
  2648. llvm_unreachable("References shouldn't get here");
  2649. case Type::Auto:
  2650. case Type::DeducedTemplateSpecialization:
  2651. llvm_unreachable("Undeduced type shouldn't get here");
  2652. case Type::Pipe:
  2653. llvm_unreachable("Pipe types shouldn't get here");
  2654. case Type::Builtin:
  2655. // GCC treats vector and complex types as fundamental types.
  2656. case Type::Vector:
  2657. case Type::ExtVector:
  2658. case Type::Complex:
  2659. case Type::Atomic:
  2660. // FIXME: GCC treats block pointers as fundamental types?!
  2661. case Type::BlockPointer:
  2662. // abi::__fundamental_type_info.
  2663. VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
  2664. break;
  2665. case Type::ConstantArray:
  2666. case Type::IncompleteArray:
  2667. case Type::VariableArray:
  2668. // abi::__array_type_info.
  2669. VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
  2670. break;
  2671. case Type::FunctionNoProto:
  2672. case Type::FunctionProto:
  2673. // abi::__function_type_info.
  2674. VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
  2675. break;
  2676. case Type::Enum:
  2677. // abi::__enum_type_info.
  2678. VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
  2679. break;
  2680. case Type::Record: {
  2681. const CXXRecordDecl *RD =
  2682. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  2683. if (!RD->hasDefinition() || !RD->getNumBases()) {
  2684. VTableName = ClassTypeInfo;
  2685. } else if (CanUseSingleInheritance(RD)) {
  2686. VTableName = SIClassTypeInfo;
  2687. } else {
  2688. VTableName = VMIClassTypeInfo;
  2689. }
  2690. break;
  2691. }
  2692. case Type::ObjCObject:
  2693. // Ignore protocol qualifiers.
  2694. Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
  2695. // Handle id and Class.
  2696. if (isa<BuiltinType>(Ty)) {
  2697. VTableName = ClassTypeInfo;
  2698. break;
  2699. }
  2700. assert(isa<ObjCInterfaceType>(Ty));
  2701. LLVM_FALLTHROUGH;
  2702. case Type::ObjCInterface:
  2703. if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
  2704. VTableName = SIClassTypeInfo;
  2705. } else {
  2706. VTableName = ClassTypeInfo;
  2707. }
  2708. break;
  2709. case Type::ObjCObjectPointer:
  2710. case Type::Pointer:
  2711. // abi::__pointer_type_info.
  2712. VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
  2713. break;
  2714. case Type::MemberPointer:
  2715. // abi::__pointer_to_member_type_info.
  2716. VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
  2717. break;
  2718. }
  2719. llvm::Constant *VTable =
  2720. CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
  2721. CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
  2722. llvm::Type *PtrDiffTy =
  2723. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  2724. // The vtable address point is 2.
  2725. llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
  2726. VTable =
  2727. llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable, Two);
  2728. VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
  2729. Fields.push_back(VTable);
  2730. }
  2731. /// Return the linkage that the type info and type info name constants
  2732. /// should have for the given type.
  2733. static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
  2734. QualType Ty) {
  2735. // Itanium C++ ABI 2.9.5p7:
  2736. // In addition, it and all of the intermediate abi::__pointer_type_info
  2737. // structs in the chain down to the abi::__class_type_info for the
  2738. // incomplete class type must be prevented from resolving to the
  2739. // corresponding type_info structs for the complete class type, possibly
  2740. // by making them local static objects. Finally, a dummy class RTTI is
  2741. // generated for the incomplete type that will not resolve to the final
  2742. // complete class RTTI (because the latter need not exist), possibly by
  2743. // making it a local static object.
  2744. if (ContainsIncompleteClassType(Ty))
  2745. return llvm::GlobalValue::InternalLinkage;
  2746. switch (Ty->getLinkage()) {
  2747. case NoLinkage:
  2748. case InternalLinkage:
  2749. case UniqueExternalLinkage:
  2750. return llvm::GlobalValue::InternalLinkage;
  2751. case VisibleNoLinkage:
  2752. case ModuleInternalLinkage:
  2753. case ModuleLinkage:
  2754. case ExternalLinkage:
  2755. // RTTI is not enabled, which means that this type info struct is going
  2756. // to be used for exception handling. Give it linkonce_odr linkage.
  2757. if (!CGM.getLangOpts().RTTI)
  2758. return llvm::GlobalValue::LinkOnceODRLinkage;
  2759. if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
  2760. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2761. if (RD->hasAttr<WeakAttr>())
  2762. return llvm::GlobalValue::WeakODRLinkage;
  2763. if (CGM.getTriple().isWindowsItaniumEnvironment())
  2764. if (RD->hasAttr<DLLImportAttr>() &&
  2765. ShouldUseExternalRTTIDescriptor(CGM, Ty))
  2766. return llvm::GlobalValue::ExternalLinkage;
  2767. // MinGW always uses LinkOnceODRLinkage for type info.
  2768. if (RD->isDynamicClass() &&
  2769. !CGM.getContext()
  2770. .getTargetInfo()
  2771. .getTriple()
  2772. .isWindowsGNUEnvironment())
  2773. return CGM.getVTableLinkage(RD);
  2774. }
  2775. return llvm::GlobalValue::LinkOnceODRLinkage;
  2776. }
  2777. llvm_unreachable("Invalid linkage!");
  2778. }
  2779. llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
  2780. // We want to operate on the canonical type.
  2781. Ty = Ty.getCanonicalType();
  2782. // Check if we've already emitted an RTTI descriptor for this type.
  2783. SmallString<256> Name;
  2784. llvm::raw_svector_ostream Out(Name);
  2785. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2786. llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
  2787. if (OldGV && !OldGV->isDeclaration()) {
  2788. assert(!OldGV->hasAvailableExternallyLinkage() &&
  2789. "available_externally typeinfos not yet implemented");
  2790. return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
  2791. }
  2792. // Check if there is already an external RTTI descriptor for this type.
  2793. if (IsStandardLibraryRTTIDescriptor(Ty) ||
  2794. ShouldUseExternalRTTIDescriptor(CGM, Ty))
  2795. return GetAddrOfExternalRTTIDescriptor(Ty);
  2796. // Emit the standard library with external linkage.
  2797. llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
  2798. // Give the type_info object and name the formal visibility of the
  2799. // type itself.
  2800. llvm::GlobalValue::VisibilityTypes llvmVisibility;
  2801. if (llvm::GlobalValue::isLocalLinkage(Linkage))
  2802. // If the linkage is local, only default visibility makes sense.
  2803. llvmVisibility = llvm::GlobalValue::DefaultVisibility;
  2804. else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
  2805. ItaniumCXXABI::RUK_NonUniqueHidden)
  2806. llvmVisibility = llvm::GlobalValue::HiddenVisibility;
  2807. else
  2808. llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
  2809. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
  2810. llvm::GlobalValue::DefaultStorageClass;
  2811. if (CGM.getTriple().isWindowsItaniumEnvironment()) {
  2812. auto RD = Ty->getAsCXXRecordDecl();
  2813. if (RD && RD->hasAttr<DLLExportAttr>())
  2814. DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
  2815. }
  2816. return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
  2817. }
  2818. llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
  2819. QualType Ty,
  2820. llvm::GlobalVariable::LinkageTypes Linkage,
  2821. llvm::GlobalValue::VisibilityTypes Visibility,
  2822. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
  2823. // Add the vtable pointer.
  2824. BuildVTablePointer(cast<Type>(Ty));
  2825. // And the name.
  2826. llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
  2827. llvm::Constant *TypeNameField;
  2828. // If we're supposed to demote the visibility, be sure to set a flag
  2829. // to use a string comparison for type_info comparisons.
  2830. ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
  2831. CXXABI.classifyRTTIUniqueness(Ty, Linkage);
  2832. if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
  2833. // The flag is the sign bit, which on ARM64 is defined to be clear
  2834. // for global pointers. This is very ARM64-specific.
  2835. TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
  2836. llvm::Constant *flag =
  2837. llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
  2838. TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
  2839. TypeNameField =
  2840. llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
  2841. } else {
  2842. TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
  2843. }
  2844. Fields.push_back(TypeNameField);
  2845. switch (Ty->getTypeClass()) {
  2846. #define TYPE(Class, Base)
  2847. #define ABSTRACT_TYPE(Class, Base)
  2848. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2849. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2850. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2851. #include "clang/AST/TypeNodes.inc"
  2852. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  2853. // GCC treats vector types as fundamental types.
  2854. case Type::Builtin:
  2855. case Type::Vector:
  2856. case Type::ExtVector:
  2857. case Type::Complex:
  2858. case Type::BlockPointer:
  2859. // Itanium C++ ABI 2.9.5p4:
  2860. // abi::__fundamental_type_info adds no data members to std::type_info.
  2861. break;
  2862. case Type::LValueReference:
  2863. case Type::RValueReference:
  2864. llvm_unreachable("References shouldn't get here");
  2865. case Type::Auto:
  2866. case Type::DeducedTemplateSpecialization:
  2867. llvm_unreachable("Undeduced type shouldn't get here");
  2868. case Type::Pipe:
  2869. llvm_unreachable("Pipe type shouldn't get here");
  2870. case Type::ConstantArray:
  2871. case Type::IncompleteArray:
  2872. case Type::VariableArray:
  2873. // Itanium C++ ABI 2.9.5p5:
  2874. // abi::__array_type_info adds no data members to std::type_info.
  2875. break;
  2876. case Type::FunctionNoProto:
  2877. case Type::FunctionProto:
  2878. // Itanium C++ ABI 2.9.5p5:
  2879. // abi::__function_type_info adds no data members to std::type_info.
  2880. break;
  2881. case Type::Enum:
  2882. // Itanium C++ ABI 2.9.5p5:
  2883. // abi::__enum_type_info adds no data members to std::type_info.
  2884. break;
  2885. case Type::Record: {
  2886. const CXXRecordDecl *RD =
  2887. cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
  2888. if (!RD->hasDefinition() || !RD->getNumBases()) {
  2889. // We don't need to emit any fields.
  2890. break;
  2891. }
  2892. if (CanUseSingleInheritance(RD))
  2893. BuildSIClassTypeInfo(RD);
  2894. else
  2895. BuildVMIClassTypeInfo(RD);
  2896. break;
  2897. }
  2898. case Type::ObjCObject:
  2899. case Type::ObjCInterface:
  2900. BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
  2901. break;
  2902. case Type::ObjCObjectPointer:
  2903. BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
  2904. break;
  2905. case Type::Pointer:
  2906. BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
  2907. break;
  2908. case Type::MemberPointer:
  2909. BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
  2910. break;
  2911. case Type::Atomic:
  2912. // No fields, at least for the moment.
  2913. break;
  2914. }
  2915. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
  2916. SmallString<256> Name;
  2917. llvm::raw_svector_ostream Out(Name);
  2918. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
  2919. llvm::Module &M = CGM.getModule();
  2920. llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
  2921. llvm::GlobalVariable *GV =
  2922. new llvm::GlobalVariable(M, Init->getType(),
  2923. /*isConstant=*/true, Linkage, Init, Name);
  2924. // If there's already an old global variable, replace it with the new one.
  2925. if (OldGV) {
  2926. GV->takeName(OldGV);
  2927. llvm::Constant *NewPtr =
  2928. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2929. OldGV->replaceAllUsesWith(NewPtr);
  2930. OldGV->eraseFromParent();
  2931. }
  2932. if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
  2933. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2934. CharUnits Align =
  2935. CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
  2936. GV->setAlignment(Align.getAsAlign());
  2937. // The Itanium ABI specifies that type_info objects must be globally
  2938. // unique, with one exception: if the type is an incomplete class
  2939. // type or a (possibly indirect) pointer to one. That exception
  2940. // affects the general case of comparing type_info objects produced
  2941. // by the typeid operator, which is why the comparison operators on
  2942. // std::type_info generally use the type_info name pointers instead
  2943. // of the object addresses. However, the language's built-in uses
  2944. // of RTTI generally require class types to be complete, even when
  2945. // manipulating pointers to those class types. This allows the
  2946. // implementation of dynamic_cast to rely on address equality tests,
  2947. // which is much faster.
  2948. // All of this is to say that it's important that both the type_info
  2949. // object and the type_info name be uniqued when weakly emitted.
  2950. TypeName->setVisibility(Visibility);
  2951. CGM.setDSOLocal(TypeName);
  2952. GV->setVisibility(Visibility);
  2953. CGM.setDSOLocal(GV);
  2954. TypeName->setDLLStorageClass(DLLStorageClass);
  2955. GV->setDLLStorageClass(DLLStorageClass);
  2956. TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
  2957. GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
  2958. return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
  2959. }
  2960. /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
  2961. /// for the given Objective-C object type.
  2962. void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
  2963. // Drop qualifiers.
  2964. const Type *T = OT->getBaseType().getTypePtr();
  2965. assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
  2966. // The builtin types are abi::__class_type_infos and don't require
  2967. // extra fields.
  2968. if (isa<BuiltinType>(T)) return;
  2969. ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
  2970. ObjCInterfaceDecl *Super = Class->getSuperClass();
  2971. // Root classes are also __class_type_info.
  2972. if (!Super) return;
  2973. QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
  2974. // Everything else is single inheritance.
  2975. llvm::Constant *BaseTypeInfo =
  2976. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
  2977. Fields.push_back(BaseTypeInfo);
  2978. }
  2979. /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
  2980. /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
  2981. void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
  2982. // Itanium C++ ABI 2.9.5p6b:
  2983. // It adds to abi::__class_type_info a single member pointing to the
  2984. // type_info structure for the base type,
  2985. llvm::Constant *BaseTypeInfo =
  2986. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
  2987. Fields.push_back(BaseTypeInfo);
  2988. }
  2989. namespace {
  2990. /// SeenBases - Contains virtual and non-virtual bases seen when traversing
  2991. /// a class hierarchy.
  2992. struct SeenBases {
  2993. llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
  2994. llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
  2995. };
  2996. }
  2997. /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
  2998. /// abi::__vmi_class_type_info.
  2999. ///
  3000. static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
  3001. SeenBases &Bases) {
  3002. unsigned Flags = 0;
  3003. auto *BaseDecl =
  3004. cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
  3005. if (Base->isVirtual()) {
  3006. // Mark the virtual base as seen.
  3007. if (!Bases.VirtualBases.insert(BaseDecl).second) {
  3008. // If this virtual base has been seen before, then the class is diamond
  3009. // shaped.
  3010. Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
  3011. } else {
  3012. if (Bases.NonVirtualBases.count(BaseDecl))
  3013. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  3014. }
  3015. } else {
  3016. // Mark the non-virtual base as seen.
  3017. if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
  3018. // If this non-virtual base has been seen before, then the class has non-
  3019. // diamond shaped repeated inheritance.
  3020. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  3021. } else {
  3022. if (Bases.VirtualBases.count(BaseDecl))
  3023. Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
  3024. }
  3025. }
  3026. // Walk all bases.
  3027. for (const auto &I : BaseDecl->bases())
  3028. Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
  3029. return Flags;
  3030. }
  3031. static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
  3032. unsigned Flags = 0;
  3033. SeenBases Bases;
  3034. // Walk all bases.
  3035. for (const auto &I : RD->bases())
  3036. Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
  3037. return Flags;
  3038. }
  3039. /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
  3040. /// classes with bases that do not satisfy the abi::__si_class_type_info
  3041. /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
  3042. void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
  3043. llvm::Type *UnsignedIntLTy =
  3044. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  3045. // Itanium C++ ABI 2.9.5p6c:
  3046. // __flags is a word with flags describing details about the class
  3047. // structure, which may be referenced by using the __flags_masks
  3048. // enumeration. These flags refer to both direct and indirect bases.
  3049. unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
  3050. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  3051. // Itanium C++ ABI 2.9.5p6c:
  3052. // __base_count is a word with the number of direct proper base class
  3053. // descriptions that follow.
  3054. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
  3055. if (!RD->getNumBases())
  3056. return;
  3057. // Now add the base class descriptions.
  3058. // Itanium C++ ABI 2.9.5p6c:
  3059. // __base_info[] is an array of base class descriptions -- one for every
  3060. // direct proper base. Each description is of the type:
  3061. //
  3062. // struct abi::__base_class_type_info {
  3063. // public:
  3064. // const __class_type_info *__base_type;
  3065. // long __offset_flags;
  3066. //
  3067. // enum __offset_flags_masks {
  3068. // __virtual_mask = 0x1,
  3069. // __public_mask = 0x2,
  3070. // __offset_shift = 8
  3071. // };
  3072. // };
  3073. // If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
  3074. // long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
  3075. // LLP64 platforms.
  3076. // FIXME: Consider updating libc++abi to match, and extend this logic to all
  3077. // LLP64 platforms.
  3078. QualType OffsetFlagsTy = CGM.getContext().LongTy;
  3079. const TargetInfo &TI = CGM.getContext().getTargetInfo();
  3080. if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
  3081. OffsetFlagsTy = CGM.getContext().LongLongTy;
  3082. llvm::Type *OffsetFlagsLTy =
  3083. CGM.getTypes().ConvertType(OffsetFlagsTy);
  3084. for (const auto &Base : RD->bases()) {
  3085. // The __base_type member points to the RTTI for the base type.
  3086. Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
  3087. auto *BaseDecl =
  3088. cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
  3089. int64_t OffsetFlags = 0;
  3090. // All but the lower 8 bits of __offset_flags are a signed offset.
  3091. // For a non-virtual base, this is the offset in the object of the base
  3092. // subobject. For a virtual base, this is the offset in the virtual table of
  3093. // the virtual base offset for the virtual base referenced (negative).
  3094. CharUnits Offset;
  3095. if (Base.isVirtual())
  3096. Offset =
  3097. CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
  3098. else {
  3099. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  3100. Offset = Layout.getBaseClassOffset(BaseDecl);
  3101. };
  3102. OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
  3103. // The low-order byte of __offset_flags contains flags, as given by the
  3104. // masks from the enumeration __offset_flags_masks.
  3105. if (Base.isVirtual())
  3106. OffsetFlags |= BCTI_Virtual;
  3107. if (Base.getAccessSpecifier() == AS_public)
  3108. OffsetFlags |= BCTI_Public;
  3109. Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
  3110. }
  3111. }
  3112. /// Compute the flags for a __pbase_type_info, and remove the corresponding
  3113. /// pieces from \p Type.
  3114. static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
  3115. unsigned Flags = 0;
  3116. if (Type.isConstQualified())
  3117. Flags |= ItaniumRTTIBuilder::PTI_Const;
  3118. if (Type.isVolatileQualified())
  3119. Flags |= ItaniumRTTIBuilder::PTI_Volatile;
  3120. if (Type.isRestrictQualified())
  3121. Flags |= ItaniumRTTIBuilder::PTI_Restrict;
  3122. Type = Type.getUnqualifiedType();
  3123. // Itanium C++ ABI 2.9.5p7:
  3124. // When the abi::__pbase_type_info is for a direct or indirect pointer to an
  3125. // incomplete class type, the incomplete target type flag is set.
  3126. if (ContainsIncompleteClassType(Type))
  3127. Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
  3128. if (auto *Proto = Type->getAs<FunctionProtoType>()) {
  3129. if (Proto->isNothrow()) {
  3130. Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
  3131. Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
  3132. }
  3133. }
  3134. return Flags;
  3135. }
  3136. /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
  3137. /// used for pointer types.
  3138. void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
  3139. // Itanium C++ ABI 2.9.5p7:
  3140. // __flags is a flag word describing the cv-qualification and other
  3141. // attributes of the type pointed to
  3142. unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
  3143. llvm::Type *UnsignedIntLTy =
  3144. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  3145. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  3146. // Itanium C++ ABI 2.9.5p7:
  3147. // __pointee is a pointer to the std::type_info derivation for the
  3148. // unqualified type being pointed to.
  3149. llvm::Constant *PointeeTypeInfo =
  3150. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
  3151. Fields.push_back(PointeeTypeInfo);
  3152. }
  3153. /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
  3154. /// struct, used for member pointer types.
  3155. void
  3156. ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
  3157. QualType PointeeTy = Ty->getPointeeType();
  3158. // Itanium C++ ABI 2.9.5p7:
  3159. // __flags is a flag word describing the cv-qualification and other
  3160. // attributes of the type pointed to.
  3161. unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
  3162. const RecordType *ClassType = cast<RecordType>(Ty->getClass());
  3163. if (IsIncompleteClassType(ClassType))
  3164. Flags |= PTI_ContainingClassIncomplete;
  3165. llvm::Type *UnsignedIntLTy =
  3166. CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
  3167. Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
  3168. // Itanium C++ ABI 2.9.5p7:
  3169. // __pointee is a pointer to the std::type_info derivation for the
  3170. // unqualified type being pointed to.
  3171. llvm::Constant *PointeeTypeInfo =
  3172. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
  3173. Fields.push_back(PointeeTypeInfo);
  3174. // Itanium C++ ABI 2.9.5p9:
  3175. // __context is a pointer to an abi::__class_type_info corresponding to the
  3176. // class type containing the member pointed to
  3177. // (e.g., the "A" in "int A::*").
  3178. Fields.push_back(
  3179. ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
  3180. }
  3181. llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
  3182. return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
  3183. }
  3184. void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
  3185. // Types added here must also be added to TypeInfoIsInStandardLibrary.
  3186. QualType FundamentalTypes[] = {
  3187. getContext().VoidTy, getContext().NullPtrTy,
  3188. getContext().BoolTy, getContext().WCharTy,
  3189. getContext().CharTy, getContext().UnsignedCharTy,
  3190. getContext().SignedCharTy, getContext().ShortTy,
  3191. getContext().UnsignedShortTy, getContext().IntTy,
  3192. getContext().UnsignedIntTy, getContext().LongTy,
  3193. getContext().UnsignedLongTy, getContext().LongLongTy,
  3194. getContext().UnsignedLongLongTy, getContext().Int128Ty,
  3195. getContext().UnsignedInt128Ty, getContext().HalfTy,
  3196. getContext().FloatTy, getContext().DoubleTy,
  3197. getContext().LongDoubleTy, getContext().Float128Ty,
  3198. getContext().Char8Ty, getContext().Char16Ty,
  3199. getContext().Char32Ty
  3200. };
  3201. llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
  3202. RD->hasAttr<DLLExportAttr>()
  3203. ? llvm::GlobalValue::DLLExportStorageClass
  3204. : llvm::GlobalValue::DefaultStorageClass;
  3205. llvm::GlobalValue::VisibilityTypes Visibility =
  3206. CodeGenModule::GetLLVMVisibility(RD->getVisibility());
  3207. for (const QualType &FundamentalType : FundamentalTypes) {
  3208. QualType PointerType = getContext().getPointerType(FundamentalType);
  3209. QualType PointerTypeConst = getContext().getPointerType(
  3210. FundamentalType.withConst());
  3211. for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
  3212. ItaniumRTTIBuilder(*this).BuildTypeInfo(
  3213. Type, llvm::GlobalValue::ExternalLinkage,
  3214. Visibility, DLLStorageClass);
  3215. }
  3216. }
  3217. /// What sort of uniqueness rules should we use for the RTTI for the
  3218. /// given type?
  3219. ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
  3220. QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
  3221. if (shouldRTTIBeUnique())
  3222. return RUK_Unique;
  3223. // It's only necessary for linkonce_odr or weak_odr linkage.
  3224. if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
  3225. Linkage != llvm::GlobalValue::WeakODRLinkage)
  3226. return RUK_Unique;
  3227. // It's only necessary with default visibility.
  3228. if (CanTy->getVisibility() != DefaultVisibility)
  3229. return RUK_Unique;
  3230. // If we're not required to publish this symbol, hide it.
  3231. if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
  3232. return RUK_NonUniqueHidden;
  3233. // If we're required to publish this symbol, as we might be under an
  3234. // explicit instantiation, leave it with default visibility but
  3235. // enable string-comparisons.
  3236. assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
  3237. return RUK_NonUniqueVisible;
  3238. }
  3239. // Find out how to codegen the complete destructor and constructor
  3240. namespace {
  3241. enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
  3242. }
  3243. static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
  3244. const CXXMethodDecl *MD) {
  3245. if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
  3246. return StructorCodegen::Emit;
  3247. // The complete and base structors are not equivalent if there are any virtual
  3248. // bases, so emit separate functions.
  3249. if (MD->getParent()->getNumVBases())
  3250. return StructorCodegen::Emit;
  3251. GlobalDecl AliasDecl;
  3252. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  3253. AliasDecl = GlobalDecl(DD, Dtor_Complete);
  3254. } else {
  3255. const auto *CD = cast<CXXConstructorDecl>(MD);
  3256. AliasDecl = GlobalDecl(CD, Ctor_Complete);
  3257. }
  3258. llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
  3259. if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
  3260. return StructorCodegen::RAUW;
  3261. // FIXME: Should we allow available_externally aliases?
  3262. if (!llvm::GlobalAlias::isValidLinkage(Linkage))
  3263. return StructorCodegen::RAUW;
  3264. if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
  3265. // Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
  3266. if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
  3267. CGM.getTarget().getTriple().isOSBinFormatWasm())
  3268. return StructorCodegen::COMDAT;
  3269. return StructorCodegen::Emit;
  3270. }
  3271. return StructorCodegen::Alias;
  3272. }
  3273. static void emitConstructorDestructorAlias(CodeGenModule &CGM,
  3274. GlobalDecl AliasDecl,
  3275. GlobalDecl TargetDecl) {
  3276. llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
  3277. StringRef MangledName = CGM.getMangledName(AliasDecl);
  3278. llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
  3279. if (Entry && !Entry->isDeclaration())
  3280. return;
  3281. auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
  3282. // Create the alias with no name.
  3283. auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
  3284. // Constructors and destructors are always unnamed_addr.
  3285. Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3286. // Switch any previous uses to the alias.
  3287. if (Entry) {
  3288. assert(Entry->getType() == Aliasee->getType() &&
  3289. "declaration exists with different type");
  3290. Alias->takeName(Entry);
  3291. Entry->replaceAllUsesWith(Alias);
  3292. Entry->eraseFromParent();
  3293. } else {
  3294. Alias->setName(MangledName);
  3295. }
  3296. // Finally, set up the alias with its proper name and attributes.
  3297. CGM.SetCommonAttributes(AliasDecl, Alias);
  3298. }
  3299. void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
  3300. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  3301. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  3302. const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
  3303. StructorCodegen CGType = getCodegenToUse(CGM, MD);
  3304. if (CD ? GD.getCtorType() == Ctor_Complete
  3305. : GD.getDtorType() == Dtor_Complete) {
  3306. GlobalDecl BaseDecl;
  3307. if (CD)
  3308. BaseDecl = GD.getWithCtorType(Ctor_Base);
  3309. else
  3310. BaseDecl = GD.getWithDtorType(Dtor_Base);
  3311. if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
  3312. emitConstructorDestructorAlias(CGM, GD, BaseDecl);
  3313. return;
  3314. }
  3315. if (CGType == StructorCodegen::RAUW) {
  3316. StringRef MangledName = CGM.getMangledName(GD);
  3317. auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
  3318. CGM.addReplacement(MangledName, Aliasee);
  3319. return;
  3320. }
  3321. }
  3322. // The base destructor is equivalent to the base destructor of its
  3323. // base class if there is exactly one non-virtual base class with a
  3324. // non-trivial destructor, there are no fields with a non-trivial
  3325. // destructor, and the body of the destructor is trivial.
  3326. if (DD && GD.getDtorType() == Dtor_Base &&
  3327. CGType != StructorCodegen::COMDAT &&
  3328. !CGM.TryEmitBaseDestructorAsAlias(DD))
  3329. return;
  3330. // FIXME: The deleting destructor is equivalent to the selected operator
  3331. // delete if:
  3332. // * either the delete is a destroying operator delete or the destructor
  3333. // would be trivial if it weren't virtual,
  3334. // * the conversion from the 'this' parameter to the first parameter of the
  3335. // destructor is equivalent to a bitcast,
  3336. // * the destructor does not have an implicit "this" return, and
  3337. // * the operator delete has the same calling convention and IR function type
  3338. // as the destructor.
  3339. // In such cases we should try to emit the deleting dtor as an alias to the
  3340. // selected 'operator delete'.
  3341. llvm::Function *Fn = CGM.codegenCXXStructor(GD);
  3342. if (CGType == StructorCodegen::COMDAT) {
  3343. SmallString<256> Buffer;
  3344. llvm::raw_svector_ostream Out(Buffer);
  3345. if (DD)
  3346. getMangleContext().mangleCXXDtorComdat(DD, Out);
  3347. else
  3348. getMangleContext().mangleCXXCtorComdat(CD, Out);
  3349. llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
  3350. Fn->setComdat(C);
  3351. } else {
  3352. CGM.maybeSetTrivialComdat(*MD, *Fn);
  3353. }
  3354. }
  3355. static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
  3356. // void *__cxa_begin_catch(void*);
  3357. llvm::FunctionType *FTy = llvm::FunctionType::get(
  3358. CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  3359. return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
  3360. }
  3361. static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
  3362. // void __cxa_end_catch();
  3363. llvm::FunctionType *FTy =
  3364. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  3365. return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
  3366. }
  3367. static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
  3368. // void *__cxa_get_exception_ptr(void*);
  3369. llvm::FunctionType *FTy = llvm::FunctionType::get(
  3370. CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  3371. return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
  3372. }
  3373. namespace {
  3374. /// A cleanup to call __cxa_end_catch. In many cases, the caught
  3375. /// exception type lets us state definitively that the thrown exception
  3376. /// type does not have a destructor. In particular:
  3377. /// - Catch-alls tell us nothing, so we have to conservatively
  3378. /// assume that the thrown exception might have a destructor.
  3379. /// - Catches by reference behave according to their base types.
  3380. /// - Catches of non-record types will only trigger for exceptions
  3381. /// of non-record types, which never have destructors.
  3382. /// - Catches of record types can trigger for arbitrary subclasses
  3383. /// of the caught type, so we have to assume the actual thrown
  3384. /// exception type might have a throwing destructor, even if the
  3385. /// caught type's destructor is trivial or nothrow.
  3386. struct CallEndCatch final : EHScopeStack::Cleanup {
  3387. CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
  3388. bool MightThrow;
  3389. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3390. if (!MightThrow) {
  3391. CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
  3392. return;
  3393. }
  3394. CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
  3395. }
  3396. };
  3397. }
  3398. /// Emits a call to __cxa_begin_catch and enters a cleanup to call
  3399. /// __cxa_end_catch.
  3400. ///
  3401. /// \param EndMightThrow - true if __cxa_end_catch might throw
  3402. static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
  3403. llvm::Value *Exn,
  3404. bool EndMightThrow) {
  3405. llvm::CallInst *call =
  3406. CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
  3407. CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
  3408. return call;
  3409. }
  3410. /// A "special initializer" callback for initializing a catch
  3411. /// parameter during catch initialization.
  3412. static void InitCatchParam(CodeGenFunction &CGF,
  3413. const VarDecl &CatchParam,
  3414. Address ParamAddr,
  3415. SourceLocation Loc) {
  3416. // Load the exception from where the landing pad saved it.
  3417. llvm::Value *Exn = CGF.getExceptionFromSlot();
  3418. CanQualType CatchType =
  3419. CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
  3420. llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
  3421. // If we're catching by reference, we can just cast the object
  3422. // pointer to the appropriate pointer.
  3423. if (isa<ReferenceType>(CatchType)) {
  3424. QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
  3425. bool EndCatchMightThrow = CaughtType->isRecordType();
  3426. // __cxa_begin_catch returns the adjusted object pointer.
  3427. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
  3428. // We have no way to tell the personality function that we're
  3429. // catching by reference, so if we're catching a pointer,
  3430. // __cxa_begin_catch will actually return that pointer by value.
  3431. if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
  3432. QualType PointeeType = PT->getPointeeType();
  3433. // When catching by reference, generally we should just ignore
  3434. // this by-value pointer and use the exception object instead.
  3435. if (!PointeeType->isRecordType()) {
  3436. // Exn points to the struct _Unwind_Exception header, which
  3437. // we have to skip past in order to reach the exception data.
  3438. unsigned HeaderSize =
  3439. CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
  3440. AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
  3441. // However, if we're catching a pointer-to-record type that won't
  3442. // work, because the personality function might have adjusted
  3443. // the pointer. There's actually no way for us to fully satisfy
  3444. // the language/ABI contract here: we can't use Exn because it
  3445. // might have the wrong adjustment, but we can't use the by-value
  3446. // pointer because it's off by a level of abstraction.
  3447. //
  3448. // The current solution is to dump the adjusted pointer into an
  3449. // alloca, which breaks language semantics (because changing the
  3450. // pointer doesn't change the exception) but at least works.
  3451. // The better solution would be to filter out non-exact matches
  3452. // and rethrow them, but this is tricky because the rethrow
  3453. // really needs to be catchable by other sites at this landing
  3454. // pad. The best solution is to fix the personality function.
  3455. } else {
  3456. // Pull the pointer for the reference type off.
  3457. llvm::Type *PtrTy =
  3458. cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
  3459. // Create the temporary and write the adjusted pointer into it.
  3460. Address ExnPtrTmp =
  3461. CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
  3462. llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  3463. CGF.Builder.CreateStore(Casted, ExnPtrTmp);
  3464. // Bind the reference to the temporary.
  3465. AdjustedExn = ExnPtrTmp.getPointer();
  3466. }
  3467. }
  3468. llvm::Value *ExnCast =
  3469. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
  3470. CGF.Builder.CreateStore(ExnCast, ParamAddr);
  3471. return;
  3472. }
  3473. // Scalars and complexes.
  3474. TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
  3475. if (TEK != TEK_Aggregate) {
  3476. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
  3477. // If the catch type is a pointer type, __cxa_begin_catch returns
  3478. // the pointer by value.
  3479. if (CatchType->hasPointerRepresentation()) {
  3480. llvm::Value *CastExn =
  3481. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
  3482. switch (CatchType.getQualifiers().getObjCLifetime()) {
  3483. case Qualifiers::OCL_Strong:
  3484. CastExn = CGF.EmitARCRetainNonBlock(CastExn);
  3485. LLVM_FALLTHROUGH;
  3486. case Qualifiers::OCL_None:
  3487. case Qualifiers::OCL_ExplicitNone:
  3488. case Qualifiers::OCL_Autoreleasing:
  3489. CGF.Builder.CreateStore(CastExn, ParamAddr);
  3490. return;
  3491. case Qualifiers::OCL_Weak:
  3492. CGF.EmitARCInitWeak(ParamAddr, CastExn);
  3493. return;
  3494. }
  3495. llvm_unreachable("bad ownership qualifier!");
  3496. }
  3497. // Otherwise, it returns a pointer into the exception object.
  3498. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  3499. llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  3500. LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
  3501. LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
  3502. switch (TEK) {
  3503. case TEK_Complex:
  3504. CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
  3505. /*init*/ true);
  3506. return;
  3507. case TEK_Scalar: {
  3508. llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
  3509. CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
  3510. return;
  3511. }
  3512. case TEK_Aggregate:
  3513. llvm_unreachable("evaluation kind filtered out!");
  3514. }
  3515. llvm_unreachable("bad evaluation kind");
  3516. }
  3517. assert(isa<RecordType>(CatchType) && "unexpected catch type!");
  3518. auto catchRD = CatchType->getAsCXXRecordDecl();
  3519. CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
  3520. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  3521. // Check for a copy expression. If we don't have a copy expression,
  3522. // that means a trivial copy is okay.
  3523. const Expr *copyExpr = CatchParam.getInit();
  3524. if (!copyExpr) {
  3525. llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
  3526. Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
  3527. caughtExnAlignment);
  3528. LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
  3529. LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
  3530. CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
  3531. return;
  3532. }
  3533. // We have to call __cxa_get_exception_ptr to get the adjusted
  3534. // pointer before copying.
  3535. llvm::CallInst *rawAdjustedExn =
  3536. CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
  3537. // Cast that to the appropriate type.
  3538. Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
  3539. caughtExnAlignment);
  3540. // The copy expression is defined in terms of an OpaqueValueExpr.
  3541. // Find it and map it to the adjusted expression.
  3542. CodeGenFunction::OpaqueValueMapping
  3543. opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
  3544. CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
  3545. // Call the copy ctor in a terminate scope.
  3546. CGF.EHStack.pushTerminate();
  3547. // Perform the copy construction.
  3548. CGF.EmitAggExpr(copyExpr,
  3549. AggValueSlot::forAddr(ParamAddr, Qualifiers(),
  3550. AggValueSlot::IsNotDestructed,
  3551. AggValueSlot::DoesNotNeedGCBarriers,
  3552. AggValueSlot::IsNotAliased,
  3553. AggValueSlot::DoesNotOverlap));
  3554. // Leave the terminate scope.
  3555. CGF.EHStack.popTerminate();
  3556. // Undo the opaque value mapping.
  3557. opaque.pop();
  3558. // Finally we can call __cxa_begin_catch.
  3559. CallBeginCatch(CGF, Exn, true);
  3560. }
  3561. /// Begins a catch statement by initializing the catch variable and
  3562. /// calling __cxa_begin_catch.
  3563. void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  3564. const CXXCatchStmt *S) {
  3565. // We have to be very careful with the ordering of cleanups here:
  3566. // C++ [except.throw]p4:
  3567. // The destruction [of the exception temporary] occurs
  3568. // immediately after the destruction of the object declared in
  3569. // the exception-declaration in the handler.
  3570. //
  3571. // So the precise ordering is:
  3572. // 1. Construct catch variable.
  3573. // 2. __cxa_begin_catch
  3574. // 3. Enter __cxa_end_catch cleanup
  3575. // 4. Enter dtor cleanup
  3576. //
  3577. // We do this by using a slightly abnormal initialization process.
  3578. // Delegation sequence:
  3579. // - ExitCXXTryStmt opens a RunCleanupsScope
  3580. // - EmitAutoVarAlloca creates the variable and debug info
  3581. // - InitCatchParam initializes the variable from the exception
  3582. // - CallBeginCatch calls __cxa_begin_catch
  3583. // - CallBeginCatch enters the __cxa_end_catch cleanup
  3584. // - EmitAutoVarCleanups enters the variable destructor cleanup
  3585. // - EmitCXXTryStmt emits the code for the catch body
  3586. // - EmitCXXTryStmt close the RunCleanupsScope
  3587. VarDecl *CatchParam = S->getExceptionDecl();
  3588. if (!CatchParam) {
  3589. llvm::Value *Exn = CGF.getExceptionFromSlot();
  3590. CallBeginCatch(CGF, Exn, true);
  3591. return;
  3592. }
  3593. // Emit the local.
  3594. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  3595. InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
  3596. CGF.EmitAutoVarCleanups(var);
  3597. }
  3598. /// Get or define the following function:
  3599. /// void @__clang_call_terminate(i8* %exn) nounwind noreturn
  3600. /// This code is used only in C++.
  3601. static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
  3602. llvm::FunctionType *fnTy =
  3603. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  3604. llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
  3605. fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
  3606. llvm::Function *fn =
  3607. cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
  3608. if (fn->empty()) {
  3609. fn->setDoesNotThrow();
  3610. fn->setDoesNotReturn();
  3611. // What we really want is to massively penalize inlining without
  3612. // forbidding it completely. The difference between that and
  3613. // 'noinline' is negligible.
  3614. fn->addFnAttr(llvm::Attribute::NoInline);
  3615. // Allow this function to be shared across translation units, but
  3616. // we don't want it to turn into an exported symbol.
  3617. fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
  3618. fn->setVisibility(llvm::Function::HiddenVisibility);
  3619. if (CGM.supportsCOMDAT())
  3620. fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
  3621. // Set up the function.
  3622. llvm::BasicBlock *entry =
  3623. llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
  3624. CGBuilderTy builder(CGM, entry);
  3625. // Pull the exception pointer out of the parameter list.
  3626. llvm::Value *exn = &*fn->arg_begin();
  3627. // Call __cxa_begin_catch(exn).
  3628. llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
  3629. catchCall->setDoesNotThrow();
  3630. catchCall->setCallingConv(CGM.getRuntimeCC());
  3631. // Call std::terminate().
  3632. llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
  3633. termCall->setDoesNotThrow();
  3634. termCall->setDoesNotReturn();
  3635. termCall->setCallingConv(CGM.getRuntimeCC());
  3636. // std::terminate cannot return.
  3637. builder.CreateUnreachable();
  3638. }
  3639. return fnRef;
  3640. }
  3641. llvm::CallInst *
  3642. ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
  3643. llvm::Value *Exn) {
  3644. // In C++, we want to call __cxa_begin_catch() before terminating.
  3645. if (Exn) {
  3646. assert(CGF.CGM.getLangOpts().CPlusPlus);
  3647. return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
  3648. }
  3649. return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
  3650. }
  3651. std::pair<llvm::Value *, const CXXRecordDecl *>
  3652. ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
  3653. const CXXRecordDecl *RD) {
  3654. return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
  3655. }
  3656. void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
  3657. const CXXCatchStmt *C) {
  3658. if (CGF.getTarget().hasFeature("exception-handling"))
  3659. CGF.EHStack.pushCleanup<CatchRetScope>(
  3660. NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
  3661. ItaniumCXXABI::emitBeginCatch(CGF, C);
  3662. }