CodeGenModule.cpp 219 KB

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