CodeGenModule.cpp 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407
  1. //===--- CodeGenModule.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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "CodeGenTBAA.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/CodeGen/ConstantInitBuilder.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/IR/CallSite.h"
  48. #include "llvm/IR/CallingConv.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/Intrinsics.h"
  51. #include "llvm/IR/LLVMContext.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/ProfileData/InstrProfReader.h"
  54. #include "llvm/Support/ConvertUTF.h"
  55. #include "llvm/Support/ErrorHandling.h"
  56. #include "llvm/Support/MD5.h"
  57. using namespace clang;
  58. using namespace CodeGen;
  59. static const char AnnotationSection[] = "llvm.metadata";
  60. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  61. switch (CGM.getTarget().getCXXABI().getKind()) {
  62. case TargetCXXABI::GenericAArch64:
  63. case TargetCXXABI::GenericARM:
  64. case TargetCXXABI::iOS:
  65. case TargetCXXABI::iOS64:
  66. case TargetCXXABI::WatchOS:
  67. case TargetCXXABI::GenericMIPS:
  68. case TargetCXXABI::GenericItanium:
  69. case TargetCXXABI::WebAssembly:
  70. return CreateItaniumCXXABI(CGM);
  71. case TargetCXXABI::Microsoft:
  72. return CreateMicrosoftCXXABI(CGM);
  73. }
  74. llvm_unreachable("invalid C++ ABI kind");
  75. }
  76. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  77. const PreprocessorOptions &PPO,
  78. const CodeGenOptions &CGO, llvm::Module &M,
  79. DiagnosticsEngine &diags,
  80. CoverageSourceInfo *CoverageInfo)
  81. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  82. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  83. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  84. VMContext(M.getContext()), Types(*this), VTables(*this),
  85. SanitizerMD(new SanitizerMetadata(*this)) {
  86. // Initialize the type cache.
  87. llvm::LLVMContext &LLVMContext = M.getContext();
  88. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  89. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  90. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  91. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  92. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  93. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  94. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  95. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  96. PointerAlignInBytes =
  97. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  98. SizeSizeInBytes =
  99. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  100. IntAlignInBytes =
  101. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  102. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  103. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  104. C.getTargetInfo().getMaxPointerWidth());
  105. Int8PtrTy = Int8Ty->getPointerTo(0);
  106. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  107. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  108. M.getDataLayout().getAllocaAddrSpace());
  109. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  110. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  111. if (LangOpts.ObjC1)
  112. createObjCRuntime();
  113. if (LangOpts.OpenCL)
  114. createOpenCLRuntime();
  115. if (LangOpts.OpenMP)
  116. createOpenMPRuntime();
  117. if (LangOpts.CUDA)
  118. createCUDARuntime();
  119. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  120. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  121. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  122. TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  123. getCXXABI().getMangleContext()));
  124. // If debug info or coverage generation is enabled, create the CGDebugInfo
  125. // object.
  126. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  127. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  128. DebugInfo.reset(new CGDebugInfo(*this));
  129. Block.GlobalUniqueCount = 0;
  130. if (C.getLangOpts().ObjC1)
  131. ObjCData.reset(new ObjCEntrypoints());
  132. if (CodeGenOpts.hasProfileClangUse()) {
  133. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  134. CodeGenOpts.ProfileInstrumentUsePath);
  135. if (auto E = ReaderOrErr.takeError()) {
  136. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  137. "Could not read profile %0: %1");
  138. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  139. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  140. << EI.message();
  141. });
  142. } else
  143. PGOReader = std::move(ReaderOrErr.get());
  144. }
  145. // If coverage mapping generation is enabled, create the
  146. // CoverageMappingModuleGen object.
  147. if (CodeGenOpts.CoverageMapping)
  148. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  149. }
  150. CodeGenModule::~CodeGenModule() {}
  151. void CodeGenModule::createObjCRuntime() {
  152. // This is just isGNUFamily(), but we want to force implementors of
  153. // new ABIs to decide how best to do this.
  154. switch (LangOpts.ObjCRuntime.getKind()) {
  155. case ObjCRuntime::GNUstep:
  156. case ObjCRuntime::GCC:
  157. case ObjCRuntime::ObjFW:
  158. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  159. return;
  160. case ObjCRuntime::FragileMacOSX:
  161. case ObjCRuntime::MacOSX:
  162. case ObjCRuntime::iOS:
  163. case ObjCRuntime::WatchOS:
  164. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  165. return;
  166. }
  167. llvm_unreachable("bad runtime kind");
  168. }
  169. void CodeGenModule::createOpenCLRuntime() {
  170. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  171. }
  172. void CodeGenModule::createOpenMPRuntime() {
  173. // Select a specialized code generation class based on the target, if any.
  174. // If it does not exist use the default implementation.
  175. switch (getTriple().getArch()) {
  176. case llvm::Triple::nvptx:
  177. case llvm::Triple::nvptx64:
  178. assert(getLangOpts().OpenMPIsDevice &&
  179. "OpenMP NVPTX is only prepared to deal with device code.");
  180. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  181. break;
  182. default:
  183. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  184. break;
  185. }
  186. }
  187. void CodeGenModule::createCUDARuntime() {
  188. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  189. }
  190. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  191. Replacements[Name] = C;
  192. }
  193. void CodeGenModule::applyReplacements() {
  194. for (auto &I : Replacements) {
  195. StringRef MangledName = I.first();
  196. llvm::Constant *Replacement = I.second;
  197. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  198. if (!Entry)
  199. continue;
  200. auto *OldF = cast<llvm::Function>(Entry);
  201. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  202. if (!NewF) {
  203. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  204. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  205. } else {
  206. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  207. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  208. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  209. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  210. }
  211. }
  212. // Replace old with new, but keep the old order.
  213. OldF->replaceAllUsesWith(Replacement);
  214. if (NewF) {
  215. NewF->removeFromParent();
  216. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  217. NewF);
  218. }
  219. OldF->eraseFromParent();
  220. }
  221. }
  222. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  223. GlobalValReplacements.push_back(std::make_pair(GV, C));
  224. }
  225. void CodeGenModule::applyGlobalValReplacements() {
  226. for (auto &I : GlobalValReplacements) {
  227. llvm::GlobalValue *GV = I.first;
  228. llvm::Constant *C = I.second;
  229. GV->replaceAllUsesWith(C);
  230. GV->eraseFromParent();
  231. }
  232. }
  233. // This is only used in aliases that we created and we know they have a
  234. // linear structure.
  235. static const llvm::GlobalObject *getAliasedGlobal(
  236. const llvm::GlobalIndirectSymbol &GIS) {
  237. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  238. const llvm::Constant *C = &GIS;
  239. for (;;) {
  240. C = C->stripPointerCasts();
  241. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  242. return GO;
  243. // stripPointerCasts will not walk over weak aliases.
  244. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  245. if (!GIS2)
  246. return nullptr;
  247. if (!Visited.insert(GIS2).second)
  248. return nullptr;
  249. C = GIS2->getIndirectSymbol();
  250. }
  251. }
  252. void CodeGenModule::checkAliases() {
  253. // Check if the constructed aliases are well formed. It is really unfortunate
  254. // that we have to do this in CodeGen, but we only construct mangled names
  255. // and aliases during codegen.
  256. bool Error = false;
  257. DiagnosticsEngine &Diags = getDiags();
  258. for (const GlobalDecl &GD : Aliases) {
  259. const auto *D = cast<ValueDecl>(GD.getDecl());
  260. SourceLocation Location;
  261. bool IsIFunc = D->hasAttr<IFuncAttr>();
  262. if (const Attr *A = D->getDefiningAttr())
  263. Location = A->getLocation();
  264. else
  265. llvm_unreachable("Not an alias or ifunc?");
  266. StringRef MangledName = getMangledName(GD);
  267. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  268. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  269. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  270. if (!GV) {
  271. Error = true;
  272. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  273. } else if (GV->isDeclaration()) {
  274. Error = true;
  275. Diags.Report(Location, diag::err_alias_to_undefined)
  276. << IsIFunc << IsIFunc;
  277. } else if (IsIFunc) {
  278. // Check resolver function type.
  279. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  280. GV->getType()->getPointerElementType());
  281. assert(FTy);
  282. if (!FTy->getReturnType()->isPointerTy())
  283. Diags.Report(Location, diag::err_ifunc_resolver_return);
  284. if (FTy->getNumParams())
  285. Diags.Report(Location, diag::err_ifunc_resolver_params);
  286. }
  287. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  288. llvm::GlobalValue *AliaseeGV;
  289. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  290. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  291. else
  292. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  293. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  294. StringRef AliasSection = SA->getName();
  295. if (AliasSection != AliaseeGV->getSection())
  296. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  297. << AliasSection << IsIFunc << IsIFunc;
  298. }
  299. // We have to handle alias to weak aliases in here. LLVM itself disallows
  300. // this since the object semantics would not match the IL one. For
  301. // compatibility with gcc we implement it by just pointing the alias
  302. // to its aliasee's aliasee. We also warn, since the user is probably
  303. // expecting the link to be weak.
  304. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  305. if (GA->isInterposable()) {
  306. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  307. << GV->getName() << GA->getName() << IsIFunc;
  308. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  309. GA->getIndirectSymbol(), Alias->getType());
  310. Alias->setIndirectSymbol(Aliasee);
  311. }
  312. }
  313. }
  314. if (!Error)
  315. return;
  316. for (const GlobalDecl &GD : Aliases) {
  317. StringRef MangledName = getMangledName(GD);
  318. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  319. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  320. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  321. Alias->eraseFromParent();
  322. }
  323. }
  324. void CodeGenModule::clear() {
  325. DeferredDeclsToEmit.clear();
  326. if (OpenMPRuntime)
  327. OpenMPRuntime->clear();
  328. }
  329. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  330. StringRef MainFile) {
  331. if (!hasDiagnostics())
  332. return;
  333. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  334. if (MainFile.empty())
  335. MainFile = "<stdin>";
  336. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  337. } else
  338. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  339. << Mismatched;
  340. }
  341. void CodeGenModule::Release() {
  342. EmitDeferred();
  343. applyGlobalValReplacements();
  344. applyReplacements();
  345. checkAliases();
  346. EmitCXXGlobalInitFunc();
  347. EmitCXXGlobalDtorFunc();
  348. EmitCXXThreadLocalInitFunc();
  349. if (ObjCRuntime)
  350. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  351. AddGlobalCtor(ObjCInitFunction);
  352. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  353. CUDARuntime) {
  354. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  355. AddGlobalCtor(CudaCtorFunction);
  356. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  357. AddGlobalDtor(CudaDtorFunction);
  358. }
  359. if (OpenMPRuntime)
  360. if (llvm::Function *OpenMPRegistrationFunction =
  361. OpenMPRuntime->emitRegistrationFunction())
  362. AddGlobalCtor(OpenMPRegistrationFunction, 0);
  363. if (PGOReader) {
  364. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  365. if (PGOStats.hasDiagnostics())
  366. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  367. }
  368. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  369. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  370. EmitGlobalAnnotations();
  371. EmitStaticExternCAliases();
  372. EmitDeferredUnusedCoverageMappings();
  373. if (CoverageMapping)
  374. CoverageMapping->emit();
  375. if (CodeGenOpts.SanitizeCfiCrossDso) {
  376. CodeGenFunction(*this).EmitCfiCheckFail();
  377. CodeGenFunction(*this).EmitCfiCheckStub();
  378. }
  379. emitAtAvailableLinkGuard();
  380. emitLLVMUsed();
  381. if (SanStats)
  382. SanStats->finish();
  383. if (CodeGenOpts.Autolink &&
  384. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  385. EmitModuleLinkOptions();
  386. }
  387. // Record mregparm value now so it is visible through rest of codegen.
  388. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  389. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  390. CodeGenOpts.NumRegisterParameters);
  391. if (CodeGenOpts.DwarfVersion) {
  392. // We actually want the latest version when there are conflicts.
  393. // We can change from Warning to Latest if such mode is supported.
  394. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  395. CodeGenOpts.DwarfVersion);
  396. }
  397. if (CodeGenOpts.EmitCodeView) {
  398. // Indicate that we want CodeView in the metadata.
  399. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  400. }
  401. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  402. // We don't support LTO with 2 with different StrictVTablePointers
  403. // FIXME: we could support it by stripping all the information introduced
  404. // by StrictVTablePointers.
  405. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  406. llvm::Metadata *Ops[2] = {
  407. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  408. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  409. llvm::Type::getInt32Ty(VMContext), 1))};
  410. getModule().addModuleFlag(llvm::Module::Require,
  411. "StrictVTablePointersRequirement",
  412. llvm::MDNode::get(VMContext, Ops));
  413. }
  414. if (DebugInfo)
  415. // We support a single version in the linked module. The LLVM
  416. // parser will drop debug info with a different version number
  417. // (and warn about it, too).
  418. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  419. llvm::DEBUG_METADATA_VERSION);
  420. // We need to record the widths of enums and wchar_t, so that we can generate
  421. // the correct build attributes in the ARM backend.
  422. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  423. if ( Arch == llvm::Triple::arm
  424. || Arch == llvm::Triple::armeb
  425. || Arch == llvm::Triple::thumb
  426. || Arch == llvm::Triple::thumbeb) {
  427. // Width of wchar_t in bytes
  428. uint64_t WCharWidth =
  429. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  430. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  431. // The minimum width of an enum in bytes
  432. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  433. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  434. }
  435. if (CodeGenOpts.SanitizeCfiCrossDso) {
  436. // Indicate that we want cross-DSO control flow integrity checks.
  437. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  438. }
  439. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  440. // Indicate whether __nvvm_reflect should be configured to flush denormal
  441. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  442. // property.)
  443. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  444. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  445. }
  446. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  447. assert(PLevel < 3 && "Invalid PIC Level");
  448. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  449. if (Context.getLangOpts().PIE)
  450. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  451. }
  452. SimplifyPersonality();
  453. if (getCodeGenOpts().EmitDeclMetadata)
  454. EmitDeclMetadata();
  455. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  456. EmitCoverageFile();
  457. if (DebugInfo)
  458. DebugInfo->finalize();
  459. EmitVersionIdentMetadata();
  460. EmitTargetMetadata();
  461. }
  462. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  463. // Make sure that this type is translated.
  464. Types.UpdateCompletedType(TD);
  465. }
  466. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  467. // Make sure that this type is translated.
  468. Types.RefreshTypeCacheForClass(RD);
  469. }
  470. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  471. if (!TBAA)
  472. return nullptr;
  473. return TBAA->getTBAAInfo(QTy);
  474. }
  475. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  476. if (!TBAA)
  477. return nullptr;
  478. return TBAA->getTBAAInfoForVTablePtr();
  479. }
  480. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  481. if (!TBAA)
  482. return nullptr;
  483. return TBAA->getTBAAStructInfo(QTy);
  484. }
  485. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  486. llvm::MDNode *AccessN,
  487. uint64_t O) {
  488. if (!TBAA)
  489. return nullptr;
  490. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  491. }
  492. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  493. /// and struct-path aware TBAA, the tag has the same format:
  494. /// base type, access type and offset.
  495. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  496. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  497. llvm::MDNode *TBAAInfo,
  498. bool ConvertTypeToTag) {
  499. if (ConvertTypeToTag && TBAA)
  500. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  501. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  502. else
  503. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  504. }
  505. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  506. llvm::Instruction *I, const CXXRecordDecl *RD) {
  507. llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  508. auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
  509. // Check if we have to wrap MDString in MDNode.
  510. if (!MetaDataNode)
  511. MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
  512. I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
  513. }
  514. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  515. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  516. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  517. }
  518. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  519. /// specified stmt yet.
  520. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  521. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  522. "cannot compile this %0 yet");
  523. std::string Msg = Type;
  524. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  525. << Msg << S->getSourceRange();
  526. }
  527. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  528. /// specified decl yet.
  529. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  530. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  531. "cannot compile this %0 yet");
  532. std::string Msg = Type;
  533. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  534. }
  535. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  536. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  537. }
  538. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  539. const NamedDecl *D) const {
  540. // Internal definitions always have default visibility.
  541. if (GV->hasLocalLinkage()) {
  542. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  543. return;
  544. }
  545. // Set visibility for definitions.
  546. LinkageInfo LV = D->getLinkageAndVisibility();
  547. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  548. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  549. }
  550. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  551. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  552. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  553. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  554. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  555. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  556. }
  557. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  558. CodeGenOptions::TLSModel M) {
  559. switch (M) {
  560. case CodeGenOptions::GeneralDynamicTLSModel:
  561. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  562. case CodeGenOptions::LocalDynamicTLSModel:
  563. return llvm::GlobalVariable::LocalDynamicTLSModel;
  564. case CodeGenOptions::InitialExecTLSModel:
  565. return llvm::GlobalVariable::InitialExecTLSModel;
  566. case CodeGenOptions::LocalExecTLSModel:
  567. return llvm::GlobalVariable::LocalExecTLSModel;
  568. }
  569. llvm_unreachable("Invalid TLS model!");
  570. }
  571. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  572. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  573. llvm::GlobalValue::ThreadLocalMode TLM;
  574. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  575. // Override the TLS model if it is explicitly specified.
  576. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  577. TLM = GetLLVMTLSModel(Attr->getModel());
  578. }
  579. GV->setThreadLocalMode(TLM);
  580. }
  581. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  582. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  583. // Some ABIs don't have constructor variants. Make sure that base and
  584. // complete constructors get mangled the same.
  585. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  586. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  587. CXXCtorType OrigCtorType = GD.getCtorType();
  588. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  589. if (OrigCtorType == Ctor_Base)
  590. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  591. }
  592. }
  593. StringRef &FoundStr = MangledDeclNames[CanonicalGD];
  594. if (!FoundStr.empty())
  595. return FoundStr;
  596. const auto *ND = cast<NamedDecl>(GD.getDecl());
  597. SmallString<256> Buffer;
  598. StringRef Str;
  599. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  600. llvm::raw_svector_ostream Out(Buffer);
  601. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  602. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  603. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  604. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  605. else
  606. getCXXABI().getMangleContext().mangleName(ND, Out);
  607. Str = Out.str();
  608. } else {
  609. IdentifierInfo *II = ND->getIdentifier();
  610. assert(II && "Attempt to mangle unnamed decl.");
  611. const auto *FD = dyn_cast<FunctionDecl>(ND);
  612. if (FD &&
  613. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  614. llvm::raw_svector_ostream Out(Buffer);
  615. Out << "__regcall3__" << II->getName();
  616. Str = Out.str();
  617. } else {
  618. Str = II->getName();
  619. }
  620. }
  621. // Keep the first result in the case of a mangling collision.
  622. auto Result = Manglings.insert(std::make_pair(Str, GD));
  623. return FoundStr = Result.first->first();
  624. }
  625. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  626. const BlockDecl *BD) {
  627. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  628. const Decl *D = GD.getDecl();
  629. SmallString<256> Buffer;
  630. llvm::raw_svector_ostream Out(Buffer);
  631. if (!D)
  632. MangleCtx.mangleGlobalBlock(BD,
  633. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  634. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  635. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  636. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  637. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  638. else
  639. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  640. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  641. return Result.first->first();
  642. }
  643. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  644. return getModule().getNamedValue(Name);
  645. }
  646. /// AddGlobalCtor - Add a function to the list that will be called before
  647. /// main() runs.
  648. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  649. llvm::Constant *AssociatedData) {
  650. // FIXME: Type coercion of void()* types.
  651. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  652. }
  653. /// AddGlobalDtor - Add a function to the list that will be called
  654. /// when the module is unloaded.
  655. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  656. // FIXME: Type coercion of void()* types.
  657. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  658. }
  659. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  660. if (Fns.empty()) return;
  661. // Ctor function type is void()*.
  662. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  663. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  664. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  665. llvm::StructType *CtorStructTy = llvm::StructType::get(
  666. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  667. // Construct the constructor and destructor arrays.
  668. ConstantInitBuilder builder(*this);
  669. auto ctors = builder.beginArray(CtorStructTy);
  670. for (const auto &I : Fns) {
  671. auto ctor = ctors.beginStruct(CtorStructTy);
  672. ctor.addInt(Int32Ty, I.Priority);
  673. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  674. if (I.AssociatedData)
  675. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  676. else
  677. ctor.addNullPointer(VoidPtrTy);
  678. ctor.finishAndAddTo(ctors);
  679. }
  680. auto list =
  681. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  682. /*constant*/ false,
  683. llvm::GlobalValue::AppendingLinkage);
  684. // The LTO linker doesn't seem to like it when we set an alignment
  685. // on appending variables. Take it off as a workaround.
  686. list->setAlignment(0);
  687. Fns.clear();
  688. }
  689. llvm::GlobalValue::LinkageTypes
  690. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  691. const auto *D = cast<FunctionDecl>(GD.getDecl());
  692. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  693. if (isa<CXXDestructorDecl>(D) &&
  694. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  695. GD.getDtorType())) {
  696. // Destructor variants in the Microsoft C++ ABI are always internal or
  697. // linkonce_odr thunks emitted on an as-needed basis.
  698. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  699. : llvm::GlobalValue::LinkOnceODRLinkage;
  700. }
  701. if (isa<CXXConstructorDecl>(D) &&
  702. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  703. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  704. // Our approach to inheriting constructors is fundamentally different from
  705. // that used by the MS ABI, so keep our inheriting constructor thunks
  706. // internal rather than trying to pick an unambiguous mangling for them.
  707. return llvm::GlobalValue::InternalLinkage;
  708. }
  709. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  710. }
  711. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  712. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  713. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  714. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  715. // Don't dllexport/import destructor thunks.
  716. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  717. return;
  718. }
  719. }
  720. if (FD->hasAttr<DLLImportAttr>())
  721. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  722. else if (FD->hasAttr<DLLExportAttr>())
  723. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  724. else
  725. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  726. }
  727. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  728. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  729. if (!MDS) return nullptr;
  730. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  731. }
  732. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  733. llvm::Function *F) {
  734. setNonAliasAttributes(D, F);
  735. }
  736. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  737. const CGFunctionInfo &Info,
  738. llvm::Function *F) {
  739. unsigned CallingConv;
  740. AttributeListType AttributeList;
  741. ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
  742. false);
  743. F->setAttributes(llvm::AttributeList::get(getLLVMContext(), AttributeList));
  744. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  745. }
  746. /// Determines whether the language options require us to model
  747. /// unwind exceptions. We treat -fexceptions as mandating this
  748. /// except under the fragile ObjC ABI with only ObjC exceptions
  749. /// enabled. This means, for example, that C with -fexceptions
  750. /// enables this.
  751. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  752. // If exceptions are completely disabled, obviously this is false.
  753. if (!LangOpts.Exceptions) return false;
  754. // If C++ exceptions are enabled, this is true.
  755. if (LangOpts.CXXExceptions) return true;
  756. // If ObjC exceptions are enabled, this depends on the ABI.
  757. if (LangOpts.ObjCExceptions) {
  758. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  759. }
  760. return true;
  761. }
  762. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  763. llvm::Function *F) {
  764. llvm::AttrBuilder B;
  765. if (CodeGenOpts.UnwindTables)
  766. B.addAttribute(llvm::Attribute::UWTable);
  767. if (!hasUnwindExceptions(LangOpts))
  768. B.addAttribute(llvm::Attribute::NoUnwind);
  769. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  770. B.addAttribute(llvm::Attribute::StackProtect);
  771. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  772. B.addAttribute(llvm::Attribute::StackProtectStrong);
  773. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  774. B.addAttribute(llvm::Attribute::StackProtectReq);
  775. if (!D) {
  776. // If we don't have a declaration to control inlining, the function isn't
  777. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  778. // disabled, mark the function as noinline.
  779. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  780. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  781. B.addAttribute(llvm::Attribute::NoInline);
  782. F->addAttributes(
  783. llvm::AttributeList::FunctionIndex,
  784. llvm::AttributeList::get(F->getContext(),
  785. llvm::AttributeList::FunctionIndex, B));
  786. return;
  787. }
  788. if (D->hasAttr<OptimizeNoneAttr>()) {
  789. B.addAttribute(llvm::Attribute::OptimizeNone);
  790. // OptimizeNone implies noinline; we should not be inlining such functions.
  791. B.addAttribute(llvm::Attribute::NoInline);
  792. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  793. "OptimizeNone and AlwaysInline on same function!");
  794. // We still need to handle naked functions even though optnone subsumes
  795. // much of their semantics.
  796. if (D->hasAttr<NakedAttr>())
  797. B.addAttribute(llvm::Attribute::Naked);
  798. // OptimizeNone wins over OptimizeForSize and MinSize.
  799. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  800. F->removeFnAttr(llvm::Attribute::MinSize);
  801. } else if (D->hasAttr<NakedAttr>()) {
  802. // Naked implies noinline: we should not be inlining such functions.
  803. B.addAttribute(llvm::Attribute::Naked);
  804. B.addAttribute(llvm::Attribute::NoInline);
  805. } else if (D->hasAttr<NoDuplicateAttr>()) {
  806. B.addAttribute(llvm::Attribute::NoDuplicate);
  807. } else if (D->hasAttr<NoInlineAttr>()) {
  808. B.addAttribute(llvm::Attribute::NoInline);
  809. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  810. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  811. // (noinline wins over always_inline, and we can't specify both in IR)
  812. B.addAttribute(llvm::Attribute::AlwaysInline);
  813. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  814. // If we're not inlining, then force everything that isn't always_inline to
  815. // carry an explicit noinline attribute.
  816. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  817. B.addAttribute(llvm::Attribute::NoInline);
  818. } else {
  819. // Otherwise, propagate the inline hint attribute and potentially use its
  820. // absence to mark things as noinline.
  821. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  822. if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
  823. return Redecl->isInlineSpecified();
  824. })) {
  825. B.addAttribute(llvm::Attribute::InlineHint);
  826. } else if (CodeGenOpts.getInlining() ==
  827. CodeGenOptions::OnlyHintInlining &&
  828. !FD->isInlined() &&
  829. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  830. B.addAttribute(llvm::Attribute::NoInline);
  831. }
  832. }
  833. }
  834. // Add other optimization related attributes if we are optimizing this
  835. // function.
  836. if (!D->hasAttr<OptimizeNoneAttr>()) {
  837. if (D->hasAttr<ColdAttr>()) {
  838. B.addAttribute(llvm::Attribute::OptimizeForSize);
  839. B.addAttribute(llvm::Attribute::Cold);
  840. }
  841. if (D->hasAttr<MinSizeAttr>())
  842. B.addAttribute(llvm::Attribute::MinSize);
  843. }
  844. F->addAttributes(llvm::AttributeList::FunctionIndex,
  845. llvm::AttributeList::get(
  846. F->getContext(), llvm::AttributeList::FunctionIndex, B));
  847. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  848. if (alignment)
  849. F->setAlignment(alignment);
  850. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  851. // reserve a bit for differentiating between virtual and non-virtual member
  852. // functions. If the current target's C++ ABI requires this and this is a
  853. // member function, set its alignment accordingly.
  854. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  855. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  856. F->setAlignment(2);
  857. }
  858. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  859. if (CodeGenOpts.SanitizeCfiCrossDso)
  860. if (auto *FD = dyn_cast<FunctionDecl>(D))
  861. CreateFunctionTypeMetadata(FD, F);
  862. }
  863. void CodeGenModule::SetCommonAttributes(const Decl *D,
  864. llvm::GlobalValue *GV) {
  865. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  866. setGlobalVisibility(GV, ND);
  867. else
  868. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  869. if (D && D->hasAttr<UsedAttr>())
  870. addUsedGlobal(GV);
  871. }
  872. void CodeGenModule::setAliasAttributes(const Decl *D,
  873. llvm::GlobalValue *GV) {
  874. SetCommonAttributes(D, GV);
  875. // Process the dllexport attribute based on whether the original definition
  876. // (not necessarily the aliasee) was exported.
  877. if (D->hasAttr<DLLExportAttr>())
  878. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  879. }
  880. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  881. llvm::GlobalObject *GO) {
  882. SetCommonAttributes(D, GO);
  883. if (D)
  884. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  885. GO->setSection(SA->getName());
  886. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  887. }
  888. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  889. llvm::Function *F,
  890. const CGFunctionInfo &FI) {
  891. SetLLVMFunctionAttributes(D, FI, F);
  892. SetLLVMFunctionAttributesForDefinition(D, F);
  893. F->setLinkage(llvm::Function::InternalLinkage);
  894. setNonAliasAttributes(D, F);
  895. }
  896. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  897. const NamedDecl *ND) {
  898. // Set linkage and visibility in case we never see a definition.
  899. LinkageInfo LV = ND->getLinkageAndVisibility();
  900. if (LV.getLinkage() != ExternalLinkage) {
  901. // Don't set internal linkage on declarations.
  902. } else {
  903. if (ND->hasAttr<DLLImportAttr>()) {
  904. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  905. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  906. } else if (ND->hasAttr<DLLExportAttr>()) {
  907. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  908. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  909. // "extern_weak" is overloaded in LLVM; we probably should have
  910. // separate linkage types for this.
  911. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  912. }
  913. // Set visibility on a declaration only if it's explicit.
  914. if (LV.isVisibilityExplicit())
  915. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  916. }
  917. }
  918. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  919. llvm::Function *F) {
  920. // Only if we are checking indirect calls.
  921. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  922. return;
  923. // Non-static class methods are handled via vtable pointer checks elsewhere.
  924. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  925. return;
  926. // Additionally, if building with cross-DSO support...
  927. if (CodeGenOpts.SanitizeCfiCrossDso) {
  928. // Skip available_externally functions. They won't be codegen'ed in the
  929. // current module anyway.
  930. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  931. return;
  932. }
  933. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  934. F->addTypeMetadata(0, MD);
  935. // Emit a hash-based bit set entry for cross-DSO calls.
  936. if (CodeGenOpts.SanitizeCfiCrossDso)
  937. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  938. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  939. }
  940. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  941. bool IsIncompleteFunction,
  942. bool IsThunk) {
  943. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  944. // If this is an intrinsic function, set the function's attributes
  945. // to the intrinsic's attributes.
  946. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  947. return;
  948. }
  949. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  950. if (!IsIncompleteFunction)
  951. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  952. // Add the Returned attribute for "this", except for iOS 5 and earlier
  953. // where substantial code, including the libstdc++ dylib, was compiled with
  954. // GCC and does not actually return "this".
  955. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  956. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  957. assert(!F->arg_empty() &&
  958. F->arg_begin()->getType()
  959. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  960. "unexpected this return");
  961. F->addAttribute(1, llvm::Attribute::Returned);
  962. }
  963. // Only a few attributes are set on declarations; these may later be
  964. // overridden by a definition.
  965. setLinkageAndVisibilityForGV(F, FD);
  966. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  967. F->setSection(SA->getName());
  968. if (FD->isReplaceableGlobalAllocationFunction()) {
  969. // A replaceable global allocation function does not act like a builtin by
  970. // default, only if it is invoked by a new-expression or delete-expression.
  971. F->addAttribute(llvm::AttributeList::FunctionIndex,
  972. llvm::Attribute::NoBuiltin);
  973. // A sane operator new returns a non-aliasing pointer.
  974. // FIXME: Also add NonNull attribute to the return value
  975. // for the non-nothrow forms?
  976. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  977. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  978. (Kind == OO_New || Kind == OO_Array_New))
  979. F->addAttribute(llvm::AttributeList::ReturnIndex,
  980. llvm::Attribute::NoAlias);
  981. }
  982. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  983. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  984. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  985. if (MD->isVirtual())
  986. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  987. // Don't emit entries for function declarations in the cross-DSO mode. This
  988. // is handled with better precision by the receiving DSO.
  989. if (!CodeGenOpts.SanitizeCfiCrossDso)
  990. CreateFunctionTypeMetadata(FD, F);
  991. }
  992. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  993. assert(!GV->isDeclaration() &&
  994. "Only globals with definition can force usage.");
  995. LLVMUsed.emplace_back(GV);
  996. }
  997. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  998. assert(!GV->isDeclaration() &&
  999. "Only globals with definition can force usage.");
  1000. LLVMCompilerUsed.emplace_back(GV);
  1001. }
  1002. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1003. std::vector<llvm::WeakVH> &List) {
  1004. // Don't create llvm.used if there is no need.
  1005. if (List.empty())
  1006. return;
  1007. // Convert List to what ConstantArray needs.
  1008. SmallVector<llvm::Constant*, 8> UsedArray;
  1009. UsedArray.resize(List.size());
  1010. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1011. UsedArray[i] =
  1012. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1013. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1014. }
  1015. if (UsedArray.empty())
  1016. return;
  1017. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1018. auto *GV = new llvm::GlobalVariable(
  1019. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1020. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1021. GV->setSection("llvm.metadata");
  1022. }
  1023. void CodeGenModule::emitLLVMUsed() {
  1024. emitUsed(*this, "llvm.used", LLVMUsed);
  1025. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1026. }
  1027. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1028. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1029. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1030. }
  1031. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1032. llvm::SmallString<32> Opt;
  1033. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1034. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1035. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1036. }
  1037. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1038. llvm::SmallString<24> Opt;
  1039. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1040. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1041. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1042. }
  1043. /// \brief Add link options implied by the given module, including modules
  1044. /// it depends on, using a postorder walk.
  1045. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1046. SmallVectorImpl<llvm::Metadata *> &Metadata,
  1047. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1048. // Import this module's parent.
  1049. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1050. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1051. }
  1052. // Import this module's dependencies.
  1053. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1054. if (Visited.insert(Mod->Imports[I - 1]).second)
  1055. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1056. }
  1057. // Add linker options to link against the libraries/frameworks
  1058. // described by this module.
  1059. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1060. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1061. // Link against a framework. Frameworks are currently Darwin only, so we
  1062. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1063. if (Mod->LinkLibraries[I-1].IsFramework) {
  1064. llvm::Metadata *Args[2] = {
  1065. llvm::MDString::get(Context, "-framework"),
  1066. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1067. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1068. continue;
  1069. }
  1070. // Link against a library.
  1071. llvm::SmallString<24> Opt;
  1072. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1073. Mod->LinkLibraries[I-1].Library, Opt);
  1074. auto *OptString = llvm::MDString::get(Context, Opt);
  1075. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1076. }
  1077. }
  1078. void CodeGenModule::EmitModuleLinkOptions() {
  1079. // Collect the set of all of the modules we want to visit to emit link
  1080. // options, which is essentially the imported modules and all of their
  1081. // non-explicit child modules.
  1082. llvm::SetVector<clang::Module *> LinkModules;
  1083. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1084. SmallVector<clang::Module *, 16> Stack;
  1085. // Seed the stack with imported modules.
  1086. for (Module *M : ImportedModules) {
  1087. // Do not add any link flags when an implementation TU of a module imports
  1088. // a header of that same module.
  1089. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1090. !getLangOpts().isCompilingModule())
  1091. continue;
  1092. if (Visited.insert(M).second)
  1093. Stack.push_back(M);
  1094. }
  1095. // Find all of the modules to import, making a little effort to prune
  1096. // non-leaf modules.
  1097. while (!Stack.empty()) {
  1098. clang::Module *Mod = Stack.pop_back_val();
  1099. bool AnyChildren = false;
  1100. // Visit the submodules of this module.
  1101. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1102. SubEnd = Mod->submodule_end();
  1103. Sub != SubEnd; ++Sub) {
  1104. // Skip explicit children; they need to be explicitly imported to be
  1105. // linked against.
  1106. if ((*Sub)->IsExplicit)
  1107. continue;
  1108. if (Visited.insert(*Sub).second) {
  1109. Stack.push_back(*Sub);
  1110. AnyChildren = true;
  1111. }
  1112. }
  1113. // We didn't find any children, so add this module to the list of
  1114. // modules to link against.
  1115. if (!AnyChildren) {
  1116. LinkModules.insert(Mod);
  1117. }
  1118. }
  1119. // Add link options for all of the imported modules in reverse topological
  1120. // order. We don't do anything to try to order import link flags with respect
  1121. // to linker options inserted by things like #pragma comment().
  1122. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  1123. Visited.clear();
  1124. for (Module *M : LinkModules)
  1125. if (Visited.insert(M).second)
  1126. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1127. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1128. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1129. // Add the linker options metadata flag.
  1130. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  1131. llvm::MDNode::get(getLLVMContext(),
  1132. LinkerOptionsMetadata));
  1133. }
  1134. void CodeGenModule::EmitDeferred() {
  1135. // Emit code for any potentially referenced deferred decls. Since a
  1136. // previously unused static decl may become used during the generation of code
  1137. // for a static function, iterate until no changes are made.
  1138. if (!DeferredVTables.empty()) {
  1139. EmitDeferredVTables();
  1140. // Emitting a vtable doesn't directly cause more vtables to
  1141. // become deferred, although it can cause functions to be
  1142. // emitted that then need those vtables.
  1143. assert(DeferredVTables.empty());
  1144. }
  1145. // Stop if we're out of both deferred vtables and deferred declarations.
  1146. if (DeferredDeclsToEmit.empty())
  1147. return;
  1148. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1149. // work, it will not interfere with this.
  1150. std::vector<DeferredGlobal> CurDeclsToEmit;
  1151. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1152. for (DeferredGlobal &G : CurDeclsToEmit) {
  1153. GlobalDecl D = G.GD;
  1154. G.GV = nullptr;
  1155. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1156. // to get GlobalValue with exactly the type we need, not something that
  1157. // might had been created for another decl with the same mangled name but
  1158. // different type.
  1159. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1160. GetAddrOfGlobal(D, ForDefinition));
  1161. // In case of different address spaces, we may still get a cast, even with
  1162. // IsForDefinition equal to true. Query mangled names table to get
  1163. // GlobalValue.
  1164. if (!GV)
  1165. GV = GetGlobalValue(getMangledName(D));
  1166. // Make sure GetGlobalValue returned non-null.
  1167. assert(GV);
  1168. // Check to see if we've already emitted this. This is necessary
  1169. // for a couple of reasons: first, decls can end up in the
  1170. // deferred-decls queue multiple times, and second, decls can end
  1171. // up with definitions in unusual ways (e.g. by an extern inline
  1172. // function acquiring a strong function redefinition). Just
  1173. // ignore these cases.
  1174. if (!GV->isDeclaration())
  1175. continue;
  1176. // Otherwise, emit the definition and move on to the next one.
  1177. EmitGlobalDefinition(D, GV);
  1178. // If we found out that we need to emit more decls, do that recursively.
  1179. // This has the advantage that the decls are emitted in a DFS and related
  1180. // ones are close together, which is convenient for testing.
  1181. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1182. EmitDeferred();
  1183. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1184. }
  1185. }
  1186. }
  1187. void CodeGenModule::EmitGlobalAnnotations() {
  1188. if (Annotations.empty())
  1189. return;
  1190. // Create a new global variable for the ConstantStruct in the Module.
  1191. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1192. Annotations[0]->getType(), Annotations.size()), Annotations);
  1193. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1194. llvm::GlobalValue::AppendingLinkage,
  1195. Array, "llvm.global.annotations");
  1196. gv->setSection(AnnotationSection);
  1197. }
  1198. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1199. llvm::Constant *&AStr = AnnotationStrings[Str];
  1200. if (AStr)
  1201. return AStr;
  1202. // Not found yet, create a new global.
  1203. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1204. auto *gv =
  1205. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1206. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1207. gv->setSection(AnnotationSection);
  1208. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1209. AStr = gv;
  1210. return gv;
  1211. }
  1212. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1213. SourceManager &SM = getContext().getSourceManager();
  1214. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1215. if (PLoc.isValid())
  1216. return EmitAnnotationString(PLoc.getFilename());
  1217. return EmitAnnotationString(SM.getBufferName(Loc));
  1218. }
  1219. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1220. SourceManager &SM = getContext().getSourceManager();
  1221. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1222. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1223. SM.getExpansionLineNumber(L);
  1224. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1225. }
  1226. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1227. const AnnotateAttr *AA,
  1228. SourceLocation L) {
  1229. // Get the globals for file name, annotation, and the line number.
  1230. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1231. *UnitGV = EmitAnnotationUnit(L),
  1232. *LineNoCst = EmitAnnotationLineNo(L);
  1233. // Create the ConstantStruct for the global annotation.
  1234. llvm::Constant *Fields[4] = {
  1235. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1236. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1237. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1238. LineNoCst
  1239. };
  1240. return llvm::ConstantStruct::getAnon(Fields);
  1241. }
  1242. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1243. llvm::GlobalValue *GV) {
  1244. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1245. // Get the struct elements for these annotations.
  1246. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1247. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1248. }
  1249. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1250. SourceLocation Loc) const {
  1251. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1252. // Blacklist by function name.
  1253. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1254. return true;
  1255. // Blacklist by location.
  1256. if (Loc.isValid())
  1257. return SanitizerBL.isBlacklistedLocation(Loc);
  1258. // If location is unknown, this may be a compiler-generated function. Assume
  1259. // it's located in the main file.
  1260. auto &SM = Context.getSourceManager();
  1261. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1262. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1263. }
  1264. return false;
  1265. }
  1266. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1267. SourceLocation Loc, QualType Ty,
  1268. StringRef Category) const {
  1269. // For now globals can be blacklisted only in ASan and KASan.
  1270. if (!LangOpts.Sanitize.hasOneOf(
  1271. SanitizerKind::Address | SanitizerKind::KernelAddress))
  1272. return false;
  1273. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1274. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1275. return true;
  1276. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1277. return true;
  1278. // Check global type.
  1279. if (!Ty.isNull()) {
  1280. // Drill down the array types: if global variable of a fixed type is
  1281. // blacklisted, we also don't instrument arrays of them.
  1282. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1283. Ty = AT->getElementType();
  1284. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1285. // We allow to blacklist only record types (classes, structs etc.)
  1286. if (Ty->isRecordType()) {
  1287. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1288. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1289. return true;
  1290. }
  1291. }
  1292. return false;
  1293. }
  1294. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1295. StringRef Category) const {
  1296. if (!LangOpts.XRayInstrument)
  1297. return false;
  1298. const auto &XRayFilter = getContext().getXRayFilter();
  1299. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1300. auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
  1301. if (Loc.isValid())
  1302. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1303. if (Attr == ImbueAttr::NONE)
  1304. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1305. switch (Attr) {
  1306. case ImbueAttr::NONE:
  1307. return false;
  1308. case ImbueAttr::ALWAYS:
  1309. Fn->addFnAttr("function-instrument", "xray-always");
  1310. break;
  1311. case ImbueAttr::NEVER:
  1312. Fn->addFnAttr("function-instrument", "xray-never");
  1313. break;
  1314. }
  1315. return true;
  1316. }
  1317. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1318. // Never defer when EmitAllDecls is specified.
  1319. if (LangOpts.EmitAllDecls)
  1320. return true;
  1321. return getContext().DeclMustBeEmitted(Global);
  1322. }
  1323. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1324. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1325. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1326. // Implicit template instantiations may change linkage if they are later
  1327. // explicitly instantiated, so they should not be emitted eagerly.
  1328. return false;
  1329. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1330. if (Context.getInlineVariableDefinitionKind(VD) ==
  1331. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1332. // A definition of an inline constexpr static data member may change
  1333. // linkage later if it's redeclared outside the class.
  1334. return false;
  1335. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1336. // codegen for global variables, because they may be marked as threadprivate.
  1337. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1338. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1339. return false;
  1340. return true;
  1341. }
  1342. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1343. const CXXUuidofExpr* E) {
  1344. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1345. // well-formed.
  1346. StringRef Uuid = E->getUuidStr();
  1347. std::string Name = "_GUID_" + Uuid.lower();
  1348. std::replace(Name.begin(), Name.end(), '-', '_');
  1349. // The UUID descriptor should be pointer aligned.
  1350. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1351. // Look for an existing global.
  1352. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1353. return ConstantAddress(GV, Alignment);
  1354. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1355. assert(Init && "failed to initialize as constant");
  1356. auto *GV = new llvm::GlobalVariable(
  1357. getModule(), Init->getType(),
  1358. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1359. if (supportsCOMDAT())
  1360. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1361. return ConstantAddress(GV, Alignment);
  1362. }
  1363. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1364. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1365. assert(AA && "No alias?");
  1366. CharUnits Alignment = getContext().getDeclAlign(VD);
  1367. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1368. // See if there is already something with the target's name in the module.
  1369. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1370. if (Entry) {
  1371. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1372. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1373. return ConstantAddress(Ptr, Alignment);
  1374. }
  1375. llvm::Constant *Aliasee;
  1376. if (isa<llvm::FunctionType>(DeclTy))
  1377. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1378. GlobalDecl(cast<FunctionDecl>(VD)),
  1379. /*ForVTable=*/false);
  1380. else
  1381. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1382. llvm::PointerType::getUnqual(DeclTy),
  1383. nullptr);
  1384. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1385. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1386. WeakRefReferences.insert(F);
  1387. return ConstantAddress(Aliasee, Alignment);
  1388. }
  1389. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1390. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1391. // Weak references don't produce any output by themselves.
  1392. if (Global->hasAttr<WeakRefAttr>())
  1393. return;
  1394. // If this is an alias definition (which otherwise looks like a declaration)
  1395. // emit it now.
  1396. if (Global->hasAttr<AliasAttr>())
  1397. return EmitAliasDefinition(GD);
  1398. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1399. if (Global->hasAttr<IFuncAttr>())
  1400. return emitIFuncDefinition(GD);
  1401. // If this is CUDA, be selective about which declarations we emit.
  1402. if (LangOpts.CUDA) {
  1403. if (LangOpts.CUDAIsDevice) {
  1404. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1405. !Global->hasAttr<CUDAGlobalAttr>() &&
  1406. !Global->hasAttr<CUDAConstantAttr>() &&
  1407. !Global->hasAttr<CUDASharedAttr>())
  1408. return;
  1409. } else {
  1410. // We need to emit host-side 'shadows' for all global
  1411. // device-side variables because the CUDA runtime needs their
  1412. // size and host-side address in order to provide access to
  1413. // their device-side incarnations.
  1414. // So device-only functions are the only things we skip.
  1415. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1416. Global->hasAttr<CUDADeviceAttr>())
  1417. return;
  1418. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1419. "Expected Variable or Function");
  1420. }
  1421. }
  1422. if (LangOpts.OpenMP) {
  1423. // If this is OpenMP device, check if it is legal to emit this global
  1424. // normally.
  1425. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1426. return;
  1427. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1428. if (MustBeEmitted(Global))
  1429. EmitOMPDeclareReduction(DRD);
  1430. return;
  1431. }
  1432. }
  1433. // Ignore declarations, they will be emitted on their first use.
  1434. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1435. // Forward declarations are emitted lazily on first use.
  1436. if (!FD->doesThisDeclarationHaveABody()) {
  1437. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1438. return;
  1439. StringRef MangledName = getMangledName(GD);
  1440. // Compute the function info and LLVM type.
  1441. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1442. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1443. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1444. /*DontDefer=*/false);
  1445. return;
  1446. }
  1447. } else {
  1448. const auto *VD = cast<VarDecl>(Global);
  1449. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1450. // We need to emit device-side global CUDA variables even if a
  1451. // variable does not have a definition -- we still need to define
  1452. // host-side shadow for it.
  1453. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1454. !VD->hasDefinition() &&
  1455. (VD->hasAttr<CUDAConstantAttr>() ||
  1456. VD->hasAttr<CUDADeviceAttr>());
  1457. if (!MustEmitForCuda &&
  1458. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1459. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1460. // If this declaration may have caused an inline variable definition to
  1461. // change linkage, make sure that it's emitted.
  1462. if (Context.getInlineVariableDefinitionKind(VD) ==
  1463. ASTContext::InlineVariableDefinitionKind::Strong)
  1464. GetAddrOfGlobalVar(VD);
  1465. return;
  1466. }
  1467. }
  1468. // Defer code generation to first use when possible, e.g. if this is an inline
  1469. // function. If the global must always be emitted, do it eagerly if possible
  1470. // to benefit from cache locality.
  1471. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1472. // Emit the definition if it can't be deferred.
  1473. EmitGlobalDefinition(GD);
  1474. return;
  1475. }
  1476. // If we're deferring emission of a C++ variable with an
  1477. // initializer, remember the order in which it appeared in the file.
  1478. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1479. cast<VarDecl>(Global)->hasInit()) {
  1480. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1481. CXXGlobalInits.push_back(nullptr);
  1482. }
  1483. StringRef MangledName = getMangledName(GD);
  1484. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1485. // The value has already been used and should therefore be emitted.
  1486. addDeferredDeclToEmit(GV, GD);
  1487. } else if (MustBeEmitted(Global)) {
  1488. // The value must be emitted, but cannot be emitted eagerly.
  1489. assert(!MayBeEmittedEagerly(Global));
  1490. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1491. } else {
  1492. // Otherwise, remember that we saw a deferred decl with this name. The
  1493. // first use of the mangled name will cause it to move into
  1494. // DeferredDeclsToEmit.
  1495. DeferredDecls[MangledName] = GD;
  1496. }
  1497. }
  1498. // Check if T is a class type with a destructor that's not dllimport.
  1499. static bool HasNonDllImportDtor(QualType T) {
  1500. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1501. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1502. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1503. return true;
  1504. return false;
  1505. }
  1506. namespace {
  1507. struct FunctionIsDirectlyRecursive :
  1508. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1509. const StringRef Name;
  1510. const Builtin::Context &BI;
  1511. bool Result;
  1512. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1513. Name(N), BI(C), Result(false) {
  1514. }
  1515. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1516. bool TraverseCallExpr(CallExpr *E) {
  1517. const FunctionDecl *FD = E->getDirectCallee();
  1518. if (!FD)
  1519. return true;
  1520. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1521. if (Attr && Name == Attr->getLabel()) {
  1522. Result = true;
  1523. return false;
  1524. }
  1525. unsigned BuiltinID = FD->getBuiltinID();
  1526. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1527. return true;
  1528. StringRef BuiltinName = BI.getName(BuiltinID);
  1529. if (BuiltinName.startswith("__builtin_") &&
  1530. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1531. Result = true;
  1532. return false;
  1533. }
  1534. return true;
  1535. }
  1536. };
  1537. // Make sure we're not referencing non-imported vars or functions.
  1538. struct DLLImportFunctionVisitor
  1539. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1540. bool SafeToInline = true;
  1541. bool shouldVisitImplicitCode() const { return true; }
  1542. bool VisitVarDecl(VarDecl *VD) {
  1543. if (VD->getTLSKind()) {
  1544. // A thread-local variable cannot be imported.
  1545. SafeToInline = false;
  1546. return SafeToInline;
  1547. }
  1548. // A variable definition might imply a destructor call.
  1549. if (VD->isThisDeclarationADefinition())
  1550. SafeToInline = !HasNonDllImportDtor(VD->getType());
  1551. return SafeToInline;
  1552. }
  1553. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1554. if (const auto *D = E->getTemporary()->getDestructor())
  1555. SafeToInline = D->hasAttr<DLLImportAttr>();
  1556. return SafeToInline;
  1557. }
  1558. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1559. ValueDecl *VD = E->getDecl();
  1560. if (isa<FunctionDecl>(VD))
  1561. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1562. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1563. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1564. return SafeToInline;
  1565. }
  1566. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1567. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1568. return SafeToInline;
  1569. }
  1570. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  1571. CXXMethodDecl *M = E->getMethodDecl();
  1572. if (!M) {
  1573. // Call through a pointer to member function. This is safe to inline.
  1574. SafeToInline = true;
  1575. } else {
  1576. SafeToInline = M->hasAttr<DLLImportAttr>();
  1577. }
  1578. return SafeToInline;
  1579. }
  1580. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1581. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1582. return SafeToInline;
  1583. }
  1584. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1585. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1586. return SafeToInline;
  1587. }
  1588. };
  1589. }
  1590. // isTriviallyRecursive - Check if this function calls another
  1591. // decl that, because of the asm attribute or the other decl being a builtin,
  1592. // ends up pointing to itself.
  1593. bool
  1594. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1595. StringRef Name;
  1596. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1597. // asm labels are a special kind of mangling we have to support.
  1598. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1599. if (!Attr)
  1600. return false;
  1601. Name = Attr->getLabel();
  1602. } else {
  1603. Name = FD->getName();
  1604. }
  1605. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1606. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1607. return Walker.Result;
  1608. }
  1609. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1610. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1611. return true;
  1612. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1613. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1614. return false;
  1615. if (F->hasAttr<DLLImportAttr>()) {
  1616. // Check whether it would be safe to inline this dllimport function.
  1617. DLLImportFunctionVisitor Visitor;
  1618. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1619. if (!Visitor.SafeToInline)
  1620. return false;
  1621. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1622. // Implicit destructor invocations aren't captured in the AST, so the
  1623. // check above can't see them. Check for them manually here.
  1624. for (const Decl *Member : Dtor->getParent()->decls())
  1625. if (isa<FieldDecl>(Member))
  1626. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1627. return false;
  1628. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1629. if (HasNonDllImportDtor(B.getType()))
  1630. return false;
  1631. }
  1632. }
  1633. // PR9614. Avoid cases where the source code is lying to us. An available
  1634. // externally function should have an equivalent function somewhere else,
  1635. // but a function that calls itself is clearly not equivalent to the real
  1636. // implementation.
  1637. // This happens in glibc's btowc and in some configure checks.
  1638. return !isTriviallyRecursive(F);
  1639. }
  1640. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1641. const auto *D = cast<ValueDecl>(GD.getDecl());
  1642. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1643. Context.getSourceManager(),
  1644. "Generating code for declaration");
  1645. if (isa<FunctionDecl>(D)) {
  1646. // At -O0, don't generate IR for functions with available_externally
  1647. // linkage.
  1648. if (!shouldEmitFunction(GD))
  1649. return;
  1650. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1651. // Make sure to emit the definition(s) before we emit the thunks.
  1652. // This is necessary for the generation of certain thunks.
  1653. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1654. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1655. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1656. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1657. else
  1658. EmitGlobalFunctionDefinition(GD, GV);
  1659. if (Method->isVirtual())
  1660. getVTables().EmitThunks(GD);
  1661. return;
  1662. }
  1663. return EmitGlobalFunctionDefinition(GD, GV);
  1664. }
  1665. if (const auto *VD = dyn_cast<VarDecl>(D))
  1666. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1667. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1668. }
  1669. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1670. llvm::Function *NewFn);
  1671. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1672. /// module, create and return an llvm Function with the specified type. If there
  1673. /// is something in the module with the specified name, return it potentially
  1674. /// bitcasted to the right type.
  1675. ///
  1676. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1677. /// to set the attributes on the function when it is first created.
  1678. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  1679. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  1680. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  1681. ForDefinition_t IsForDefinition) {
  1682. const Decl *D = GD.getDecl();
  1683. // Lookup the entry, lazily creating it if necessary.
  1684. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1685. if (Entry) {
  1686. if (WeakRefReferences.erase(Entry)) {
  1687. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1688. if (FD && !FD->hasAttr<WeakAttr>())
  1689. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1690. }
  1691. // Handle dropped DLL attributes.
  1692. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1693. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1694. // If there are two attempts to define the same mangled name, issue an
  1695. // error.
  1696. if (IsForDefinition && !Entry->isDeclaration()) {
  1697. GlobalDecl OtherGD;
  1698. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  1699. // to make sure that we issue an error only once.
  1700. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  1701. (GD.getCanonicalDecl().getDecl() !=
  1702. OtherGD.getCanonicalDecl().getDecl()) &&
  1703. DiagnosedConflictingDefinitions.insert(GD).second) {
  1704. getDiags().Report(D->getLocation(),
  1705. diag::err_duplicate_mangled_name);
  1706. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1707. diag::note_previous_definition);
  1708. }
  1709. }
  1710. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  1711. (Entry->getType()->getElementType() == Ty)) {
  1712. return Entry;
  1713. }
  1714. // Make sure the result is of the correct type.
  1715. // (If function is requested for a definition, we always need to create a new
  1716. // function, not just return a bitcast.)
  1717. if (!IsForDefinition)
  1718. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1719. }
  1720. // This function doesn't have a complete type (for example, the return
  1721. // type is an incomplete struct). Use a fake type instead, and make
  1722. // sure not to try to set attributes.
  1723. bool IsIncompleteFunction = false;
  1724. llvm::FunctionType *FTy;
  1725. if (isa<llvm::FunctionType>(Ty)) {
  1726. FTy = cast<llvm::FunctionType>(Ty);
  1727. } else {
  1728. FTy = llvm::FunctionType::get(VoidTy, false);
  1729. IsIncompleteFunction = true;
  1730. }
  1731. llvm::Function *F =
  1732. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  1733. Entry ? StringRef() : MangledName, &getModule());
  1734. // If we already created a function with the same mangled name (but different
  1735. // type) before, take its name and add it to the list of functions to be
  1736. // replaced with F at the end of CodeGen.
  1737. //
  1738. // This happens if there is a prototype for a function (e.g. "int f()") and
  1739. // then a definition of a different type (e.g. "int f(int x)").
  1740. if (Entry) {
  1741. F->takeName(Entry);
  1742. // This might be an implementation of a function without a prototype, in
  1743. // which case, try to do special replacement of calls which match the new
  1744. // prototype. The really key thing here is that we also potentially drop
  1745. // arguments from the call site so as to make a direct call, which makes the
  1746. // inliner happier and suppresses a number of optimizer warnings (!) about
  1747. // dropping arguments.
  1748. if (!Entry->use_empty()) {
  1749. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  1750. Entry->removeDeadConstantUsers();
  1751. }
  1752. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  1753. F, Entry->getType()->getElementType()->getPointerTo());
  1754. addGlobalValReplacement(Entry, BC);
  1755. }
  1756. assert(F->getName() == MangledName && "name was uniqued!");
  1757. if (D)
  1758. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1759. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  1760. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  1761. F->addAttributes(llvm::AttributeList::FunctionIndex,
  1762. llvm::AttributeList::get(
  1763. VMContext, llvm::AttributeList::FunctionIndex, B));
  1764. }
  1765. if (!DontDefer) {
  1766. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1767. // each other bottoming out with the base dtor. Therefore we emit non-base
  1768. // dtors on usage, even if there is no dtor definition in the TU.
  1769. if (D && isa<CXXDestructorDecl>(D) &&
  1770. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1771. GD.getDtorType()))
  1772. addDeferredDeclToEmit(F, GD);
  1773. // This is the first use or definition of a mangled name. If there is a
  1774. // deferred decl with this name, remember that we need to emit it at the end
  1775. // of the file.
  1776. auto DDI = DeferredDecls.find(MangledName);
  1777. if (DDI != DeferredDecls.end()) {
  1778. // Move the potentially referenced deferred decl to the
  1779. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1780. // don't need it anymore).
  1781. addDeferredDeclToEmit(F, DDI->second);
  1782. DeferredDecls.erase(DDI);
  1783. // Otherwise, there are cases we have to worry about where we're
  1784. // using a declaration for which we must emit a definition but where
  1785. // we might not find a top-level definition:
  1786. // - member functions defined inline in their classes
  1787. // - friend functions defined inline in some class
  1788. // - special member functions with implicit definitions
  1789. // If we ever change our AST traversal to walk into class methods,
  1790. // this will be unnecessary.
  1791. //
  1792. // We also don't emit a definition for a function if it's going to be an
  1793. // entry in a vtable, unless it's already marked as used.
  1794. } else if (getLangOpts().CPlusPlus && D) {
  1795. // Look for a declaration that's lexically in a record.
  1796. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1797. FD = FD->getPreviousDecl()) {
  1798. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1799. if (FD->doesThisDeclarationHaveABody()) {
  1800. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1801. break;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807. // Make sure the result is of the requested type.
  1808. if (!IsIncompleteFunction) {
  1809. assert(F->getType()->getElementType() == Ty);
  1810. return F;
  1811. }
  1812. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1813. return llvm::ConstantExpr::getBitCast(F, PTy);
  1814. }
  1815. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1816. /// non-null, then this function will use the specified type if it has to
  1817. /// create it (this occurs when we see a definition of the function).
  1818. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1819. llvm::Type *Ty,
  1820. bool ForVTable,
  1821. bool DontDefer,
  1822. ForDefinition_t IsForDefinition) {
  1823. // If there was no specific requested type, just convert it now.
  1824. if (!Ty) {
  1825. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1826. auto CanonTy = Context.getCanonicalType(FD->getType());
  1827. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  1828. }
  1829. StringRef MangledName = getMangledName(GD);
  1830. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  1831. /*IsThunk=*/false, llvm::AttributeList(),
  1832. IsForDefinition);
  1833. }
  1834. static const FunctionDecl *
  1835. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  1836. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  1837. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  1838. IdentifierInfo &CII = C.Idents.get(Name);
  1839. for (const auto &Result : DC->lookup(&CII))
  1840. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  1841. return FD;
  1842. if (!C.getLangOpts().CPlusPlus)
  1843. return nullptr;
  1844. // Demangle the premangled name from getTerminateFn()
  1845. IdentifierInfo &CXXII =
  1846. (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
  1847. ? C.Idents.get("terminate")
  1848. : C.Idents.get(Name);
  1849. for (const auto &N : {"__cxxabiv1", "std"}) {
  1850. IdentifierInfo &NS = C.Idents.get(N);
  1851. for (const auto &Result : DC->lookup(&NS)) {
  1852. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  1853. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  1854. for (const auto &Result : LSD->lookup(&NS))
  1855. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  1856. break;
  1857. if (ND)
  1858. for (const auto &Result : ND->lookup(&CXXII))
  1859. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  1860. return FD;
  1861. }
  1862. }
  1863. return nullptr;
  1864. }
  1865. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1866. /// type and name.
  1867. llvm::Constant *
  1868. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  1869. llvm::AttributeList ExtraAttrs,
  1870. bool Local) {
  1871. llvm::Constant *C =
  1872. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1873. /*DontDefer=*/false, /*IsThunk=*/false,
  1874. ExtraAttrs);
  1875. if (auto *F = dyn_cast<llvm::Function>(C)) {
  1876. if (F->empty()) {
  1877. F->setCallingConv(getRuntimeCC());
  1878. if (!Local && getTriple().isOSBinFormatCOFF() &&
  1879. !getCodeGenOpts().LTOVisibilityPublicStd) {
  1880. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  1881. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  1882. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1883. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. return C;
  1889. }
  1890. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1891. /// type and name.
  1892. llvm::Constant *
  1893. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
  1894. llvm::AttributeList ExtraAttrs) {
  1895. llvm::Constant *C =
  1896. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1897. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1898. if (auto *F = dyn_cast<llvm::Function>(C))
  1899. if (F->empty())
  1900. F->setCallingConv(getBuiltinCC());
  1901. return C;
  1902. }
  1903. /// isTypeConstant - Determine whether an object of this type can be emitted
  1904. /// as a constant.
  1905. ///
  1906. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1907. /// will not be considered. The caller will need to verify that the object is
  1908. /// not written to during its construction.
  1909. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1910. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1911. return false;
  1912. if (Context.getLangOpts().CPlusPlus) {
  1913. if (const CXXRecordDecl *Record
  1914. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1915. return ExcludeCtor && !Record->hasMutableFields() &&
  1916. Record->hasTrivialDestructor();
  1917. }
  1918. return true;
  1919. }
  1920. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1921. /// create and return an llvm GlobalVariable with the specified type. If there
  1922. /// is something in the module with the specified name, return it potentially
  1923. /// bitcasted to the right type.
  1924. ///
  1925. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1926. /// to set the attributes on the global when it is first created.
  1927. ///
  1928. /// If IsForDefinition is true, it is guranteed that an actual global with
  1929. /// type Ty will be returned, not conversion of a variable with the same
  1930. /// mangled name but some other type.
  1931. llvm::Constant *
  1932. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1933. llvm::PointerType *Ty,
  1934. const VarDecl *D,
  1935. ForDefinition_t IsForDefinition) {
  1936. // Lookup the entry, lazily creating it if necessary.
  1937. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1938. if (Entry) {
  1939. if (WeakRefReferences.erase(Entry)) {
  1940. if (D && !D->hasAttr<WeakAttr>())
  1941. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1942. }
  1943. // Handle dropped DLL attributes.
  1944. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1945. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1946. if (Entry->getType() == Ty)
  1947. return Entry;
  1948. // If there are two attempts to define the same mangled name, issue an
  1949. // error.
  1950. if (IsForDefinition && !Entry->isDeclaration()) {
  1951. GlobalDecl OtherGD;
  1952. const VarDecl *OtherD;
  1953. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  1954. // to make sure that we issue an error only once.
  1955. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  1956. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  1957. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  1958. OtherD->hasInit() &&
  1959. DiagnosedConflictingDefinitions.insert(D).second) {
  1960. getDiags().Report(D->getLocation(),
  1961. diag::err_duplicate_mangled_name);
  1962. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1963. diag::note_previous_definition);
  1964. }
  1965. }
  1966. // Make sure the result is of the correct type.
  1967. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1968. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1969. // (If global is requested for a definition, we always need to create a new
  1970. // global, not just return a bitcast.)
  1971. if (!IsForDefinition)
  1972. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1973. }
  1974. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1975. auto *GV = new llvm::GlobalVariable(
  1976. getModule(), Ty->getElementType(), false,
  1977. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1978. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1979. // If we already created a global with the same mangled name (but different
  1980. // type) before, take its name and remove it from its parent.
  1981. if (Entry) {
  1982. GV->takeName(Entry);
  1983. if (!Entry->use_empty()) {
  1984. llvm::Constant *NewPtrForOldDecl =
  1985. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1986. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1987. }
  1988. Entry->eraseFromParent();
  1989. }
  1990. // This is the first use or definition of a mangled name. If there is a
  1991. // deferred decl with this name, remember that we need to emit it at the end
  1992. // of the file.
  1993. auto DDI = DeferredDecls.find(MangledName);
  1994. if (DDI != DeferredDecls.end()) {
  1995. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1996. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1997. addDeferredDeclToEmit(GV, DDI->second);
  1998. DeferredDecls.erase(DDI);
  1999. }
  2000. // Handle things which are present even on external declarations.
  2001. if (D) {
  2002. // FIXME: This code is overly simple and should be merged with other global
  2003. // handling.
  2004. GV->setConstant(isTypeConstant(D->getType(), false));
  2005. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2006. setLinkageAndVisibilityForGV(GV, D);
  2007. if (D->getTLSKind()) {
  2008. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2009. CXXThreadLocals.push_back(D);
  2010. setTLSMode(GV, *D);
  2011. }
  2012. // If required by the ABI, treat declarations of static data members with
  2013. // inline initializers as definitions.
  2014. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2015. EmitGlobalVarDefinition(D);
  2016. }
  2017. // Handle XCore specific ABI requirements.
  2018. if (getTriple().getArch() == llvm::Triple::xcore &&
  2019. D->getLanguageLinkage() == CLanguageLinkage &&
  2020. D->getType().isConstant(Context) &&
  2021. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2022. GV->setSection(".cp.rodata");
  2023. }
  2024. if (AddrSpace != Ty->getAddressSpace())
  2025. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  2026. return GV;
  2027. }
  2028. llvm::Constant *
  2029. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2030. ForDefinition_t IsForDefinition) {
  2031. const Decl *D = GD.getDecl();
  2032. if (isa<CXXConstructorDecl>(D))
  2033. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2034. getFromCtorType(GD.getCtorType()),
  2035. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2036. /*DontDefer=*/false, IsForDefinition);
  2037. else if (isa<CXXDestructorDecl>(D))
  2038. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2039. getFromDtorType(GD.getDtorType()),
  2040. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2041. /*DontDefer=*/false, IsForDefinition);
  2042. else if (isa<CXXMethodDecl>(D)) {
  2043. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2044. cast<CXXMethodDecl>(D));
  2045. auto Ty = getTypes().GetFunctionType(*FInfo);
  2046. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2047. IsForDefinition);
  2048. } else if (isa<FunctionDecl>(D)) {
  2049. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2050. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2051. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2052. IsForDefinition);
  2053. } else
  2054. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2055. IsForDefinition);
  2056. }
  2057. llvm::GlobalVariable *
  2058. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  2059. llvm::Type *Ty,
  2060. llvm::GlobalValue::LinkageTypes Linkage) {
  2061. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2062. llvm::GlobalVariable *OldGV = nullptr;
  2063. if (GV) {
  2064. // Check if the variable has the right type.
  2065. if (GV->getType()->getElementType() == Ty)
  2066. return GV;
  2067. // Because C++ name mangling, the only way we can end up with an already
  2068. // existing global with the same name is if it has been declared extern "C".
  2069. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2070. OldGV = GV;
  2071. }
  2072. // Create a new variable.
  2073. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2074. Linkage, nullptr, Name);
  2075. if (OldGV) {
  2076. // Replace occurrences of the old variable if needed.
  2077. GV->takeName(OldGV);
  2078. if (!OldGV->use_empty()) {
  2079. llvm::Constant *NewPtrForOldDecl =
  2080. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2081. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2082. }
  2083. OldGV->eraseFromParent();
  2084. }
  2085. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2086. !GV->hasAvailableExternallyLinkage())
  2087. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2088. return GV;
  2089. }
  2090. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2091. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2092. /// then it will be created with the specified type instead of whatever the
  2093. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  2094. /// that an actual global with type Ty will be returned, not conversion of a
  2095. /// variable with the same mangled name but some other type.
  2096. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2097. llvm::Type *Ty,
  2098. ForDefinition_t IsForDefinition) {
  2099. assert(D->hasGlobalStorage() && "Not a global variable");
  2100. QualType ASTTy = D->getType();
  2101. if (!Ty)
  2102. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2103. llvm::PointerType *PTy =
  2104. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2105. StringRef MangledName = getMangledName(D);
  2106. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2107. }
  2108. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2109. /// specified type and name.
  2110. llvm::Constant *
  2111. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2112. StringRef Name) {
  2113. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2114. }
  2115. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2116. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2117. StringRef MangledName = getMangledName(D);
  2118. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2119. // We already have a definition, not declaration, with the same mangled name.
  2120. // Emitting of declaration is not required (and actually overwrites emitted
  2121. // definition).
  2122. if (GV && !GV->isDeclaration())
  2123. return;
  2124. // If we have not seen a reference to this variable yet, place it into the
  2125. // deferred declarations table to be emitted if needed later.
  2126. if (!MustBeEmitted(D) && !GV) {
  2127. DeferredDecls[MangledName] = D;
  2128. return;
  2129. }
  2130. // The tentative definition is the only definition.
  2131. EmitGlobalVarDefinition(D);
  2132. }
  2133. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2134. return Context.toCharUnitsFromBits(
  2135. getDataLayout().getTypeStoreSizeInBits(Ty));
  2136. }
  2137. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  2138. unsigned AddrSpace) {
  2139. if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2140. if (D->hasAttr<CUDAConstantAttr>())
  2141. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  2142. else if (D->hasAttr<CUDASharedAttr>())
  2143. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  2144. else
  2145. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  2146. }
  2147. return AddrSpace;
  2148. }
  2149. template<typename SomeDecl>
  2150. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2151. llvm::GlobalValue *GV) {
  2152. if (!getLangOpts().CPlusPlus)
  2153. return;
  2154. // Must have 'used' attribute, or else inline assembly can't rely on
  2155. // the name existing.
  2156. if (!D->template hasAttr<UsedAttr>())
  2157. return;
  2158. // Must have internal linkage and an ordinary name.
  2159. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2160. return;
  2161. // Must be in an extern "C" context. Entities declared directly within
  2162. // a record are not extern "C" even if the record is in such a context.
  2163. const SomeDecl *First = D->getFirstDecl();
  2164. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2165. return;
  2166. // OK, this is an internal linkage entity inside an extern "C" linkage
  2167. // specification. Make a note of that so we can give it the "expected"
  2168. // mangled name if nothing else is using that name.
  2169. std::pair<StaticExternCMap::iterator, bool> R =
  2170. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2171. // If we have multiple internal linkage entities with the same name
  2172. // in extern "C" regions, none of them gets that name.
  2173. if (!R.second)
  2174. R.first->second = nullptr;
  2175. }
  2176. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2177. if (!CGM.supportsCOMDAT())
  2178. return false;
  2179. if (D.hasAttr<SelectAnyAttr>())
  2180. return true;
  2181. GVALinkage Linkage;
  2182. if (auto *VD = dyn_cast<VarDecl>(&D))
  2183. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2184. else
  2185. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2186. switch (Linkage) {
  2187. case GVA_Internal:
  2188. case GVA_AvailableExternally:
  2189. case GVA_StrongExternal:
  2190. return false;
  2191. case GVA_DiscardableODR:
  2192. case GVA_StrongODR:
  2193. return true;
  2194. }
  2195. llvm_unreachable("No such linkage");
  2196. }
  2197. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2198. llvm::GlobalObject &GO) {
  2199. if (!shouldBeInCOMDAT(*this, D))
  2200. return;
  2201. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2202. }
  2203. /// Pass IsTentative as true if you want to create a tentative definition.
  2204. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2205. bool IsTentative) {
  2206. // OpenCL global variables of sampler type are translated to function calls,
  2207. // therefore no need to be translated.
  2208. QualType ASTTy = D->getType();
  2209. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2210. return;
  2211. llvm::Constant *Init = nullptr;
  2212. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2213. bool NeedsGlobalCtor = false;
  2214. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2215. const VarDecl *InitDecl;
  2216. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2217. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2218. // as part of their declaration." Sema has already checked for
  2219. // error cases, so we just need to set Init to UndefValue.
  2220. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2221. D->hasAttr<CUDASharedAttr>())
  2222. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2223. else if (!InitExpr) {
  2224. // This is a tentative definition; tentative definitions are
  2225. // implicitly initialized with { 0 }.
  2226. //
  2227. // Note that tentative definitions are only emitted at the end of
  2228. // a translation unit, so they should never have incomplete
  2229. // type. In addition, EmitTentativeDefinition makes sure that we
  2230. // never attempt to emit a tentative definition if a real one
  2231. // exists. A use may still exists, however, so we still may need
  2232. // to do a RAUW.
  2233. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2234. Init = EmitNullConstant(D->getType());
  2235. } else {
  2236. initializedGlobalDecl = GlobalDecl(D);
  2237. Init = EmitConstantInit(*InitDecl);
  2238. if (!Init) {
  2239. QualType T = InitExpr->getType();
  2240. if (D->getType()->isReferenceType())
  2241. T = D->getType();
  2242. if (getLangOpts().CPlusPlus) {
  2243. Init = EmitNullConstant(T);
  2244. NeedsGlobalCtor = true;
  2245. } else {
  2246. ErrorUnsupported(D, "static initializer");
  2247. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2248. }
  2249. } else {
  2250. // We don't need an initializer, so remove the entry for the delayed
  2251. // initializer position (just in case this entry was delayed) if we
  2252. // also don't need to register a destructor.
  2253. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2254. DelayedCXXInitPosition.erase(D);
  2255. }
  2256. }
  2257. llvm::Type* InitType = Init->getType();
  2258. llvm::Constant *Entry =
  2259. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2260. // Strip off a bitcast if we got one back.
  2261. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2262. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2263. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2264. // All zero index gep.
  2265. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2266. Entry = CE->getOperand(0);
  2267. }
  2268. // Entry is now either a Function or GlobalVariable.
  2269. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2270. // We have a definition after a declaration with the wrong type.
  2271. // We must make a new GlobalVariable* and update everything that used OldGV
  2272. // (a declaration or tentative definition) with the new GlobalVariable*
  2273. // (which will be a definition).
  2274. //
  2275. // This happens if there is a prototype for a global (e.g.
  2276. // "extern int x[];") and then a definition of a different type (e.g.
  2277. // "int x[10];"). This also happens when an initializer has a different type
  2278. // from the type of the global (this happens with unions).
  2279. if (!GV ||
  2280. GV->getType()->getElementType() != InitType ||
  2281. GV->getType()->getAddressSpace() !=
  2282. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  2283. // Move the old entry aside so that we'll create a new one.
  2284. Entry->setName(StringRef());
  2285. // Make a new global with the correct type, this is now guaranteed to work.
  2286. GV = cast<llvm::GlobalVariable>(
  2287. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2288. // Replace all uses of the old global with the new global
  2289. llvm::Constant *NewPtrForOldDecl =
  2290. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2291. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2292. // Erase the old global, since it is no longer used.
  2293. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2294. }
  2295. MaybeHandleStaticInExternC(D, GV);
  2296. if (D->hasAttr<AnnotateAttr>())
  2297. AddGlobalAnnotations(D, GV);
  2298. // Set the llvm linkage type as appropriate.
  2299. llvm::GlobalValue::LinkageTypes Linkage =
  2300. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2301. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2302. // the device. [...]"
  2303. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2304. // __device__, declares a variable that: [...]
  2305. // Is accessible from all the threads within the grid and from the host
  2306. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2307. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2308. if (GV && LangOpts.CUDA) {
  2309. if (LangOpts.CUDAIsDevice) {
  2310. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2311. GV->setExternallyInitialized(true);
  2312. } else {
  2313. // Host-side shadows of external declarations of device-side
  2314. // global variables become internal definitions. These have to
  2315. // be internal in order to prevent name conflicts with global
  2316. // host variables with the same name in a different TUs.
  2317. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2318. Linkage = llvm::GlobalValue::InternalLinkage;
  2319. // Shadow variables and their properties must be registered
  2320. // with CUDA runtime.
  2321. unsigned Flags = 0;
  2322. if (!D->hasDefinition())
  2323. Flags |= CGCUDARuntime::ExternDeviceVar;
  2324. if (D->hasAttr<CUDAConstantAttr>())
  2325. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2326. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2327. } else if (D->hasAttr<CUDASharedAttr>())
  2328. // __shared__ variables are odd. Shadows do get created, but
  2329. // they are not registered with the CUDA runtime, so they
  2330. // can't really be used to access their device-side
  2331. // counterparts. It's not clear yet whether it's nvcc's bug or
  2332. // a feature, but we've got to do the same for compatibility.
  2333. Linkage = llvm::GlobalValue::InternalLinkage;
  2334. }
  2335. }
  2336. GV->setInitializer(Init);
  2337. // If it is safe to mark the global 'constant', do so now.
  2338. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2339. isTypeConstant(D->getType(), true));
  2340. // If it is in a read-only section, mark it 'constant'.
  2341. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2342. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2343. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2344. GV->setConstant(true);
  2345. }
  2346. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2347. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2348. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2349. // copies within a linkage unit; otherwise, the backing variable has
  2350. // internal linkage and all accesses should just be calls to the
  2351. // Itanium-specified entry point, which has the normal linkage of the
  2352. // variable. This is to preserve the ability to change the implementation
  2353. // behind the scenes.
  2354. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2355. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2356. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2357. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2358. Linkage = llvm::GlobalValue::InternalLinkage;
  2359. GV->setLinkage(Linkage);
  2360. if (D->hasAttr<DLLImportAttr>())
  2361. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2362. else if (D->hasAttr<DLLExportAttr>())
  2363. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2364. else
  2365. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2366. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  2367. // common vars aren't constant even if declared const.
  2368. GV->setConstant(false);
  2369. // Tentative definition of global variables may be initialized with
  2370. // non-zero null pointers. In this case they should have weak linkage
  2371. // since common linkage must have zero initializer and must not have
  2372. // explicit section therefore cannot have non-zero initial value.
  2373. if (!GV->getInitializer()->isNullValue())
  2374. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  2375. }
  2376. setNonAliasAttributes(D, GV);
  2377. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2378. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2379. CXXThreadLocals.push_back(D);
  2380. setTLSMode(GV, *D);
  2381. }
  2382. maybeSetTrivialComdat(*D, *GV);
  2383. // Emit the initializer function if necessary.
  2384. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2385. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2386. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2387. // Emit global variable debug information.
  2388. if (CGDebugInfo *DI = getModuleDebugInfo())
  2389. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2390. DI->EmitGlobalVariable(GV, D);
  2391. }
  2392. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2393. CodeGenModule &CGM, const VarDecl *D,
  2394. bool NoCommon) {
  2395. // Don't give variables common linkage if -fno-common was specified unless it
  2396. // was overridden by a NoCommon attribute.
  2397. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2398. return true;
  2399. // C11 6.9.2/2:
  2400. // A declaration of an identifier for an object that has file scope without
  2401. // an initializer, and without a storage-class specifier or with the
  2402. // storage-class specifier static, constitutes a tentative definition.
  2403. if (D->getInit() || D->hasExternalStorage())
  2404. return true;
  2405. // A variable cannot be both common and exist in a section.
  2406. if (D->hasAttr<SectionAttr>())
  2407. return true;
  2408. // Thread local vars aren't considered common linkage.
  2409. if (D->getTLSKind())
  2410. return true;
  2411. // Tentative definitions marked with WeakImportAttr are true definitions.
  2412. if (D->hasAttr<WeakImportAttr>())
  2413. return true;
  2414. // A variable cannot be both common and exist in a comdat.
  2415. if (shouldBeInCOMDAT(CGM, *D))
  2416. return true;
  2417. // Declarations with a required alignment do not have common linkage in MSVC
  2418. // mode.
  2419. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2420. if (D->hasAttr<AlignedAttr>())
  2421. return true;
  2422. QualType VarType = D->getType();
  2423. if (Context.isAlignmentRequired(VarType))
  2424. return true;
  2425. if (const auto *RT = VarType->getAs<RecordType>()) {
  2426. const RecordDecl *RD = RT->getDecl();
  2427. for (const FieldDecl *FD : RD->fields()) {
  2428. if (FD->isBitField())
  2429. continue;
  2430. if (FD->hasAttr<AlignedAttr>())
  2431. return true;
  2432. if (Context.isAlignmentRequired(FD->getType()))
  2433. return true;
  2434. }
  2435. }
  2436. }
  2437. return false;
  2438. }
  2439. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2440. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2441. if (Linkage == GVA_Internal)
  2442. return llvm::Function::InternalLinkage;
  2443. if (D->hasAttr<WeakAttr>()) {
  2444. if (IsConstantVariable)
  2445. return llvm::GlobalVariable::WeakODRLinkage;
  2446. else
  2447. return llvm::GlobalVariable::WeakAnyLinkage;
  2448. }
  2449. // We are guaranteed to have a strong definition somewhere else,
  2450. // so we can use available_externally linkage.
  2451. if (Linkage == GVA_AvailableExternally)
  2452. return llvm::GlobalValue::AvailableExternallyLinkage;
  2453. // Note that Apple's kernel linker doesn't support symbol
  2454. // coalescing, so we need to avoid linkonce and weak linkages there.
  2455. // Normally, this means we just map to internal, but for explicit
  2456. // instantiations we'll map to external.
  2457. // In C++, the compiler has to emit a definition in every translation unit
  2458. // that references the function. We should use linkonce_odr because
  2459. // a) if all references in this translation unit are optimized away, we
  2460. // don't need to codegen it. b) if the function persists, it needs to be
  2461. // merged with other definitions. c) C++ has the ODR, so we know the
  2462. // definition is dependable.
  2463. if (Linkage == GVA_DiscardableODR)
  2464. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2465. : llvm::Function::InternalLinkage;
  2466. // An explicit instantiation of a template has weak linkage, since
  2467. // explicit instantiations can occur in multiple translation units
  2468. // and must all be equivalent. However, we are not allowed to
  2469. // throw away these explicit instantiations.
  2470. //
  2471. // We don't currently support CUDA device code spread out across multiple TUs,
  2472. // so say that CUDA templates are either external (for kernels) or internal.
  2473. // This lets llvm perform aggressive inter-procedural optimizations.
  2474. if (Linkage == GVA_StrongODR) {
  2475. if (Context.getLangOpts().AppleKext)
  2476. return llvm::Function::ExternalLinkage;
  2477. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2478. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2479. : llvm::Function::InternalLinkage;
  2480. return llvm::Function::WeakODRLinkage;
  2481. }
  2482. // C++ doesn't have tentative definitions and thus cannot have common
  2483. // linkage.
  2484. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2485. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2486. CodeGenOpts.NoCommon))
  2487. return llvm::GlobalVariable::CommonLinkage;
  2488. // selectany symbols are externally visible, so use weak instead of
  2489. // linkonce. MSVC optimizes away references to const selectany globals, so
  2490. // all definitions should be the same and ODR linkage should be used.
  2491. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2492. if (D->hasAttr<SelectAnyAttr>())
  2493. return llvm::GlobalVariable::WeakODRLinkage;
  2494. // Otherwise, we have strong external linkage.
  2495. assert(Linkage == GVA_StrongExternal);
  2496. return llvm::GlobalVariable::ExternalLinkage;
  2497. }
  2498. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2499. const VarDecl *VD, bool IsConstant) {
  2500. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2501. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2502. }
  2503. /// Replace the uses of a function that was declared with a non-proto type.
  2504. /// We want to silently drop extra arguments from call sites
  2505. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2506. llvm::Function *newFn) {
  2507. // Fast path.
  2508. if (old->use_empty()) return;
  2509. llvm::Type *newRetTy = newFn->getReturnType();
  2510. SmallVector<llvm::Value*, 4> newArgs;
  2511. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2512. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2513. ui != ue; ) {
  2514. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2515. llvm::User *user = use->getUser();
  2516. // Recognize and replace uses of bitcasts. Most calls to
  2517. // unprototyped functions will use bitcasts.
  2518. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2519. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2520. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2521. continue;
  2522. }
  2523. // Recognize calls to the function.
  2524. llvm::CallSite callSite(user);
  2525. if (!callSite) continue;
  2526. if (!callSite.isCallee(&*use)) continue;
  2527. // If the return types don't match exactly, then we can't
  2528. // transform this call unless it's dead.
  2529. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2530. continue;
  2531. // Get the call site's attribute list.
  2532. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  2533. llvm::AttributeList oldAttrs = callSite.getAttributes();
  2534. // If the function was passed too few arguments, don't transform.
  2535. unsigned newNumArgs = newFn->arg_size();
  2536. if (callSite.arg_size() < newNumArgs) continue;
  2537. // If extra arguments were passed, we silently drop them.
  2538. // If any of the types mismatch, we don't transform.
  2539. unsigned argNo = 0;
  2540. bool dontTransform = false;
  2541. for (llvm::Argument &A : newFn->args()) {
  2542. if (callSite.getArgument(argNo)->getType() != A.getType()) {
  2543. dontTransform = true;
  2544. break;
  2545. }
  2546. // Add any parameter attributes.
  2547. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  2548. argNo++;
  2549. }
  2550. if (dontTransform)
  2551. continue;
  2552. // Okay, we can transform this. Create the new call instruction and copy
  2553. // over the required information.
  2554. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2555. // Copy over any operand bundles.
  2556. callSite.getOperandBundlesAsDefs(newBundles);
  2557. llvm::CallSite newCall;
  2558. if (callSite.isCall()) {
  2559. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  2560. callSite.getInstruction());
  2561. } else {
  2562. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2563. newCall = llvm::InvokeInst::Create(newFn,
  2564. oldInvoke->getNormalDest(),
  2565. oldInvoke->getUnwindDest(),
  2566. newArgs, newBundles, "",
  2567. callSite.getInstruction());
  2568. }
  2569. newArgs.clear(); // for the next iteration
  2570. if (!newCall->getType()->isVoidTy())
  2571. newCall->takeName(callSite.getInstruction());
  2572. newCall.setAttributes(llvm::AttributeList::get(
  2573. newFn->getContext(), oldAttrs.getFnAttributes(),
  2574. oldAttrs.getRetAttributes(), newArgAttrs));
  2575. newCall.setCallingConv(callSite.getCallingConv());
  2576. // Finally, remove the old call, replacing any uses with the new one.
  2577. if (!callSite->use_empty())
  2578. callSite->replaceAllUsesWith(newCall.getInstruction());
  2579. // Copy debug location attached to CI.
  2580. if (callSite->getDebugLoc())
  2581. newCall->setDebugLoc(callSite->getDebugLoc());
  2582. callSite->eraseFromParent();
  2583. }
  2584. }
  2585. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2586. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2587. /// existing call uses of the old function in the module, this adjusts them to
  2588. /// call the new function directly.
  2589. ///
  2590. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2591. /// functions to be able to inline them. If there is a bitcast in the way, it
  2592. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2593. /// run at -O0.
  2594. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2595. llvm::Function *NewFn) {
  2596. // If we're redefining a global as a function, don't transform it.
  2597. if (!isa<llvm::Function>(Old)) return;
  2598. replaceUsesOfNonProtoConstant(Old, NewFn);
  2599. }
  2600. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2601. auto DK = VD->isThisDeclarationADefinition();
  2602. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  2603. return;
  2604. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2605. // If we have a definition, this might be a deferred decl. If the
  2606. // instantiation is explicit, make sure we emit it at the end.
  2607. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2608. GetAddrOfGlobalVar(VD);
  2609. EmitTopLevelDecl(VD);
  2610. }
  2611. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2612. llvm::GlobalValue *GV) {
  2613. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2614. // Compute the function info and LLVM type.
  2615. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2616. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2617. // Get or create the prototype for the function.
  2618. if (!GV || (GV->getType()->getElementType() != Ty))
  2619. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  2620. /*DontDefer=*/true,
  2621. ForDefinition));
  2622. // Already emitted.
  2623. if (!GV->isDeclaration())
  2624. return;
  2625. // We need to set linkage and visibility on the function before
  2626. // generating code for it because various parts of IR generation
  2627. // want to propagate this information down (e.g. to local static
  2628. // declarations).
  2629. auto *Fn = cast<llvm::Function>(GV);
  2630. setFunctionLinkage(GD, Fn);
  2631. setFunctionDLLStorageClass(GD, Fn);
  2632. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2633. setGlobalVisibility(Fn, D);
  2634. MaybeHandleStaticInExternC(D, Fn);
  2635. maybeSetTrivialComdat(*D, *Fn);
  2636. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2637. setFunctionDefinitionAttributes(D, Fn);
  2638. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2639. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2640. AddGlobalCtor(Fn, CA->getPriority());
  2641. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2642. AddGlobalDtor(Fn, DA->getPriority());
  2643. if (D->hasAttr<AnnotateAttr>())
  2644. AddGlobalAnnotations(D, Fn);
  2645. }
  2646. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2647. const auto *D = cast<ValueDecl>(GD.getDecl());
  2648. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2649. assert(AA && "Not an alias?");
  2650. StringRef MangledName = getMangledName(GD);
  2651. if (AA->getAliasee() == MangledName) {
  2652. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2653. return;
  2654. }
  2655. // If there is a definition in the module, then it wins over the alias.
  2656. // This is dubious, but allow it to be safe. Just ignore the alias.
  2657. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2658. if (Entry && !Entry->isDeclaration())
  2659. return;
  2660. Aliases.push_back(GD);
  2661. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2662. // Create a reference to the named value. This ensures that it is emitted
  2663. // if a deferred decl.
  2664. llvm::Constant *Aliasee;
  2665. if (isa<llvm::FunctionType>(DeclTy))
  2666. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2667. /*ForVTable=*/false);
  2668. else
  2669. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2670. llvm::PointerType::getUnqual(DeclTy),
  2671. /*D=*/nullptr);
  2672. // Create the new alias itself, but don't set a name yet.
  2673. auto *GA = llvm::GlobalAlias::create(
  2674. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2675. if (Entry) {
  2676. if (GA->getAliasee() == Entry) {
  2677. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2678. return;
  2679. }
  2680. assert(Entry->isDeclaration());
  2681. // If there is a declaration in the module, then we had an extern followed
  2682. // by the alias, as in:
  2683. // extern int test6();
  2684. // ...
  2685. // int test6() __attribute__((alias("test7")));
  2686. //
  2687. // Remove it and replace uses of it with the alias.
  2688. GA->takeName(Entry);
  2689. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2690. Entry->getType()));
  2691. Entry->eraseFromParent();
  2692. } else {
  2693. GA->setName(MangledName);
  2694. }
  2695. // Set attributes which are particular to an alias; this is a
  2696. // specialization of the attributes which may be set on a global
  2697. // variable/function.
  2698. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2699. D->isWeakImported()) {
  2700. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2701. }
  2702. if (const auto *VD = dyn_cast<VarDecl>(D))
  2703. if (VD->getTLSKind())
  2704. setTLSMode(GA, *VD);
  2705. setAliasAttributes(D, GA);
  2706. }
  2707. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  2708. const auto *D = cast<ValueDecl>(GD.getDecl());
  2709. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  2710. assert(IFA && "Not an ifunc?");
  2711. StringRef MangledName = getMangledName(GD);
  2712. if (IFA->getResolver() == MangledName) {
  2713. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2714. return;
  2715. }
  2716. // Report an error if some definition overrides ifunc.
  2717. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2718. if (Entry && !Entry->isDeclaration()) {
  2719. GlobalDecl OtherGD;
  2720. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2721. DiagnosedConflictingDefinitions.insert(GD).second) {
  2722. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2723. Diags.Report(OtherGD.getDecl()->getLocation(),
  2724. diag::note_previous_definition);
  2725. }
  2726. return;
  2727. }
  2728. Aliases.push_back(GD);
  2729. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2730. llvm::Constant *Resolver =
  2731. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  2732. /*ForVTable=*/false);
  2733. llvm::GlobalIFunc *GIF =
  2734. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  2735. "", Resolver, &getModule());
  2736. if (Entry) {
  2737. if (GIF->getResolver() == Entry) {
  2738. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2739. return;
  2740. }
  2741. assert(Entry->isDeclaration());
  2742. // If there is a declaration in the module, then we had an extern followed
  2743. // by the ifunc, as in:
  2744. // extern int test();
  2745. // ...
  2746. // int test() __attribute__((ifunc("resolver")));
  2747. //
  2748. // Remove it and replace uses of it with the ifunc.
  2749. GIF->takeName(Entry);
  2750. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  2751. Entry->getType()));
  2752. Entry->eraseFromParent();
  2753. } else
  2754. GIF->setName(MangledName);
  2755. SetCommonAttributes(D, GIF);
  2756. }
  2757. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2758. ArrayRef<llvm::Type*> Tys) {
  2759. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2760. Tys);
  2761. }
  2762. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2763. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2764. const StringLiteral *Literal, bool TargetIsLSB,
  2765. bool &IsUTF16, unsigned &StringLength) {
  2766. StringRef String = Literal->getString();
  2767. unsigned NumBytes = String.size();
  2768. // Check for simple case.
  2769. if (!Literal->containsNonAsciiOrNull()) {
  2770. StringLength = NumBytes;
  2771. return *Map.insert(std::make_pair(String, nullptr)).first;
  2772. }
  2773. // Otherwise, convert the UTF8 literals into a string of shorts.
  2774. IsUTF16 = true;
  2775. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2776. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  2777. llvm::UTF16 *ToPtr = &ToBuf[0];
  2778. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  2779. ToPtr + NumBytes, llvm::strictConversion);
  2780. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2781. StringLength = ToPtr - &ToBuf[0];
  2782. // Add an explicit null.
  2783. *ToPtr = 0;
  2784. return *Map.insert(std::make_pair(
  2785. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2786. (StringLength + 1) * 2),
  2787. nullptr)).first;
  2788. }
  2789. ConstantAddress
  2790. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2791. unsigned StringLength = 0;
  2792. bool isUTF16 = false;
  2793. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2794. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2795. getDataLayout().isLittleEndian(), isUTF16,
  2796. StringLength);
  2797. if (auto *C = Entry.second)
  2798. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  2799. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2800. llvm::Constant *Zeros[] = { Zero, Zero };
  2801. // If we don't already have it, get __CFConstantStringClassReference.
  2802. if (!CFConstantStringClassRef) {
  2803. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2804. Ty = llvm::ArrayType::get(Ty, 0);
  2805. llvm::Constant *GV =
  2806. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  2807. if (getTriple().isOSBinFormatCOFF()) {
  2808. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  2809. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  2810. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2811. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  2812. const VarDecl *VD = nullptr;
  2813. for (const auto &Result : DC->lookup(&II))
  2814. if ((VD = dyn_cast<VarDecl>(Result)))
  2815. break;
  2816. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  2817. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2818. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2819. } else {
  2820. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2821. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2822. }
  2823. }
  2824. // Decay array -> ptr
  2825. CFConstantStringClassRef =
  2826. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2827. }
  2828. QualType CFTy = getContext().getCFConstantStringType();
  2829. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2830. ConstantInitBuilder Builder(*this);
  2831. auto Fields = Builder.beginStruct(STy);
  2832. // Class pointer.
  2833. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  2834. // Flags.
  2835. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  2836. // String pointer.
  2837. llvm::Constant *C = nullptr;
  2838. if (isUTF16) {
  2839. auto Arr = llvm::makeArrayRef(
  2840. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2841. Entry.first().size() / 2);
  2842. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2843. } else {
  2844. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2845. }
  2846. // Note: -fwritable-strings doesn't make the backing store strings of
  2847. // CFStrings writable. (See <rdar://problem/10657500>)
  2848. auto *GV =
  2849. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2850. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2851. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2852. // Don't enforce the target's minimum global alignment, since the only use
  2853. // of the string is via this class initializer.
  2854. CharUnits Align = isUTF16
  2855. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  2856. : getContext().getTypeAlignInChars(getContext().CharTy);
  2857. GV->setAlignment(Align.getQuantity());
  2858. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  2859. // Without it LLVM can merge the string with a non unnamed_addr one during
  2860. // LTO. Doing that changes the section it ends in, which surprises ld64.
  2861. if (getTriple().isOSBinFormatMachO())
  2862. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  2863. : "__TEXT,__cstring,cstring_literals");
  2864. // String.
  2865. llvm::Constant *Str =
  2866. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2867. if (isUTF16)
  2868. // Cast the UTF16 string to the correct type.
  2869. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  2870. Fields.add(Str);
  2871. // String length.
  2872. auto Ty = getTypes().ConvertType(getContext().LongTy);
  2873. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  2874. CharUnits Alignment = getPointerAlign();
  2875. // The struct.
  2876. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  2877. /*isConstant=*/false,
  2878. llvm::GlobalVariable::PrivateLinkage);
  2879. switch (getTriple().getObjectFormat()) {
  2880. case llvm::Triple::UnknownObjectFormat:
  2881. llvm_unreachable("unknown file format");
  2882. case llvm::Triple::COFF:
  2883. case llvm::Triple::ELF:
  2884. case llvm::Triple::Wasm:
  2885. GV->setSection("cfstring");
  2886. break;
  2887. case llvm::Triple::MachO:
  2888. GV->setSection("__DATA,__cfstring");
  2889. break;
  2890. }
  2891. Entry.second = GV;
  2892. return ConstantAddress(GV, Alignment);
  2893. }
  2894. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2895. if (ObjCFastEnumerationStateType.isNull()) {
  2896. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2897. D->startDefinition();
  2898. QualType FieldTypes[] = {
  2899. Context.UnsignedLongTy,
  2900. Context.getPointerType(Context.getObjCIdType()),
  2901. Context.getPointerType(Context.UnsignedLongTy),
  2902. Context.getConstantArrayType(Context.UnsignedLongTy,
  2903. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2904. };
  2905. for (size_t i = 0; i < 4; ++i) {
  2906. FieldDecl *Field = FieldDecl::Create(Context,
  2907. D,
  2908. SourceLocation(),
  2909. SourceLocation(), nullptr,
  2910. FieldTypes[i], /*TInfo=*/nullptr,
  2911. /*BitWidth=*/nullptr,
  2912. /*Mutable=*/false,
  2913. ICIS_NoInit);
  2914. Field->setAccess(AS_public);
  2915. D->addDecl(Field);
  2916. }
  2917. D->completeDefinition();
  2918. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2919. }
  2920. return ObjCFastEnumerationStateType;
  2921. }
  2922. llvm::Constant *
  2923. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2924. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2925. // Don't emit it as the address of the string, emit the string data itself
  2926. // as an inline array.
  2927. if (E->getCharByteWidth() == 1) {
  2928. SmallString<64> Str(E->getString());
  2929. // Resize the string to the right size, which is indicated by its type.
  2930. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2931. Str.resize(CAT->getSize().getZExtValue());
  2932. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2933. }
  2934. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2935. llvm::Type *ElemTy = AType->getElementType();
  2936. unsigned NumElements = AType->getNumElements();
  2937. // Wide strings have either 2-byte or 4-byte elements.
  2938. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2939. SmallVector<uint16_t, 32> Elements;
  2940. Elements.reserve(NumElements);
  2941. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2942. Elements.push_back(E->getCodeUnit(i));
  2943. Elements.resize(NumElements);
  2944. return llvm::ConstantDataArray::get(VMContext, Elements);
  2945. }
  2946. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2947. SmallVector<uint32_t, 32> Elements;
  2948. Elements.reserve(NumElements);
  2949. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2950. Elements.push_back(E->getCodeUnit(i));
  2951. Elements.resize(NumElements);
  2952. return llvm::ConstantDataArray::get(VMContext, Elements);
  2953. }
  2954. static llvm::GlobalVariable *
  2955. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2956. CodeGenModule &CGM, StringRef GlobalName,
  2957. CharUnits Alignment) {
  2958. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2959. unsigned AddrSpace = 0;
  2960. if (CGM.getLangOpts().OpenCL)
  2961. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2962. llvm::Module &M = CGM.getModule();
  2963. // Create a global variable for this string
  2964. auto *GV = new llvm::GlobalVariable(
  2965. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2966. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2967. GV->setAlignment(Alignment.getQuantity());
  2968. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2969. if (GV->isWeakForLinker()) {
  2970. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2971. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2972. }
  2973. return GV;
  2974. }
  2975. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2976. /// constant array for the given string literal.
  2977. ConstantAddress
  2978. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2979. StringRef Name) {
  2980. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  2981. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2982. llvm::GlobalVariable **Entry = nullptr;
  2983. if (!LangOpts.WritableStrings) {
  2984. Entry = &ConstantStringMap[C];
  2985. if (auto GV = *Entry) {
  2986. if (Alignment.getQuantity() > GV->getAlignment())
  2987. GV->setAlignment(Alignment.getQuantity());
  2988. return ConstantAddress(GV, Alignment);
  2989. }
  2990. }
  2991. SmallString<256> MangledNameBuffer;
  2992. StringRef GlobalVariableName;
  2993. llvm::GlobalValue::LinkageTypes LT;
  2994. // Mangle the string literal if the ABI allows for it. However, we cannot
  2995. // do this if we are compiling with ASan or -fwritable-strings because they
  2996. // rely on strings having normal linkage.
  2997. if (!LangOpts.WritableStrings &&
  2998. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2999. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  3000. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3001. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3002. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3003. GlobalVariableName = MangledNameBuffer;
  3004. } else {
  3005. LT = llvm::GlobalValue::PrivateLinkage;
  3006. GlobalVariableName = Name;
  3007. }
  3008. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3009. if (Entry)
  3010. *Entry = GV;
  3011. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3012. QualType());
  3013. return ConstantAddress(GV, Alignment);
  3014. }
  3015. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3016. /// array for the given ObjCEncodeExpr node.
  3017. ConstantAddress
  3018. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3019. std::string Str;
  3020. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3021. return GetAddrOfConstantCString(Str);
  3022. }
  3023. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3024. /// the literal and a terminating '\0' character.
  3025. /// The result has pointer to array type.
  3026. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3027. const std::string &Str, const char *GlobalName) {
  3028. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3029. CharUnits Alignment =
  3030. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3031. llvm::Constant *C =
  3032. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3033. // Don't share any string literals if strings aren't constant.
  3034. llvm::GlobalVariable **Entry = nullptr;
  3035. if (!LangOpts.WritableStrings) {
  3036. Entry = &ConstantStringMap[C];
  3037. if (auto GV = *Entry) {
  3038. if (Alignment.getQuantity() > GV->getAlignment())
  3039. GV->setAlignment(Alignment.getQuantity());
  3040. return ConstantAddress(GV, Alignment);
  3041. }
  3042. }
  3043. // Get the default prefix if a name wasn't specified.
  3044. if (!GlobalName)
  3045. GlobalName = ".str";
  3046. // Create a global variable for this.
  3047. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3048. GlobalName, Alignment);
  3049. if (Entry)
  3050. *Entry = GV;
  3051. return ConstantAddress(GV, Alignment);
  3052. }
  3053. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3054. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3055. assert((E->getStorageDuration() == SD_Static ||
  3056. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3057. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3058. // If we're not materializing a subobject of the temporary, keep the
  3059. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3060. QualType MaterializedType = Init->getType();
  3061. if (Init == E->GetTemporaryExpr())
  3062. MaterializedType = E->getType();
  3063. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3064. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3065. return ConstantAddress(Slot, Align);
  3066. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3067. // we need to give each temporary the same name in every translation unit (and
  3068. // we also need to make the temporaries externally-visible).
  3069. SmallString<256> Name;
  3070. llvm::raw_svector_ostream Out(Name);
  3071. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3072. VD, E->getManglingNumber(), Out);
  3073. APValue *Value = nullptr;
  3074. if (E->getStorageDuration() == SD_Static) {
  3075. // We might have a cached constant initializer for this temporary. Note
  3076. // that this might have a different value from the value computed by
  3077. // evaluating the initializer if the surrounding constant expression
  3078. // modifies the temporary.
  3079. Value = getContext().getMaterializedTemporaryValue(E, false);
  3080. if (Value && Value->isUninit())
  3081. Value = nullptr;
  3082. }
  3083. // Try evaluating it now, it might have a constant initializer.
  3084. Expr::EvalResult EvalResult;
  3085. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3086. !EvalResult.hasSideEffects())
  3087. Value = &EvalResult.Val;
  3088. llvm::Constant *InitialValue = nullptr;
  3089. bool Constant = false;
  3090. llvm::Type *Type;
  3091. if (Value) {
  3092. // The temporary has a constant initializer, use it.
  3093. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  3094. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3095. Type = InitialValue->getType();
  3096. } else {
  3097. // No initializer, the initialization will be provided when we
  3098. // initialize the declaration which performed lifetime extension.
  3099. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3100. }
  3101. // Create a global variable for this lifetime-extended temporary.
  3102. llvm::GlobalValue::LinkageTypes Linkage =
  3103. getLLVMLinkageVarDefinition(VD, Constant);
  3104. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3105. const VarDecl *InitVD;
  3106. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3107. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3108. // Temporaries defined inside a class get linkonce_odr linkage because the
  3109. // class can be defined in multipe translation units.
  3110. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3111. } else {
  3112. // There is no need for this temporary to have external linkage if the
  3113. // VarDecl has external linkage.
  3114. Linkage = llvm::GlobalVariable::InternalLinkage;
  3115. }
  3116. }
  3117. unsigned AddrSpace = GetGlobalVarAddressSpace(
  3118. VD, getContext().getTargetAddressSpace(MaterializedType));
  3119. auto *GV = new llvm::GlobalVariable(
  3120. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3121. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  3122. AddrSpace);
  3123. setGlobalVisibility(GV, VD);
  3124. GV->setAlignment(Align.getQuantity());
  3125. if (supportsCOMDAT() && GV->isWeakForLinker())
  3126. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3127. if (VD->getTLSKind())
  3128. setTLSMode(GV, *VD);
  3129. MaterializedGlobalTemporaryMap[E] = GV;
  3130. return ConstantAddress(GV, Align);
  3131. }
  3132. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3133. /// properties for an implementation.
  3134. void CodeGenModule::EmitObjCPropertyImplementations(const
  3135. ObjCImplementationDecl *D) {
  3136. for (const auto *PID : D->property_impls()) {
  3137. // Dynamic is just for type-checking.
  3138. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3139. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3140. // Determine which methods need to be implemented, some may have
  3141. // been overridden. Note that ::isPropertyAccessor is not the method
  3142. // we want, that just indicates if the decl came from a
  3143. // property. What we want to know is if the method is defined in
  3144. // this implementation.
  3145. if (!D->getInstanceMethod(PD->getGetterName()))
  3146. CodeGenFunction(*this).GenerateObjCGetter(
  3147. const_cast<ObjCImplementationDecl *>(D), PID);
  3148. if (!PD->isReadOnly() &&
  3149. !D->getInstanceMethod(PD->getSetterName()))
  3150. CodeGenFunction(*this).GenerateObjCSetter(
  3151. const_cast<ObjCImplementationDecl *>(D), PID);
  3152. }
  3153. }
  3154. }
  3155. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3156. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3157. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3158. ivar; ivar = ivar->getNextIvar())
  3159. if (ivar->getType().isDestructedType())
  3160. return true;
  3161. return false;
  3162. }
  3163. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3164. ObjCImplementationDecl *D) {
  3165. CodeGenFunction CGF(CGM);
  3166. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3167. E = D->init_end(); B != E; ++B) {
  3168. CXXCtorInitializer *CtorInitExp = *B;
  3169. Expr *Init = CtorInitExp->getInit();
  3170. if (!CGF.isTrivialInitializer(Init))
  3171. return false;
  3172. }
  3173. return true;
  3174. }
  3175. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3176. /// for an implementation.
  3177. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3178. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3179. if (needsDestructMethod(D)) {
  3180. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3181. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3182. ObjCMethodDecl *DTORMethod =
  3183. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3184. cxxSelector, getContext().VoidTy, nullptr, D,
  3185. /*isInstance=*/true, /*isVariadic=*/false,
  3186. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3187. /*isDefined=*/false, ObjCMethodDecl::Required);
  3188. D->addInstanceMethod(DTORMethod);
  3189. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3190. D->setHasDestructors(true);
  3191. }
  3192. // If the implementation doesn't have any ivar initializers, we don't need
  3193. // a .cxx_construct.
  3194. if (D->getNumIvarInitializers() == 0 ||
  3195. AllTrivialInitializers(*this, D))
  3196. return;
  3197. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3198. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3199. // The constructor returns 'self'.
  3200. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3201. D->getLocation(),
  3202. D->getLocation(),
  3203. cxxSelector,
  3204. getContext().getObjCIdType(),
  3205. nullptr, D, /*isInstance=*/true,
  3206. /*isVariadic=*/false,
  3207. /*isPropertyAccessor=*/true,
  3208. /*isImplicitlyDeclared=*/true,
  3209. /*isDefined=*/false,
  3210. ObjCMethodDecl::Required);
  3211. D->addInstanceMethod(CTORMethod);
  3212. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3213. D->setHasNonZeroConstructors(true);
  3214. }
  3215. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3216. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3217. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3218. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3219. ErrorUnsupported(LSD, "linkage spec");
  3220. return;
  3221. }
  3222. EmitDeclContext(LSD);
  3223. }
  3224. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3225. for (auto *I : DC->decls()) {
  3226. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3227. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3228. // ObjCImplDecl does not recursively visit them. We need to do that in
  3229. // case they're nested inside another construct (LinkageSpecDecl /
  3230. // ExportDecl) that does stop them from being considered "top-level".
  3231. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3232. for (auto *M : OID->methods())
  3233. EmitTopLevelDecl(M);
  3234. }
  3235. EmitTopLevelDecl(I);
  3236. }
  3237. }
  3238. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3239. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3240. // Ignore dependent declarations.
  3241. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  3242. return;
  3243. switch (D->getKind()) {
  3244. case Decl::CXXConversion:
  3245. case Decl::CXXMethod:
  3246. case Decl::Function:
  3247. // Skip function templates
  3248. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3249. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3250. return;
  3251. EmitGlobal(cast<FunctionDecl>(D));
  3252. // Always provide some coverage mapping
  3253. // even for the functions that aren't emitted.
  3254. AddDeferredUnusedCoverageMapping(D);
  3255. break;
  3256. case Decl::Var:
  3257. case Decl::Decomposition:
  3258. // Skip variable templates
  3259. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  3260. return;
  3261. case Decl::VarTemplateSpecialization:
  3262. EmitGlobal(cast<VarDecl>(D));
  3263. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3264. for (auto *B : DD->bindings())
  3265. if (auto *HD = B->getHoldingVar())
  3266. EmitGlobal(HD);
  3267. break;
  3268. // Indirect fields from global anonymous structs and unions can be
  3269. // ignored; only the actual variable requires IR gen support.
  3270. case Decl::IndirectField:
  3271. break;
  3272. // C++ Decls
  3273. case Decl::Namespace:
  3274. EmitDeclContext(cast<NamespaceDecl>(D));
  3275. break;
  3276. case Decl::CXXRecord:
  3277. if (DebugInfo) {
  3278. if (auto *ES = D->getASTContext().getExternalSource())
  3279. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  3280. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  3281. }
  3282. // Emit any static data members, they may be definitions.
  3283. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3284. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3285. EmitTopLevelDecl(I);
  3286. break;
  3287. // No code generation needed.
  3288. case Decl::UsingShadow:
  3289. case Decl::ClassTemplate:
  3290. case Decl::VarTemplate:
  3291. case Decl::VarTemplatePartialSpecialization:
  3292. case Decl::FunctionTemplate:
  3293. case Decl::TypeAliasTemplate:
  3294. case Decl::Block:
  3295. case Decl::Empty:
  3296. break;
  3297. case Decl::Using: // using X; [C++]
  3298. if (CGDebugInfo *DI = getModuleDebugInfo())
  3299. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3300. return;
  3301. case Decl::NamespaceAlias:
  3302. if (CGDebugInfo *DI = getModuleDebugInfo())
  3303. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3304. return;
  3305. case Decl::UsingDirective: // using namespace X; [C++]
  3306. if (CGDebugInfo *DI = getModuleDebugInfo())
  3307. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3308. return;
  3309. case Decl::CXXConstructor:
  3310. // Skip function templates
  3311. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3312. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3313. return;
  3314. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3315. break;
  3316. case Decl::CXXDestructor:
  3317. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  3318. return;
  3319. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3320. break;
  3321. case Decl::StaticAssert:
  3322. // Nothing to do.
  3323. break;
  3324. // Objective-C Decls
  3325. // Forward declarations, no (immediate) code generation.
  3326. case Decl::ObjCInterface:
  3327. case Decl::ObjCCategory:
  3328. break;
  3329. case Decl::ObjCProtocol: {
  3330. auto *Proto = cast<ObjCProtocolDecl>(D);
  3331. if (Proto->isThisDeclarationADefinition())
  3332. ObjCRuntime->GenerateProtocol(Proto);
  3333. break;
  3334. }
  3335. case Decl::ObjCCategoryImpl:
  3336. // Categories have properties but don't support synthesize so we
  3337. // can ignore them here.
  3338. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3339. break;
  3340. case Decl::ObjCImplementation: {
  3341. auto *OMD = cast<ObjCImplementationDecl>(D);
  3342. EmitObjCPropertyImplementations(OMD);
  3343. EmitObjCIvarInitializations(OMD);
  3344. ObjCRuntime->GenerateClass(OMD);
  3345. // Emit global variable debug information.
  3346. if (CGDebugInfo *DI = getModuleDebugInfo())
  3347. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3348. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3349. OMD->getClassInterface()), OMD->getLocation());
  3350. break;
  3351. }
  3352. case Decl::ObjCMethod: {
  3353. auto *OMD = cast<ObjCMethodDecl>(D);
  3354. // If this is not a prototype, emit the body.
  3355. if (OMD->getBody())
  3356. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3357. break;
  3358. }
  3359. case Decl::ObjCCompatibleAlias:
  3360. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3361. break;
  3362. case Decl::PragmaComment: {
  3363. const auto *PCD = cast<PragmaCommentDecl>(D);
  3364. switch (PCD->getCommentKind()) {
  3365. case PCK_Unknown:
  3366. llvm_unreachable("unexpected pragma comment kind");
  3367. case PCK_Linker:
  3368. AppendLinkerOptions(PCD->getArg());
  3369. break;
  3370. case PCK_Lib:
  3371. AddDependentLib(PCD->getArg());
  3372. break;
  3373. case PCK_Compiler:
  3374. case PCK_ExeStr:
  3375. case PCK_User:
  3376. break; // We ignore all of these.
  3377. }
  3378. break;
  3379. }
  3380. case Decl::PragmaDetectMismatch: {
  3381. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3382. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3383. break;
  3384. }
  3385. case Decl::LinkageSpec:
  3386. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3387. break;
  3388. case Decl::FileScopeAsm: {
  3389. // File-scope asm is ignored during device-side CUDA compilation.
  3390. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3391. break;
  3392. // File-scope asm is ignored during device-side OpenMP compilation.
  3393. if (LangOpts.OpenMPIsDevice)
  3394. break;
  3395. auto *AD = cast<FileScopeAsmDecl>(D);
  3396. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3397. break;
  3398. }
  3399. case Decl::Import: {
  3400. auto *Import = cast<ImportDecl>(D);
  3401. // If we've already imported this module, we're done.
  3402. if (!ImportedModules.insert(Import->getImportedModule()))
  3403. break;
  3404. // Emit debug information for direct imports.
  3405. if (!Import->getImportedOwningModule()) {
  3406. if (CGDebugInfo *DI = getModuleDebugInfo())
  3407. DI->EmitImportDecl(*Import);
  3408. }
  3409. // Find all of the submodules and emit the module initializers.
  3410. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3411. SmallVector<clang::Module *, 16> Stack;
  3412. Visited.insert(Import->getImportedModule());
  3413. Stack.push_back(Import->getImportedModule());
  3414. while (!Stack.empty()) {
  3415. clang::Module *Mod = Stack.pop_back_val();
  3416. if (!EmittedModuleInitializers.insert(Mod).second)
  3417. continue;
  3418. for (auto *D : Context.getModuleInitializers(Mod))
  3419. EmitTopLevelDecl(D);
  3420. // Visit the submodules of this module.
  3421. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3422. SubEnd = Mod->submodule_end();
  3423. Sub != SubEnd; ++Sub) {
  3424. // Skip explicit children; they need to be explicitly imported to emit
  3425. // the initializers.
  3426. if ((*Sub)->IsExplicit)
  3427. continue;
  3428. if (Visited.insert(*Sub).second)
  3429. Stack.push_back(*Sub);
  3430. }
  3431. }
  3432. break;
  3433. }
  3434. case Decl::Export:
  3435. EmitDeclContext(cast<ExportDecl>(D));
  3436. break;
  3437. case Decl::OMPThreadPrivate:
  3438. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3439. break;
  3440. case Decl::ClassTemplateSpecialization: {
  3441. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3442. if (DebugInfo &&
  3443. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3444. Spec->hasDefinition())
  3445. DebugInfo->completeTemplateDefinition(*Spec);
  3446. break;
  3447. }
  3448. case Decl::OMPDeclareReduction:
  3449. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3450. break;
  3451. default:
  3452. // Make sure we handled everything we should, every other kind is a
  3453. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3454. // function. Need to recode Decl::Kind to do that easily.
  3455. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3456. break;
  3457. }
  3458. }
  3459. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3460. // Do we need to generate coverage mapping?
  3461. if (!CodeGenOpts.CoverageMapping)
  3462. return;
  3463. switch (D->getKind()) {
  3464. case Decl::CXXConversion:
  3465. case Decl::CXXMethod:
  3466. case Decl::Function:
  3467. case Decl::ObjCMethod:
  3468. case Decl::CXXConstructor:
  3469. case Decl::CXXDestructor: {
  3470. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3471. return;
  3472. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3473. if (I == DeferredEmptyCoverageMappingDecls.end())
  3474. DeferredEmptyCoverageMappingDecls[D] = true;
  3475. break;
  3476. }
  3477. default:
  3478. break;
  3479. };
  3480. }
  3481. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3482. // Do we need to generate coverage mapping?
  3483. if (!CodeGenOpts.CoverageMapping)
  3484. return;
  3485. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3486. if (Fn->isTemplateInstantiation())
  3487. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3488. }
  3489. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3490. if (I == DeferredEmptyCoverageMappingDecls.end())
  3491. DeferredEmptyCoverageMappingDecls[D] = false;
  3492. else
  3493. I->second = false;
  3494. }
  3495. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3496. std::vector<const Decl *> DeferredDecls;
  3497. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3498. if (!I.second)
  3499. continue;
  3500. DeferredDecls.push_back(I.first);
  3501. }
  3502. // Sort the declarations by their location to make sure that the tests get a
  3503. // predictable order for the coverage mapping for the unused declarations.
  3504. if (CodeGenOpts.DumpCoverageMapping)
  3505. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3506. [] (const Decl *LHS, const Decl *RHS) {
  3507. return LHS->getLocStart() < RHS->getLocStart();
  3508. });
  3509. for (const auto *D : DeferredDecls) {
  3510. switch (D->getKind()) {
  3511. case Decl::CXXConversion:
  3512. case Decl::CXXMethod:
  3513. case Decl::Function:
  3514. case Decl::ObjCMethod: {
  3515. CodeGenPGO PGO(*this);
  3516. GlobalDecl GD(cast<FunctionDecl>(D));
  3517. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3518. getFunctionLinkage(GD));
  3519. break;
  3520. }
  3521. case Decl::CXXConstructor: {
  3522. CodeGenPGO PGO(*this);
  3523. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3524. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3525. getFunctionLinkage(GD));
  3526. break;
  3527. }
  3528. case Decl::CXXDestructor: {
  3529. CodeGenPGO PGO(*this);
  3530. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3531. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3532. getFunctionLinkage(GD));
  3533. break;
  3534. }
  3535. default:
  3536. break;
  3537. };
  3538. }
  3539. }
  3540. /// Turns the given pointer into a constant.
  3541. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3542. const void *Ptr) {
  3543. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3544. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3545. return llvm::ConstantInt::get(i64, PtrInt);
  3546. }
  3547. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3548. llvm::NamedMDNode *&GlobalMetadata,
  3549. GlobalDecl D,
  3550. llvm::GlobalValue *Addr) {
  3551. if (!GlobalMetadata)
  3552. GlobalMetadata =
  3553. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3554. // TODO: should we report variant information for ctors/dtors?
  3555. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3556. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3557. CGM.getLLVMContext(), D.getDecl()))};
  3558. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3559. }
  3560. /// For each function which is declared within an extern "C" region and marked
  3561. /// as 'used', but has internal linkage, create an alias from the unmangled
  3562. /// name to the mangled name if possible. People expect to be able to refer
  3563. /// to such functions with an unmangled name from inline assembly within the
  3564. /// same translation unit.
  3565. void CodeGenModule::EmitStaticExternCAliases() {
  3566. // Don't do anything if we're generating CUDA device code -- the NVPTX
  3567. // assembly target doesn't support aliases.
  3568. if (Context.getTargetInfo().getTriple().isNVPTX())
  3569. return;
  3570. for (auto &I : StaticExternCValues) {
  3571. IdentifierInfo *Name = I.first;
  3572. llvm::GlobalValue *Val = I.second;
  3573. if (Val && !getModule().getNamedValue(Name->getName()))
  3574. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3575. }
  3576. }
  3577. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3578. GlobalDecl &Result) const {
  3579. auto Res = Manglings.find(MangledName);
  3580. if (Res == Manglings.end())
  3581. return false;
  3582. Result = Res->getValue();
  3583. return true;
  3584. }
  3585. /// Emits metadata nodes associating all the global values in the
  3586. /// current module with the Decls they came from. This is useful for
  3587. /// projects using IR gen as a subroutine.
  3588. ///
  3589. /// Since there's currently no way to associate an MDNode directly
  3590. /// with an llvm::GlobalValue, we create a global named metadata
  3591. /// with the name 'clang.global.decl.ptrs'.
  3592. void CodeGenModule::EmitDeclMetadata() {
  3593. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3594. for (auto &I : MangledDeclNames) {
  3595. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3596. // Some mangled names don't necessarily have an associated GlobalValue
  3597. // in this module, e.g. if we mangled it for DebugInfo.
  3598. if (Addr)
  3599. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3600. }
  3601. }
  3602. /// Emits metadata nodes for all the local variables in the current
  3603. /// function.
  3604. void CodeGenFunction::EmitDeclMetadata() {
  3605. if (LocalDeclMap.empty()) return;
  3606. llvm::LLVMContext &Context = getLLVMContext();
  3607. // Find the unique metadata ID for this name.
  3608. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3609. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3610. for (auto &I : LocalDeclMap) {
  3611. const Decl *D = I.first;
  3612. llvm::Value *Addr = I.second.getPointer();
  3613. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3614. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3615. Alloca->setMetadata(
  3616. DeclPtrKind, llvm::MDNode::get(
  3617. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3618. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3619. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3620. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3621. }
  3622. }
  3623. }
  3624. void CodeGenModule::EmitVersionIdentMetadata() {
  3625. llvm::NamedMDNode *IdentMetadata =
  3626. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3627. std::string Version = getClangFullVersion();
  3628. llvm::LLVMContext &Ctx = TheModule.getContext();
  3629. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3630. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3631. }
  3632. void CodeGenModule::EmitTargetMetadata() {
  3633. // Warning, new MangledDeclNames may be appended within this loop.
  3634. // We rely on MapVector insertions adding new elements to the end
  3635. // of the container.
  3636. // FIXME: Move this loop into the one target that needs it, and only
  3637. // loop over those declarations for which we couldn't emit the target
  3638. // metadata when we emitted the declaration.
  3639. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3640. auto Val = *(MangledDeclNames.begin() + I);
  3641. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3642. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3643. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3644. }
  3645. }
  3646. void CodeGenModule::EmitCoverageFile() {
  3647. if (getCodeGenOpts().CoverageDataFile.empty() &&
  3648. getCodeGenOpts().CoverageNotesFile.empty())
  3649. return;
  3650. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  3651. if (!CUNode)
  3652. return;
  3653. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3654. llvm::LLVMContext &Ctx = TheModule.getContext();
  3655. auto *CoverageDataFile =
  3656. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  3657. auto *CoverageNotesFile =
  3658. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  3659. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3660. llvm::MDNode *CU = CUNode->getOperand(i);
  3661. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  3662. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3663. }
  3664. }
  3665. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3666. // Sema has checked that all uuid strings are of the form
  3667. // "12345678-1234-1234-1234-1234567890ab".
  3668. assert(Uuid.size() == 36);
  3669. for (unsigned i = 0; i < 36; ++i) {
  3670. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3671. else assert(isHexDigit(Uuid[i]));
  3672. }
  3673. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3674. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3675. llvm::Constant *Field3[8];
  3676. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3677. Field3[Idx] = llvm::ConstantInt::get(
  3678. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3679. llvm::Constant *Fields[4] = {
  3680. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3681. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3682. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3683. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3684. };
  3685. return llvm::ConstantStruct::getAnon(Fields);
  3686. }
  3687. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3688. bool ForEH) {
  3689. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3690. // FIXME: should we even be calling this method if RTTI is disabled
  3691. // and it's not for EH?
  3692. if (!ForEH && !getLangOpts().RTTI)
  3693. return llvm::Constant::getNullValue(Int8PtrTy);
  3694. if (ForEH && Ty->isObjCObjectPointerType() &&
  3695. LangOpts.ObjCRuntime.isGNUFamily())
  3696. return ObjCRuntime->GetEHType(Ty);
  3697. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3698. }
  3699. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3700. for (auto RefExpr : D->varlists()) {
  3701. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3702. bool PerformInit =
  3703. VD->getAnyInitializer() &&
  3704. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3705. /*ForRef=*/false);
  3706. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  3707. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3708. VD, Addr, RefExpr->getLocStart(), PerformInit))
  3709. CXXGlobalInits.push_back(InitFunction);
  3710. }
  3711. }
  3712. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  3713. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  3714. if (InternalId)
  3715. return InternalId;
  3716. if (isExternallyVisible(T->getLinkage())) {
  3717. std::string OutName;
  3718. llvm::raw_string_ostream Out(OutName);
  3719. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  3720. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  3721. } else {
  3722. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  3723. llvm::ArrayRef<llvm::Metadata *>());
  3724. }
  3725. return InternalId;
  3726. }
  3727. /// Returns whether this module needs the "all-vtables" type identifier.
  3728. bool CodeGenModule::NeedAllVtablesTypeId() const {
  3729. // Returns true if at least one of vtable-based CFI checkers is enabled and
  3730. // is not in the trapping mode.
  3731. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  3732. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  3733. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  3734. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  3735. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  3736. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  3737. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  3738. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  3739. }
  3740. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  3741. CharUnits Offset,
  3742. const CXXRecordDecl *RD) {
  3743. llvm::Metadata *MD =
  3744. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  3745. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3746. if (CodeGenOpts.SanitizeCfiCrossDso)
  3747. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  3748. VTable->addTypeMetadata(Offset.getQuantity(),
  3749. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  3750. if (NeedAllVtablesTypeId()) {
  3751. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  3752. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3753. }
  3754. }
  3755. // Fills in the supplied string map with the set of target features for the
  3756. // passed in function.
  3757. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  3758. const FunctionDecl *FD) {
  3759. StringRef TargetCPU = Target.getTargetOpts().CPU;
  3760. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  3761. // If we have a TargetAttr build up the feature map based on that.
  3762. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  3763. // Make a copy of the features as passed on the command line into the
  3764. // beginning of the additional features from the function to override.
  3765. ParsedAttr.first.insert(ParsedAttr.first.begin(),
  3766. Target.getTargetOpts().FeaturesAsWritten.begin(),
  3767. Target.getTargetOpts().FeaturesAsWritten.end());
  3768. if (ParsedAttr.second != "")
  3769. TargetCPU = ParsedAttr.second;
  3770. // Now populate the feature map, first with the TargetCPU which is either
  3771. // the default or a new one from the target attribute string. Then we'll use
  3772. // the passed in features (FeaturesAsWritten) along with the new ones from
  3773. // the attribute.
  3774. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
  3775. } else {
  3776. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  3777. Target.getTargetOpts().Features);
  3778. }
  3779. }
  3780. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  3781. if (!SanStats)
  3782. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  3783. return *SanStats;
  3784. }
  3785. llvm::Value *
  3786. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  3787. CodeGenFunction &CGF) {
  3788. llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
  3789. auto SamplerT = getOpenCLRuntime().getSamplerType();
  3790. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  3791. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  3792. "__translate_sampler_initializer"),
  3793. {C});
  3794. }