CodeGenModule.cpp 188 KB

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