CodeGenModule.cpp 142 KB

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