CodeGenModule.cpp 176 KB

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