ItaniumCXXABI.cpp 140 KB

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