CodeGenFunction.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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-function state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGBlocks.h"
  14. #include "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/ASTLambda.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/FrontendDiagnostic.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  39. using namespace clang;
  40. using namespace CodeGen;
  41. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  42. /// markers.
  43. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  44. const LangOptions &LangOpts) {
  45. if (CGOpts.DisableLifetimeMarkers)
  46. return false;
  47. // Sanitizers may use markers.
  48. if (CGOpts.SanitizeAddressUseAfterScope ||
  49. LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
  50. LangOpts.Sanitize.has(SanitizerKind::Memory))
  51. return true;
  52. // For now, only in optimized builds.
  53. return CGOpts.OptimizationLevel != 0;
  54. }
  55. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  56. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  57. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  58. CGBuilderInserterTy(this)),
  59. SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
  60. PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
  61. CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  62. if (!suppressNewContext)
  63. CGM.getCXXABI().getMangleContext().startNewFunction();
  64. llvm::FastMathFlags FMF;
  65. if (CGM.getLangOpts().FastMath)
  66. FMF.setFast();
  67. if (CGM.getLangOpts().FiniteMathOnly) {
  68. FMF.setNoNaNs();
  69. FMF.setNoInfs();
  70. }
  71. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  72. FMF.setNoNaNs();
  73. }
  74. if (CGM.getCodeGenOpts().NoSignedZeros) {
  75. FMF.setNoSignedZeros();
  76. }
  77. if (CGM.getCodeGenOpts().ReciprocalMath) {
  78. FMF.setAllowReciprocal();
  79. }
  80. if (CGM.getCodeGenOpts().Reassociate) {
  81. FMF.setAllowReassoc();
  82. }
  83. Builder.setFastMathFlags(FMF);
  84. }
  85. CodeGenFunction::~CodeGenFunction() {
  86. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  87. // If there are any unclaimed block infos, go ahead and destroy them
  88. // now. This can happen if IR-gen gets clever and skips evaluating
  89. // something.
  90. if (FirstBlockInfo)
  91. destroyBlockInfos(FirstBlockInfo);
  92. if (getLangOpts().OpenMP && CurFn)
  93. CGM.getOpenMPRuntime().functionFinished(*this);
  94. }
  95. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  96. LValueBaseInfo *BaseInfo,
  97. TBAAAccessInfo *TBAAInfo) {
  98. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  99. /* forPointeeType= */ true);
  100. }
  101. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  102. LValueBaseInfo *BaseInfo,
  103. TBAAAccessInfo *TBAAInfo,
  104. bool forPointeeType) {
  105. if (TBAAInfo)
  106. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  107. // Honor alignment typedef attributes even on incomplete types.
  108. // We also honor them straight for C++ class types, even as pointees;
  109. // there's an expressivity gap here.
  110. if (auto TT = T->getAs<TypedefType>()) {
  111. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  112. if (BaseInfo)
  113. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  114. return getContext().toCharUnitsFromBits(Align);
  115. }
  116. }
  117. if (BaseInfo)
  118. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  119. CharUnits Alignment;
  120. if (T->isIncompleteType()) {
  121. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  122. } else {
  123. // For C++ class pointees, we don't know whether we're pointing at a
  124. // base or a complete object, so we generally need to use the
  125. // non-virtual alignment.
  126. const CXXRecordDecl *RD;
  127. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  128. Alignment = CGM.getClassPointerAlignment(RD);
  129. } else {
  130. Alignment = getContext().getTypeAlignInChars(T);
  131. if (T.getQualifiers().hasUnaligned())
  132. Alignment = CharUnits::One();
  133. }
  134. // Cap to the global maximum type alignment unless the alignment
  135. // was somehow explicit on the type.
  136. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  137. if (Alignment.getQuantity() > MaxAlign &&
  138. !getContext().isAlignmentRequired(T))
  139. Alignment = CharUnits::fromQuantity(MaxAlign);
  140. }
  141. }
  142. return Alignment;
  143. }
  144. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  145. LValueBaseInfo BaseInfo;
  146. TBAAAccessInfo TBAAInfo;
  147. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  148. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  149. TBAAInfo);
  150. }
  151. /// Given a value of type T* that may not be to a complete object,
  152. /// construct an l-value with the natural pointee alignment of T.
  153. LValue
  154. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  155. LValueBaseInfo BaseInfo;
  156. TBAAAccessInfo TBAAInfo;
  157. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  158. /* forPointeeType= */ true);
  159. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  160. }
  161. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  162. return CGM.getTypes().ConvertTypeForMem(T);
  163. }
  164. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  165. return CGM.getTypes().ConvertType(T);
  166. }
  167. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  168. type = type.getCanonicalType();
  169. while (true) {
  170. switch (type->getTypeClass()) {
  171. #define TYPE(name, parent)
  172. #define ABSTRACT_TYPE(name, parent)
  173. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  174. #define DEPENDENT_TYPE(name, parent) case Type::name:
  175. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  176. #include "clang/AST/TypeNodes.inc"
  177. llvm_unreachable("non-canonical or dependent type in IR-generation");
  178. case Type::Auto:
  179. case Type::DeducedTemplateSpecialization:
  180. llvm_unreachable("undeduced type in IR-generation");
  181. // Various scalar types.
  182. case Type::Builtin:
  183. case Type::Pointer:
  184. case Type::BlockPointer:
  185. case Type::LValueReference:
  186. case Type::RValueReference:
  187. case Type::MemberPointer:
  188. case Type::Vector:
  189. case Type::ExtVector:
  190. case Type::FunctionProto:
  191. case Type::FunctionNoProto:
  192. case Type::Enum:
  193. case Type::ObjCObjectPointer:
  194. case Type::Pipe:
  195. return TEK_Scalar;
  196. // Complexes.
  197. case Type::Complex:
  198. return TEK_Complex;
  199. // Arrays, records, and Objective-C objects.
  200. case Type::ConstantArray:
  201. case Type::IncompleteArray:
  202. case Type::VariableArray:
  203. case Type::Record:
  204. case Type::ObjCObject:
  205. case Type::ObjCInterface:
  206. return TEK_Aggregate;
  207. // We operate on atomic values according to their underlying type.
  208. case Type::Atomic:
  209. type = cast<AtomicType>(type)->getValueType();
  210. continue;
  211. }
  212. llvm_unreachable("unknown type kind!");
  213. }
  214. }
  215. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  216. // For cleanliness, we try to avoid emitting the return block for
  217. // simple cases.
  218. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  219. if (CurBB) {
  220. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  221. // We have a valid insert point, reuse it if it is empty or there are no
  222. // explicit jumps to the return block.
  223. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  224. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  225. delete ReturnBlock.getBlock();
  226. ReturnBlock = JumpDest();
  227. } else
  228. EmitBlock(ReturnBlock.getBlock());
  229. return llvm::DebugLoc();
  230. }
  231. // Otherwise, if the return block is the target of a single direct
  232. // branch then we can just put the code in that block instead. This
  233. // cleans up functions which started with a unified return block.
  234. if (ReturnBlock.getBlock()->hasOneUse()) {
  235. llvm::BranchInst *BI =
  236. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  237. if (BI && BI->isUnconditional() &&
  238. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  239. // Record/return the DebugLoc of the simple 'return' expression to be used
  240. // later by the actual 'ret' instruction.
  241. llvm::DebugLoc Loc = BI->getDebugLoc();
  242. Builder.SetInsertPoint(BI->getParent());
  243. BI->eraseFromParent();
  244. delete ReturnBlock.getBlock();
  245. ReturnBlock = JumpDest();
  246. return Loc;
  247. }
  248. }
  249. // FIXME: We are at an unreachable point, there is no reason to emit the block
  250. // unless it has uses. However, we still need a place to put the debug
  251. // region.end for now.
  252. EmitBlock(ReturnBlock.getBlock());
  253. return llvm::DebugLoc();
  254. }
  255. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  256. if (!BB) return;
  257. if (!BB->use_empty())
  258. return CGF.CurFn->getBasicBlockList().push_back(BB);
  259. delete BB;
  260. }
  261. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  262. assert(BreakContinueStack.empty() &&
  263. "mismatched push/pop in break/continue stack!");
  264. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  265. && NumSimpleReturnExprs == NumReturnExprs
  266. && ReturnBlock.getBlock()->use_empty();
  267. // Usually the return expression is evaluated before the cleanup
  268. // code. If the function contains only a simple return statement,
  269. // such as a constant, the location before the cleanup code becomes
  270. // the last useful breakpoint in the function, because the simple
  271. // return expression will be evaluated after the cleanup code. To be
  272. // safe, set the debug location for cleanup code to the location of
  273. // the return statement. Otherwise the cleanup code should be at the
  274. // end of the function's lexical scope.
  275. //
  276. // If there are multiple branches to the return block, the branch
  277. // instructions will get the location of the return statements and
  278. // all will be fine.
  279. if (CGDebugInfo *DI = getDebugInfo()) {
  280. if (OnlySimpleReturnStmts)
  281. DI->EmitLocation(Builder, LastStopPoint);
  282. else
  283. DI->EmitLocation(Builder, EndLoc);
  284. }
  285. // Pop any cleanups that might have been associated with the
  286. // parameters. Do this in whatever block we're currently in; it's
  287. // important to do this before we enter the return block or return
  288. // edges will be *really* confused.
  289. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  290. bool HasOnlyLifetimeMarkers =
  291. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  292. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  293. if (HasCleanups) {
  294. // Make sure the line table doesn't jump back into the body for
  295. // the ret after it's been at EndLoc.
  296. if (CGDebugInfo *DI = getDebugInfo())
  297. if (OnlySimpleReturnStmts)
  298. DI->EmitLocation(Builder, EndLoc);
  299. PopCleanupBlocks(PrologueCleanupDepth);
  300. }
  301. // Emit function epilog (to return).
  302. llvm::DebugLoc Loc = EmitReturnBlock();
  303. if (ShouldInstrumentFunction()) {
  304. if (CGM.getCodeGenOpts().InstrumentFunctions)
  305. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  306. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  307. CurFn->addFnAttr("instrument-function-exit-inlined",
  308. "__cyg_profile_func_exit");
  309. }
  310. // Emit debug descriptor for function end.
  311. if (CGDebugInfo *DI = getDebugInfo())
  312. DI->EmitFunctionEnd(Builder, CurFn);
  313. // Reset the debug location to that of the simple 'return' expression, if any
  314. // rather than that of the end of the function's scope '}'.
  315. ApplyDebugLocation AL(*this, Loc);
  316. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  317. EmitEndEHSpec(CurCodeDecl);
  318. assert(EHStack.empty() &&
  319. "did not remove all scopes from cleanup stack!");
  320. // If someone did an indirect goto, emit the indirect goto block at the end of
  321. // the function.
  322. if (IndirectBranch) {
  323. EmitBlock(IndirectBranch->getParent());
  324. Builder.ClearInsertionPoint();
  325. }
  326. // If some of our locals escaped, insert a call to llvm.localescape in the
  327. // entry block.
  328. if (!EscapedLocals.empty()) {
  329. // Invert the map from local to index into a simple vector. There should be
  330. // no holes.
  331. SmallVector<llvm::Value *, 4> EscapeArgs;
  332. EscapeArgs.resize(EscapedLocals.size());
  333. for (auto &Pair : EscapedLocals)
  334. EscapeArgs[Pair.second] = Pair.first;
  335. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  336. &CGM.getModule(), llvm::Intrinsic::localescape);
  337. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  338. }
  339. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  340. llvm::Instruction *Ptr = AllocaInsertPt;
  341. AllocaInsertPt = nullptr;
  342. Ptr->eraseFromParent();
  343. // If someone took the address of a label but never did an indirect goto, we
  344. // made a zero entry PHI node, which is illegal, zap it now.
  345. if (IndirectBranch) {
  346. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  347. if (PN->getNumIncomingValues() == 0) {
  348. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  349. PN->eraseFromParent();
  350. }
  351. }
  352. EmitIfUsed(*this, EHResumeBlock);
  353. EmitIfUsed(*this, TerminateLandingPad);
  354. EmitIfUsed(*this, TerminateHandler);
  355. EmitIfUsed(*this, UnreachableBlock);
  356. for (const auto &FuncletAndParent : TerminateFunclets)
  357. EmitIfUsed(*this, FuncletAndParent.second);
  358. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  359. EmitDeclMetadata();
  360. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  361. I = DeferredReplacements.begin(),
  362. E = DeferredReplacements.end();
  363. I != E; ++I) {
  364. I->first->replaceAllUsesWith(I->second);
  365. I->first->eraseFromParent();
  366. }
  367. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  368. // PHIs if the current function is a coroutine. We don't do it for all
  369. // functions as it may result in slight increase in numbers of instructions
  370. // if compiled with no optimizations. We do it for coroutine as the lifetime
  371. // of CleanupDestSlot alloca make correct coroutine frame building very
  372. // difficult.
  373. if (NormalCleanupDest.isValid() && isCoroutine()) {
  374. llvm::DominatorTree DT(*CurFn);
  375. llvm::PromoteMemToReg(
  376. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  377. NormalCleanupDest = Address::invalid();
  378. }
  379. // Scan function arguments for vector width.
  380. for (llvm::Argument &A : CurFn->args())
  381. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  382. LargestVectorWidth = std::max((uint64_t)LargestVectorWidth,
  383. VT->getPrimitiveSizeInBits().getFixedSize());
  384. // Update vector width based on return type.
  385. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  386. LargestVectorWidth = std::max((uint64_t)LargestVectorWidth,
  387. VT->getPrimitiveSizeInBits().getFixedSize());
  388. // Add the required-vector-width attribute. This contains the max width from:
  389. // 1. min-vector-width attribute used in the source program.
  390. // 2. Any builtins used that have a vector width specified.
  391. // 3. Values passed in and out of inline assembly.
  392. // 4. Width of vector arguments and return types for this function.
  393. // 5. Width of vector aguments and return types for functions called by this
  394. // function.
  395. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  396. // If we generated an unreachable return block, delete it now.
  397. if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
  398. Builder.ClearInsertionPoint();
  399. ReturnBlock.getBlock()->eraseFromParent();
  400. }
  401. if (ReturnValue.isValid()) {
  402. auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
  403. if (RetAlloca && RetAlloca->use_empty()) {
  404. RetAlloca->eraseFromParent();
  405. ReturnValue = Address::invalid();
  406. }
  407. }
  408. }
  409. /// ShouldInstrumentFunction - Return true if the current function should be
  410. /// instrumented with __cyg_profile_func_* calls
  411. bool CodeGenFunction::ShouldInstrumentFunction() {
  412. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  413. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  414. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  415. return false;
  416. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  417. return false;
  418. return true;
  419. }
  420. /// ShouldXRayInstrument - Return true if the current function should be
  421. /// instrumented with XRay nop sleds.
  422. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  423. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  424. }
  425. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  426. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  427. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  428. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  429. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  430. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  431. XRayInstrKind::Custom);
  432. }
  433. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  434. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  435. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  436. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  437. XRayInstrKind::Typed);
  438. }
  439. llvm::Constant *
  440. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  441. llvm::Constant *Addr) {
  442. // Addresses stored in prologue data can't require run-time fixups and must
  443. // be PC-relative. Run-time fixups are undesirable because they necessitate
  444. // writable text segments, which are unsafe. And absolute addresses are
  445. // undesirable because they break PIE mode.
  446. // Add a layer of indirection through a private global. Taking its address
  447. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  448. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  449. /*isConstant=*/true,
  450. llvm::GlobalValue::PrivateLinkage, Addr);
  451. // Create a PC-relative address.
  452. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  453. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  454. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  455. return (IntPtrTy == Int32Ty)
  456. ? PCRelAsInt
  457. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  458. }
  459. llvm::Value *
  460. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  461. llvm::Value *EncodedAddr) {
  462. // Reconstruct the address of the global.
  463. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  464. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  465. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  466. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  467. // Load the original pointer through the global.
  468. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  469. "decoded_addr");
  470. }
  471. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  472. llvm::Function *Fn)
  473. {
  474. if (!FD->hasAttr<OpenCLKernelAttr>())
  475. return;
  476. llvm::LLVMContext &Context = getLLVMContext();
  477. CGM.GenOpenCLArgMetadata(Fn, FD, this);
  478. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  479. QualType HintQTy = A->getTypeHint();
  480. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  481. bool IsSignedInteger =
  482. HintQTy->isSignedIntegerType() ||
  483. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  484. llvm::Metadata *AttrMDArgs[] = {
  485. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  486. CGM.getTypes().ConvertType(A->getTypeHint()))),
  487. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  488. llvm::IntegerType::get(Context, 32),
  489. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  490. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  491. }
  492. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  493. llvm::Metadata *AttrMDArgs[] = {
  494. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  495. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  496. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  497. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  498. }
  499. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  500. llvm::Metadata *AttrMDArgs[] = {
  501. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  502. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  503. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  504. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  505. }
  506. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  507. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  508. llvm::Metadata *AttrMDArgs[] = {
  509. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  510. Fn->setMetadata("intel_reqd_sub_group_size",
  511. llvm::MDNode::get(Context, AttrMDArgs));
  512. }
  513. }
  514. /// Determine whether the function F ends with a return stmt.
  515. static bool endsWithReturn(const Decl* F) {
  516. const Stmt *Body = nullptr;
  517. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  518. Body = FD->getBody();
  519. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  520. Body = OMD->getBody();
  521. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  522. auto LastStmt = CS->body_rbegin();
  523. if (LastStmt != CS->body_rend())
  524. return isa<ReturnStmt>(*LastStmt);
  525. }
  526. return false;
  527. }
  528. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  529. if (SanOpts.has(SanitizerKind::Thread)) {
  530. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  531. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  532. }
  533. }
  534. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  535. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  536. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  537. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  538. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  539. return false;
  540. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  541. return false;
  542. if (MD->getNumParams() == 2) {
  543. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  544. if (!PT || !PT->isVoidPointerType() ||
  545. !PT->getPointeeType().isConstQualified())
  546. return false;
  547. }
  548. return true;
  549. }
  550. /// Return the UBSan prologue signature for \p FD if one is available.
  551. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  552. const FunctionDecl *FD) {
  553. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  554. if (!MD->isStatic())
  555. return nullptr;
  556. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  557. }
  558. void CodeGenFunction::StartFunction(GlobalDecl GD,
  559. QualType RetTy,
  560. llvm::Function *Fn,
  561. const CGFunctionInfo &FnInfo,
  562. const FunctionArgList &Args,
  563. SourceLocation Loc,
  564. SourceLocation StartLoc) {
  565. assert(!CurFn &&
  566. "Do not use a CodeGenFunction object for more than one function");
  567. const Decl *D = GD.getDecl();
  568. DidCallStackSave = false;
  569. CurCodeDecl = D;
  570. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  571. if (FD->usesSEHTry())
  572. CurSEHParent = FD;
  573. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  574. FnRetTy = RetTy;
  575. CurFn = Fn;
  576. CurFnInfo = &FnInfo;
  577. assert(CurFn->isDeclaration() && "Function already has body?");
  578. // If this function has been blacklisted for any of the enabled sanitizers,
  579. // disable the sanitizer for the function.
  580. do {
  581. #define SANITIZER(NAME, ID) \
  582. if (SanOpts.empty()) \
  583. break; \
  584. if (SanOpts.has(SanitizerKind::ID)) \
  585. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  586. SanOpts.set(SanitizerKind::ID, false);
  587. #include "clang/Basic/Sanitizers.def"
  588. #undef SANITIZER
  589. } while (0);
  590. if (D) {
  591. // Apply the no_sanitize* attributes to SanOpts.
  592. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  593. SanitizerMask mask = Attr->getMask();
  594. SanOpts.Mask &= ~mask;
  595. if (mask & SanitizerKind::Address)
  596. SanOpts.set(SanitizerKind::KernelAddress, false);
  597. if (mask & SanitizerKind::KernelAddress)
  598. SanOpts.set(SanitizerKind::Address, false);
  599. if (mask & SanitizerKind::HWAddress)
  600. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  601. if (mask & SanitizerKind::KernelHWAddress)
  602. SanOpts.set(SanitizerKind::HWAddress, false);
  603. }
  604. }
  605. // Apply sanitizer attributes to the function.
  606. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  607. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  608. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  609. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  610. if (SanOpts.has(SanitizerKind::MemTag))
  611. Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
  612. if (SanOpts.has(SanitizerKind::Thread))
  613. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  614. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  615. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  616. if (SanOpts.has(SanitizerKind::SafeStack))
  617. Fn->addFnAttr(llvm::Attribute::SafeStack);
  618. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  619. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  620. // Apply fuzzing attribute to the function.
  621. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  622. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  623. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  624. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  625. if (SanOpts.has(SanitizerKind::Thread)) {
  626. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  627. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  628. if (OMD->getMethodFamily() == OMF_dealloc ||
  629. OMD->getMethodFamily() == OMF_initialize ||
  630. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  631. markAsIgnoreThreadCheckingAtRuntime(Fn);
  632. }
  633. }
  634. }
  635. // Ignore unrelated casts in STL allocate() since the allocator must cast
  636. // from void* to T* before object initialization completes. Don't match on the
  637. // namespace because not all allocators are in std::
  638. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  639. if (matchesStlAllocatorFn(D, getContext()))
  640. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  641. }
  642. // Ignore null checks in coroutine functions since the coroutines passes
  643. // are not aware of how to move the extra UBSan instructions across the split
  644. // coroutine boundaries.
  645. if (D && SanOpts.has(SanitizerKind::Null))
  646. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  647. if (FD->getBody() &&
  648. FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
  649. SanOpts.Mask &= ~SanitizerKind::Null;
  650. // Apply xray attributes to the function (as a string, for now)
  651. if (D) {
  652. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  653. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  654. XRayInstrKind::Function)) {
  655. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
  656. Fn->addFnAttr("function-instrument", "xray-always");
  657. if (XRayAttr->neverXRayInstrument())
  658. Fn->addFnAttr("function-instrument", "xray-never");
  659. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  660. if (ShouldXRayInstrumentFunction())
  661. Fn->addFnAttr("xray-log-args",
  662. llvm::utostr(LogArgs->getArgumentCount()));
  663. }
  664. } else {
  665. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  666. Fn->addFnAttr(
  667. "xray-instruction-threshold",
  668. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  669. }
  670. }
  671. // Add no-jump-tables value.
  672. Fn->addFnAttr("no-jump-tables",
  673. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  674. // Add profile-sample-accurate value.
  675. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  676. Fn->addFnAttr("profile-sample-accurate");
  677. if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
  678. Fn->addFnAttr("cfi-canonical-jump-table");
  679. if (getLangOpts().OpenCL) {
  680. // Add metadata for a kernel function.
  681. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  682. EmitOpenCLKernelMetadata(FD, Fn);
  683. }
  684. // If we are checking function types, emit a function type signature as
  685. // prologue data.
  686. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  687. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  688. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  689. // Remove any (C++17) exception specifications, to allow calling e.g. a
  690. // noexcept function through a non-noexcept pointer.
  691. auto ProtoTy =
  692. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  693. EST_None);
  694. llvm::Constant *FTRTTIConst =
  695. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  696. llvm::Constant *FTRTTIConstEncoded =
  697. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  698. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  699. FTRTTIConstEncoded};
  700. llvm::Constant *PrologueStructConst =
  701. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  702. Fn->setPrologueData(PrologueStructConst);
  703. }
  704. }
  705. }
  706. // If we're checking nullability, we need to know whether we can check the
  707. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  708. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  709. auto Nullability = FnRetTy->getNullability(getContext());
  710. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  711. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  712. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  713. RetValNullabilityPrecondition =
  714. llvm::ConstantInt::getTrue(getLLVMContext());
  715. }
  716. }
  717. // If we're in C++ mode and the function name is "main", it is guaranteed
  718. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  719. // used within a program").
  720. if (getLangOpts().CPlusPlus)
  721. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  722. if (FD->isMain())
  723. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  724. // If a custom alignment is used, force realigning to this alignment on
  725. // any main function which certainly will need it.
  726. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  727. if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  728. CGM.getCodeGenOpts().StackAlignment)
  729. Fn->addFnAttr("stackrealign");
  730. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  731. // Create a marker to make it easy to insert allocas into the entryblock
  732. // later. Don't create this with the builder, because we don't want it
  733. // folded.
  734. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  735. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  736. ReturnBlock = getJumpDestInCurrentScope("return");
  737. Builder.SetInsertPoint(EntryBB);
  738. // If we're checking the return value, allocate space for a pointer to a
  739. // precise source location of the checked return statement.
  740. if (requiresReturnValueCheck()) {
  741. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  742. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  743. }
  744. // Emit subprogram debug descriptor.
  745. if (CGDebugInfo *DI = getDebugInfo()) {
  746. // Reconstruct the type from the argument list so that implicit parameters,
  747. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  748. // convention.
  749. CallingConv CC = CallingConv::CC_C;
  750. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  751. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  752. CC = SrcFnTy->getCallConv();
  753. SmallVector<QualType, 16> ArgTypes;
  754. for (const VarDecl *VD : Args)
  755. ArgTypes.push_back(VD->getType());
  756. QualType FnType = getContext().getFunctionType(
  757. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  758. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
  759. Builder);
  760. }
  761. if (ShouldInstrumentFunction()) {
  762. if (CGM.getCodeGenOpts().InstrumentFunctions)
  763. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  764. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  765. CurFn->addFnAttr("instrument-function-entry-inlined",
  766. "__cyg_profile_func_enter");
  767. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  768. CurFn->addFnAttr("instrument-function-entry-inlined",
  769. "__cyg_profile_func_enter_bare");
  770. }
  771. // Since emitting the mcount call here impacts optimizations such as function
  772. // inlining, we just add an attribute to insert a mcount call in backend.
  773. // The attribute "counting-function" is set to mcount function name which is
  774. // architecture dependent.
  775. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  776. // Calls to fentry/mcount should not be generated if function has
  777. // the no_instrument_function attribute.
  778. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  779. if (CGM.getCodeGenOpts().CallFEntry)
  780. Fn->addFnAttr("fentry-call", "true");
  781. else {
  782. Fn->addFnAttr("instrument-function-entry-inlined",
  783. getTarget().getMCountName());
  784. }
  785. }
  786. }
  787. if (RetTy->isVoidType()) {
  788. // Void type; nothing to return.
  789. ReturnValue = Address::invalid();
  790. // Count the implicit return.
  791. if (!endsWithReturn(D))
  792. ++NumReturnExprs;
  793. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
  794. // Indirect return; emit returned value directly into sret slot.
  795. // This reduces code size, and affects correctness in C++.
  796. auto AI = CurFn->arg_begin();
  797. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  798. ++AI;
  799. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  800. if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
  801. ReturnValuePointer =
  802. CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
  803. Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
  804. ReturnValue.getPointer(), Int8PtrTy),
  805. ReturnValuePointer);
  806. }
  807. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  808. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  809. // Load the sret pointer from the argument struct and return into that.
  810. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  811. llvm::Function::arg_iterator EI = CurFn->arg_end();
  812. --EI;
  813. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  814. ReturnValuePointer = Address(Addr, getPointerAlign());
  815. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  816. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  817. } else {
  818. ReturnValue = CreateIRTemp(RetTy, "retval");
  819. // Tell the epilog emitter to autorelease the result. We do this
  820. // now so that various specialized functions can suppress it
  821. // during their IR-generation.
  822. if (getLangOpts().ObjCAutoRefCount &&
  823. !CurFnInfo->isReturnsRetained() &&
  824. RetTy->isObjCRetainableType())
  825. AutoreleaseResult = true;
  826. }
  827. EmitStartEHSpec(CurCodeDecl);
  828. PrologueCleanupDepth = EHStack.stable_begin();
  829. // Emit OpenMP specific initialization of the device functions.
  830. if (getLangOpts().OpenMP && CurCodeDecl)
  831. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  832. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  833. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  834. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  835. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  836. if (MD->getParent()->isLambda() &&
  837. MD->getOverloadedOperator() == OO_Call) {
  838. // We're in a lambda; figure out the captures.
  839. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  840. LambdaThisCaptureField);
  841. if (LambdaThisCaptureField) {
  842. // If the lambda captures the object referred to by '*this' - either by
  843. // value or by reference, make sure CXXThisValue points to the correct
  844. // object.
  845. // Get the lvalue for the field (which is a copy of the enclosing object
  846. // or contains the address of the enclosing object).
  847. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  848. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  849. // If the enclosing object was captured by value, just use its address.
  850. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  851. } else {
  852. // Load the lvalue pointed to by the field, since '*this' was captured
  853. // by reference.
  854. CXXThisValue =
  855. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  856. }
  857. }
  858. for (auto *FD : MD->getParent()->fields()) {
  859. if (FD->hasCapturedVLAType()) {
  860. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  861. SourceLocation()).getScalarVal();
  862. auto VAT = FD->getCapturedVLAType();
  863. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  864. }
  865. }
  866. } else {
  867. // Not in a lambda; just use 'this' from the method.
  868. // FIXME: Should we generate a new load for each use of 'this'? The
  869. // fast register allocator would be happier...
  870. CXXThisValue = CXXABIThisValue;
  871. }
  872. // Check the 'this' pointer once per function, if it's available.
  873. if (CXXABIThisValue) {
  874. SanitizerSet SkippedChecks;
  875. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  876. QualType ThisTy = MD->getThisType();
  877. // If this is the call operator of a lambda with no capture-default, it
  878. // may have a static invoker function, which may call this operator with
  879. // a null 'this' pointer.
  880. if (isLambdaCallOperator(MD) &&
  881. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  882. SkippedChecks.set(SanitizerKind::Null, true);
  883. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  884. : TCK_MemberCall,
  885. Loc, CXXABIThisValue, ThisTy,
  886. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  887. SkippedChecks);
  888. }
  889. }
  890. // If any of the arguments have a variably modified type, make sure to
  891. // emit the type size.
  892. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  893. i != e; ++i) {
  894. const VarDecl *VD = *i;
  895. // Dig out the type as written from ParmVarDecls; it's unclear whether
  896. // the standard (C99 6.9.1p10) requires this, but we're following the
  897. // precedent set by gcc.
  898. QualType Ty;
  899. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  900. Ty = PVD->getOriginalType();
  901. else
  902. Ty = VD->getType();
  903. if (Ty->isVariablyModifiedType())
  904. EmitVariablyModifiedType(Ty);
  905. }
  906. // Emit a location at the end of the prologue.
  907. if (CGDebugInfo *DI = getDebugInfo())
  908. DI->EmitLocation(Builder, StartLoc);
  909. // TODO: Do we need to handle this in two places like we do with
  910. // target-features/target-cpu?
  911. if (CurFuncDecl)
  912. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  913. LargestVectorWidth = VecWidth->getVectorWidth();
  914. }
  915. void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
  916. incrementProfileCounter(Body);
  917. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  918. EmitCompoundStmtWithoutScope(*S);
  919. else
  920. EmitStmt(Body);
  921. }
  922. /// When instrumenting to collect profile data, the counts for some blocks
  923. /// such as switch cases need to not include the fall-through counts, so
  924. /// emit a branch around the instrumentation code. When not instrumenting,
  925. /// this just calls EmitBlock().
  926. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  927. const Stmt *S) {
  928. llvm::BasicBlock *SkipCountBB = nullptr;
  929. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  930. // When instrumenting for profiling, the fallthrough to certain
  931. // statements needs to skip over the instrumentation code so that we
  932. // get an accurate count.
  933. SkipCountBB = createBasicBlock("skipcount");
  934. EmitBranch(SkipCountBB);
  935. }
  936. EmitBlock(BB);
  937. uint64_t CurrentCount = getCurrentProfileCount();
  938. incrementProfileCounter(S);
  939. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  940. if (SkipCountBB)
  941. EmitBlock(SkipCountBB);
  942. }
  943. /// Tries to mark the given function nounwind based on the
  944. /// non-existence of any throwing calls within it. We believe this is
  945. /// lightweight enough to do at -O0.
  946. static void TryMarkNoThrow(llvm::Function *F) {
  947. // LLVM treats 'nounwind' on a function as part of the type, so we
  948. // can't do this on functions that can be overwritten.
  949. if (F->isInterposable()) return;
  950. for (llvm::BasicBlock &BB : *F)
  951. for (llvm::Instruction &I : BB)
  952. if (I.mayThrow())
  953. return;
  954. F->setDoesNotThrow();
  955. }
  956. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  957. FunctionArgList &Args) {
  958. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  959. QualType ResTy = FD->getReturnType();
  960. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  961. if (MD && MD->isInstance()) {
  962. if (CGM.getCXXABI().HasThisReturn(GD))
  963. ResTy = MD->getThisType();
  964. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  965. ResTy = CGM.getContext().VoidPtrTy;
  966. CGM.getCXXABI().buildThisParam(*this, Args);
  967. }
  968. // The base version of an inheriting constructor whose constructed base is a
  969. // virtual base is not passed any arguments (because it doesn't actually call
  970. // the inherited constructor).
  971. bool PassedParams = true;
  972. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  973. if (auto Inherited = CD->getInheritedConstructor())
  974. PassedParams =
  975. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  976. if (PassedParams) {
  977. for (auto *Param : FD->parameters()) {
  978. Args.push_back(Param);
  979. if (!Param->hasAttr<PassObjectSizeAttr>())
  980. continue;
  981. auto *Implicit = ImplicitParamDecl::Create(
  982. getContext(), Param->getDeclContext(), Param->getLocation(),
  983. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  984. SizeArguments[Param] = Implicit;
  985. Args.push_back(Implicit);
  986. }
  987. }
  988. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  989. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  990. return ResTy;
  991. }
  992. static bool
  993. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  994. const ASTContext &Context) {
  995. QualType T = FD->getReturnType();
  996. // Avoid the optimization for functions that return a record type with a
  997. // trivial destructor or another trivially copyable type.
  998. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  999. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1000. return !ClassDecl->hasTrivialDestructor();
  1001. }
  1002. return !T.isTriviallyCopyableType(Context);
  1003. }
  1004. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1005. const CGFunctionInfo &FnInfo) {
  1006. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1007. CurGD = GD;
  1008. FunctionArgList Args;
  1009. QualType ResTy = BuildFunctionArgList(GD, Args);
  1010. // Check if we should generate debug info for this function.
  1011. if (FD->hasAttr<NoDebugAttr>())
  1012. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1013. // The function might not have a body if we're generating thunks for a
  1014. // function declaration.
  1015. SourceRange BodyRange;
  1016. if (Stmt *Body = FD->getBody())
  1017. BodyRange = Body->getSourceRange();
  1018. else
  1019. BodyRange = FD->getLocation();
  1020. CurEHLocation = BodyRange.getEnd();
  1021. // Use the location of the start of the function to determine where
  1022. // the function definition is located. By default use the location
  1023. // of the declaration as the location for the subprogram. A function
  1024. // may lack a declaration in the source code if it is created by code
  1025. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1026. SourceLocation Loc = FD->getLocation();
  1027. // If this is a function specialization then use the pattern body
  1028. // as the location for the function.
  1029. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1030. if (SpecDecl->hasBody(SpecDecl))
  1031. Loc = SpecDecl->getLocation();
  1032. Stmt *Body = FD->getBody();
  1033. // Initialize helper which will detect jumps which can cause invalid lifetime
  1034. // markers.
  1035. if (Body && ShouldEmitLifetimeMarkers)
  1036. Bypasses.Init(Body);
  1037. // Emit the standard function prologue.
  1038. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1039. // Generate the body of the function.
  1040. PGO.assignRegionCounters(GD, CurFn);
  1041. if (isa<CXXDestructorDecl>(FD))
  1042. EmitDestructorBody(Args);
  1043. else if (isa<CXXConstructorDecl>(FD))
  1044. EmitConstructorBody(Args);
  1045. else if (getLangOpts().CUDA &&
  1046. !getLangOpts().CUDAIsDevice &&
  1047. FD->hasAttr<CUDAGlobalAttr>())
  1048. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1049. else if (isa<CXXMethodDecl>(FD) &&
  1050. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1051. // The lambda static invoker function is special, because it forwards or
  1052. // clones the body of the function call operator (but is actually static).
  1053. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1054. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1055. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1056. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1057. // Implicit copy-assignment gets the same special treatment as implicit
  1058. // copy-constructors.
  1059. emitImplicitAssignmentOperatorBody(Args);
  1060. } else if (Body) {
  1061. EmitFunctionBody(Body);
  1062. } else
  1063. llvm_unreachable("no definition for emitted function");
  1064. // C++11 [stmt.return]p2:
  1065. // Flowing off the end of a function [...] results in undefined behavior in
  1066. // a value-returning function.
  1067. // C11 6.9.1p12:
  1068. // If the '}' that terminates a function is reached, and the value of the
  1069. // function call is used by the caller, the behavior is undefined.
  1070. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1071. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1072. bool ShouldEmitUnreachable =
  1073. CGM.getCodeGenOpts().StrictReturn ||
  1074. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1075. if (SanOpts.has(SanitizerKind::Return)) {
  1076. SanitizerScope SanScope(this);
  1077. llvm::Value *IsFalse = Builder.getFalse();
  1078. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1079. SanitizerHandler::MissingReturn,
  1080. EmitCheckSourceLocation(FD->getLocation()), None);
  1081. } else if (ShouldEmitUnreachable) {
  1082. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1083. EmitTrapCall(llvm::Intrinsic::trap);
  1084. }
  1085. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1086. Builder.CreateUnreachable();
  1087. Builder.ClearInsertionPoint();
  1088. }
  1089. }
  1090. // Emit the standard function epilogue.
  1091. FinishFunction(BodyRange.getEnd());
  1092. // If we haven't marked the function nothrow through other means, do
  1093. // a quick pass now to see if we can.
  1094. if (!CurFn->doesNotThrow())
  1095. TryMarkNoThrow(CurFn);
  1096. }
  1097. /// ContainsLabel - Return true if the statement contains a label in it. If
  1098. /// this statement is not executed normally, it not containing a label means
  1099. /// that we can just remove the code.
  1100. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1101. // Null statement, not a label!
  1102. if (!S) return false;
  1103. // If this is a label, we have to emit the code, consider something like:
  1104. // if (0) { ... foo: bar(); } goto foo;
  1105. //
  1106. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1107. // can't jump to one from outside their declared region.
  1108. if (isa<LabelStmt>(S))
  1109. return true;
  1110. // If this is a case/default statement, and we haven't seen a switch, we have
  1111. // to emit the code.
  1112. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1113. return true;
  1114. // If this is a switch statement, we want to ignore cases below it.
  1115. if (isa<SwitchStmt>(S))
  1116. IgnoreCaseStmts = true;
  1117. // Scan subexpressions for verboten labels.
  1118. for (const Stmt *SubStmt : S->children())
  1119. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1120. return true;
  1121. return false;
  1122. }
  1123. /// containsBreak - Return true if the statement contains a break out of it.
  1124. /// If the statement (recursively) contains a switch or loop with a break
  1125. /// inside of it, this is fine.
  1126. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1127. // Null statement, not a label!
  1128. if (!S) return false;
  1129. // If this is a switch or loop that defines its own break scope, then we can
  1130. // include it and anything inside of it.
  1131. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1132. isa<ForStmt>(S))
  1133. return false;
  1134. if (isa<BreakStmt>(S))
  1135. return true;
  1136. // Scan subexpressions for verboten breaks.
  1137. for (const Stmt *SubStmt : S->children())
  1138. if (containsBreak(SubStmt))
  1139. return true;
  1140. return false;
  1141. }
  1142. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1143. if (!S) return false;
  1144. // Some statement kinds add a scope and thus never add a decl to the current
  1145. // scope. Note, this list is longer than the list of statements that might
  1146. // have an unscoped decl nested within them, but this way is conservatively
  1147. // correct even if more statement kinds are added.
  1148. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1149. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1150. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1151. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1152. return false;
  1153. if (isa<DeclStmt>(S))
  1154. return true;
  1155. for (const Stmt *SubStmt : S->children())
  1156. if (mightAddDeclToScope(SubStmt))
  1157. return true;
  1158. return false;
  1159. }
  1160. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1161. /// to a constant, or if it does but contains a label, return false. If it
  1162. /// constant folds return true and set the boolean result in Result.
  1163. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1164. bool &ResultBool,
  1165. bool AllowLabels) {
  1166. llvm::APSInt ResultInt;
  1167. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1168. return false;
  1169. ResultBool = ResultInt.getBoolValue();
  1170. return true;
  1171. }
  1172. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1173. /// to a constant, or if it does but contains a label, return false. If it
  1174. /// constant folds return true and set the folded value.
  1175. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1176. llvm::APSInt &ResultInt,
  1177. bool AllowLabels) {
  1178. // FIXME: Rename and handle conversion of other evaluatable things
  1179. // to bool.
  1180. Expr::EvalResult Result;
  1181. if (!Cond->EvaluateAsInt(Result, getContext()))
  1182. return false; // Not foldable, not integer or not fully evaluatable.
  1183. llvm::APSInt Int = Result.Val.getInt();
  1184. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1185. return false; // Contains a label.
  1186. ResultInt = Int;
  1187. return true;
  1188. }
  1189. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1190. /// statement) to the specified blocks. Based on the condition, this might try
  1191. /// to simplify the codegen of the conditional based on the branch.
  1192. ///
  1193. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1194. llvm::BasicBlock *TrueBlock,
  1195. llvm::BasicBlock *FalseBlock,
  1196. uint64_t TrueCount) {
  1197. Cond = Cond->IgnoreParens();
  1198. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1199. // Handle X && Y in a condition.
  1200. if (CondBOp->getOpcode() == BO_LAnd) {
  1201. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1202. // folded if the case was simple enough.
  1203. bool ConstantBool = false;
  1204. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1205. ConstantBool) {
  1206. // br(1 && X) -> br(X).
  1207. incrementProfileCounter(CondBOp);
  1208. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1209. TrueCount);
  1210. }
  1211. // If we have "X && 1", simplify the code to use an uncond branch.
  1212. // "X && 0" would have been constant folded to 0.
  1213. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1214. ConstantBool) {
  1215. // br(X && 1) -> br(X).
  1216. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1217. TrueCount);
  1218. }
  1219. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1220. // want to jump to the FalseBlock.
  1221. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1222. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1223. // can be propagated to that branch.
  1224. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1225. ConditionalEvaluation eval(*this);
  1226. {
  1227. ApplyDebugLocation DL(*this, Cond);
  1228. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1229. EmitBlock(LHSTrue);
  1230. }
  1231. incrementProfileCounter(CondBOp);
  1232. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1233. // Any temporaries created here are conditional.
  1234. eval.begin(*this);
  1235. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1236. eval.end(*this);
  1237. return;
  1238. }
  1239. if (CondBOp->getOpcode() == BO_LOr) {
  1240. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1241. // folded if the case was simple enough.
  1242. bool ConstantBool = false;
  1243. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1244. !ConstantBool) {
  1245. // br(0 || X) -> br(X).
  1246. incrementProfileCounter(CondBOp);
  1247. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1248. TrueCount);
  1249. }
  1250. // If we have "X || 0", simplify the code to use an uncond branch.
  1251. // "X || 1" would have been constant folded to 1.
  1252. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1253. !ConstantBool) {
  1254. // br(X || 0) -> br(X).
  1255. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1256. TrueCount);
  1257. }
  1258. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1259. // want to jump to the TrueBlock.
  1260. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1261. // We have the count for entry to the RHS and for the whole expression
  1262. // being true, so we can divy up True count between the short circuit and
  1263. // the RHS.
  1264. uint64_t LHSCount =
  1265. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1266. uint64_t RHSCount = TrueCount - LHSCount;
  1267. ConditionalEvaluation eval(*this);
  1268. {
  1269. ApplyDebugLocation DL(*this, Cond);
  1270. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1271. EmitBlock(LHSFalse);
  1272. }
  1273. incrementProfileCounter(CondBOp);
  1274. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1275. // Any temporaries created here are conditional.
  1276. eval.begin(*this);
  1277. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1278. eval.end(*this);
  1279. return;
  1280. }
  1281. }
  1282. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1283. // br(!x, t, f) -> br(x, f, t)
  1284. if (CondUOp->getOpcode() == UO_LNot) {
  1285. // Negate the count.
  1286. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1287. // Negate the condition and swap the destination blocks.
  1288. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1289. FalseCount);
  1290. }
  1291. }
  1292. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1293. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1294. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1295. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1296. ConditionalEvaluation cond(*this);
  1297. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1298. getProfileCount(CondOp));
  1299. // When computing PGO branch weights, we only know the overall count for
  1300. // the true block. This code is essentially doing tail duplication of the
  1301. // naive code-gen, introducing new edges for which counts are not
  1302. // available. Divide the counts proportionally between the LHS and RHS of
  1303. // the conditional operator.
  1304. uint64_t LHSScaledTrueCount = 0;
  1305. if (TrueCount) {
  1306. double LHSRatio =
  1307. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1308. LHSScaledTrueCount = TrueCount * LHSRatio;
  1309. }
  1310. cond.begin(*this);
  1311. EmitBlock(LHSBlock);
  1312. incrementProfileCounter(CondOp);
  1313. {
  1314. ApplyDebugLocation DL(*this, Cond);
  1315. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1316. LHSScaledTrueCount);
  1317. }
  1318. cond.end(*this);
  1319. cond.begin(*this);
  1320. EmitBlock(RHSBlock);
  1321. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1322. TrueCount - LHSScaledTrueCount);
  1323. cond.end(*this);
  1324. return;
  1325. }
  1326. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1327. // Conditional operator handling can give us a throw expression as a
  1328. // condition for a case like:
  1329. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1330. // Fold this to:
  1331. // br(c, throw x, br(y, t, f))
  1332. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1333. return;
  1334. }
  1335. // If the branch has a condition wrapped by __builtin_unpredictable,
  1336. // create metadata that specifies that the branch is unpredictable.
  1337. // Don't bother if not optimizing because that metadata would not be used.
  1338. llvm::MDNode *Unpredictable = nullptr;
  1339. auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
  1340. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1341. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1342. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1343. llvm::MDBuilder MDHelper(getLLVMContext());
  1344. Unpredictable = MDHelper.createUnpredictable();
  1345. }
  1346. }
  1347. // Create branch weights based on the number of times we get here and the
  1348. // number of times the condition should be true.
  1349. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1350. llvm::MDNode *Weights =
  1351. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1352. // Emit the code with the fully general case.
  1353. llvm::Value *CondV;
  1354. {
  1355. ApplyDebugLocation DL(*this, Cond);
  1356. CondV = EvaluateExprAsBool(Cond);
  1357. }
  1358. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1359. }
  1360. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1361. /// specified stmt yet.
  1362. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1363. CGM.ErrorUnsupported(S, Type);
  1364. }
  1365. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1366. /// variable-length array whose elements have a non-zero bit-pattern.
  1367. ///
  1368. /// \param baseType the inner-most element type of the array
  1369. /// \param src - a char* pointing to the bit-pattern for a single
  1370. /// base element of the array
  1371. /// \param sizeInChars - the total size of the VLA, in chars
  1372. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1373. Address dest, Address src,
  1374. llvm::Value *sizeInChars) {
  1375. CGBuilderTy &Builder = CGF.Builder;
  1376. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1377. llvm::Value *baseSizeInChars
  1378. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1379. Address begin =
  1380. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1381. llvm::Value *end =
  1382. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1383. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1384. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1385. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1386. // Make a loop over the VLA. C99 guarantees that the VLA element
  1387. // count must be nonzero.
  1388. CGF.EmitBlock(loopBB);
  1389. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1390. cur->addIncoming(begin.getPointer(), originBB);
  1391. CharUnits curAlign =
  1392. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1393. // memcpy the individual element bit-pattern.
  1394. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1395. /*volatile*/ false);
  1396. // Go to the next element.
  1397. llvm::Value *next =
  1398. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1399. // Leave if that's the end of the VLA.
  1400. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1401. Builder.CreateCondBr(done, contBB, loopBB);
  1402. cur->addIncoming(next, loopBB);
  1403. CGF.EmitBlock(contBB);
  1404. }
  1405. void
  1406. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1407. // Ignore empty classes in C++.
  1408. if (getLangOpts().CPlusPlus) {
  1409. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1410. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1411. return;
  1412. }
  1413. }
  1414. // Cast the dest ptr to the appropriate i8 pointer type.
  1415. if (DestPtr.getElementType() != Int8Ty)
  1416. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1417. // Get size and alignment info for this aggregate.
  1418. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1419. llvm::Value *SizeVal;
  1420. const VariableArrayType *vla;
  1421. // Don't bother emitting a zero-byte memset.
  1422. if (size.isZero()) {
  1423. // But note that getTypeInfo returns 0 for a VLA.
  1424. if (const VariableArrayType *vlaType =
  1425. dyn_cast_or_null<VariableArrayType>(
  1426. getContext().getAsArrayType(Ty))) {
  1427. auto VlaSize = getVLASize(vlaType);
  1428. SizeVal = VlaSize.NumElts;
  1429. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1430. if (!eltSize.isOne())
  1431. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1432. vla = vlaType;
  1433. } else {
  1434. return;
  1435. }
  1436. } else {
  1437. SizeVal = CGM.getSize(size);
  1438. vla = nullptr;
  1439. }
  1440. // If the type contains a pointer to data member we can't memset it to zero.
  1441. // Instead, create a null constant and copy it to the destination.
  1442. // TODO: there are other patterns besides zero that we can usefully memset,
  1443. // like -1, which happens to be the pattern used by member-pointers.
  1444. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1445. // For a VLA, emit a single element, then splat that over the VLA.
  1446. if (vla) Ty = getContext().getBaseElementType(vla);
  1447. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1448. llvm::GlobalVariable *NullVariable =
  1449. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1450. /*isConstant=*/true,
  1451. llvm::GlobalVariable::PrivateLinkage,
  1452. NullConstant, Twine());
  1453. CharUnits NullAlign = DestPtr.getAlignment();
  1454. NullVariable->setAlignment(NullAlign.getAsAlign());
  1455. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1456. NullAlign);
  1457. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1458. // Get and call the appropriate llvm.memcpy overload.
  1459. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1460. return;
  1461. }
  1462. // Otherwise, just memset the whole thing to zero. This is legal
  1463. // because in LLVM, all default initializers (other than the ones we just
  1464. // handled above) are guaranteed to have a bit pattern of all zeros.
  1465. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1466. }
  1467. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1468. // Make sure that there is a block for the indirect goto.
  1469. if (!IndirectBranch)
  1470. GetIndirectGotoBlock();
  1471. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1472. // Make sure the indirect branch includes all of the address-taken blocks.
  1473. IndirectBranch->addDestination(BB);
  1474. return llvm::BlockAddress::get(CurFn, BB);
  1475. }
  1476. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1477. // If we already made the indirect branch for indirect goto, return its block.
  1478. if (IndirectBranch) return IndirectBranch->getParent();
  1479. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1480. // Create the PHI node that indirect gotos will add entries to.
  1481. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1482. "indirect.goto.dest");
  1483. // Create the indirect branch instruction.
  1484. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1485. return IndirectBranch->getParent();
  1486. }
  1487. /// Computes the length of an array in elements, as well as the base
  1488. /// element type and a properly-typed first element pointer.
  1489. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1490. QualType &baseType,
  1491. Address &addr) {
  1492. const ArrayType *arrayType = origArrayType;
  1493. // If it's a VLA, we have to load the stored size. Note that
  1494. // this is the size of the VLA in bytes, not its size in elements.
  1495. llvm::Value *numVLAElements = nullptr;
  1496. if (isa<VariableArrayType>(arrayType)) {
  1497. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1498. // Walk into all VLAs. This doesn't require changes to addr,
  1499. // which has type T* where T is the first non-VLA element type.
  1500. do {
  1501. QualType elementType = arrayType->getElementType();
  1502. arrayType = getContext().getAsArrayType(elementType);
  1503. // If we only have VLA components, 'addr' requires no adjustment.
  1504. if (!arrayType) {
  1505. baseType = elementType;
  1506. return numVLAElements;
  1507. }
  1508. } while (isa<VariableArrayType>(arrayType));
  1509. // We get out here only if we find a constant array type
  1510. // inside the VLA.
  1511. }
  1512. // We have some number of constant-length arrays, so addr should
  1513. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1514. // down to the first element of addr.
  1515. SmallVector<llvm::Value*, 8> gepIndices;
  1516. // GEP down to the array type.
  1517. llvm::ConstantInt *zero = Builder.getInt32(0);
  1518. gepIndices.push_back(zero);
  1519. uint64_t countFromCLAs = 1;
  1520. QualType eltType;
  1521. llvm::ArrayType *llvmArrayType =
  1522. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1523. while (llvmArrayType) {
  1524. assert(isa<ConstantArrayType>(arrayType));
  1525. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1526. == llvmArrayType->getNumElements());
  1527. gepIndices.push_back(zero);
  1528. countFromCLAs *= llvmArrayType->getNumElements();
  1529. eltType = arrayType->getElementType();
  1530. llvmArrayType =
  1531. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1532. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1533. assert((!llvmArrayType || arrayType) &&
  1534. "LLVM and Clang types are out-of-synch");
  1535. }
  1536. if (arrayType) {
  1537. // From this point onwards, the Clang array type has been emitted
  1538. // as some other type (probably a packed struct). Compute the array
  1539. // size, and just emit the 'begin' expression as a bitcast.
  1540. while (arrayType) {
  1541. countFromCLAs *=
  1542. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1543. eltType = arrayType->getElementType();
  1544. arrayType = getContext().getAsArrayType(eltType);
  1545. }
  1546. llvm::Type *baseType = ConvertType(eltType);
  1547. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1548. } else {
  1549. // Create the actual GEP.
  1550. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1551. gepIndices, "array.begin"),
  1552. addr.getAlignment());
  1553. }
  1554. baseType = eltType;
  1555. llvm::Value *numElements
  1556. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1557. // If we had any VLA dimensions, factor them in.
  1558. if (numVLAElements)
  1559. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1560. return numElements;
  1561. }
  1562. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1563. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1564. assert(vla && "type was not a variable array type!");
  1565. return getVLASize(vla);
  1566. }
  1567. CodeGenFunction::VlaSizePair
  1568. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1569. // The number of elements so far; always size_t.
  1570. llvm::Value *numElements = nullptr;
  1571. QualType elementType;
  1572. do {
  1573. elementType = type->getElementType();
  1574. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1575. assert(vlaSize && "no size for VLA!");
  1576. assert(vlaSize->getType() == SizeTy);
  1577. if (!numElements) {
  1578. numElements = vlaSize;
  1579. } else {
  1580. // It's undefined behavior if this wraps around, so mark it that way.
  1581. // FIXME: Teach -fsanitize=undefined to trap this.
  1582. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1583. }
  1584. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1585. return { numElements, elementType };
  1586. }
  1587. CodeGenFunction::VlaSizePair
  1588. CodeGenFunction::getVLAElements1D(QualType type) {
  1589. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1590. assert(vla && "type was not a variable array type!");
  1591. return getVLAElements1D(vla);
  1592. }
  1593. CodeGenFunction::VlaSizePair
  1594. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1595. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1596. assert(VlaSize && "no size for VLA!");
  1597. assert(VlaSize->getType() == SizeTy);
  1598. return { VlaSize, Vla->getElementType() };
  1599. }
  1600. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1601. assert(type->isVariablyModifiedType() &&
  1602. "Must pass variably modified type to EmitVLASizes!");
  1603. EnsureInsertPoint();
  1604. // We're going to walk down into the type and look for VLA
  1605. // expressions.
  1606. do {
  1607. assert(type->isVariablyModifiedType());
  1608. const Type *ty = type.getTypePtr();
  1609. switch (ty->getTypeClass()) {
  1610. #define TYPE(Class, Base)
  1611. #define ABSTRACT_TYPE(Class, Base)
  1612. #define NON_CANONICAL_TYPE(Class, Base)
  1613. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1614. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1615. #include "clang/AST/TypeNodes.inc"
  1616. llvm_unreachable("unexpected dependent type!");
  1617. // These types are never variably-modified.
  1618. case Type::Builtin:
  1619. case Type::Complex:
  1620. case Type::Vector:
  1621. case Type::ExtVector:
  1622. case Type::Record:
  1623. case Type::Enum:
  1624. case Type::Elaborated:
  1625. case Type::TemplateSpecialization:
  1626. case Type::ObjCTypeParam:
  1627. case Type::ObjCObject:
  1628. case Type::ObjCInterface:
  1629. case Type::ObjCObjectPointer:
  1630. llvm_unreachable("type class is never variably-modified!");
  1631. case Type::Adjusted:
  1632. type = cast<AdjustedType>(ty)->getAdjustedType();
  1633. break;
  1634. case Type::Decayed:
  1635. type = cast<DecayedType>(ty)->getPointeeType();
  1636. break;
  1637. case Type::Pointer:
  1638. type = cast<PointerType>(ty)->getPointeeType();
  1639. break;
  1640. case Type::BlockPointer:
  1641. type = cast<BlockPointerType>(ty)->getPointeeType();
  1642. break;
  1643. case Type::LValueReference:
  1644. case Type::RValueReference:
  1645. type = cast<ReferenceType>(ty)->getPointeeType();
  1646. break;
  1647. case Type::MemberPointer:
  1648. type = cast<MemberPointerType>(ty)->getPointeeType();
  1649. break;
  1650. case Type::ConstantArray:
  1651. case Type::IncompleteArray:
  1652. // Losing element qualification here is fine.
  1653. type = cast<ArrayType>(ty)->getElementType();
  1654. break;
  1655. case Type::VariableArray: {
  1656. // Losing element qualification here is fine.
  1657. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1658. // Unknown size indication requires no size computation.
  1659. // Otherwise, evaluate and record it.
  1660. if (const Expr *size = vat->getSizeExpr()) {
  1661. // It's possible that we might have emitted this already,
  1662. // e.g. with a typedef and a pointer to it.
  1663. llvm::Value *&entry = VLASizeMap[size];
  1664. if (!entry) {
  1665. llvm::Value *Size = EmitScalarExpr(size);
  1666. // C11 6.7.6.2p5:
  1667. // If the size is an expression that is not an integer constant
  1668. // expression [...] each time it is evaluated it shall have a value
  1669. // greater than zero.
  1670. if (SanOpts.has(SanitizerKind::VLABound) &&
  1671. size->getType()->isSignedIntegerType()) {
  1672. SanitizerScope SanScope(this);
  1673. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1674. llvm::Constant *StaticArgs[] = {
  1675. EmitCheckSourceLocation(size->getBeginLoc()),
  1676. EmitCheckTypeDescriptor(size->getType())};
  1677. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1678. SanitizerKind::VLABound),
  1679. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1680. }
  1681. // Always zexting here would be wrong if it weren't
  1682. // undefined behavior to have a negative bound.
  1683. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1684. }
  1685. }
  1686. type = vat->getElementType();
  1687. break;
  1688. }
  1689. case Type::FunctionProto:
  1690. case Type::FunctionNoProto:
  1691. type = cast<FunctionType>(ty)->getReturnType();
  1692. break;
  1693. case Type::Paren:
  1694. case Type::TypeOf:
  1695. case Type::UnaryTransform:
  1696. case Type::Attributed:
  1697. case Type::SubstTemplateTypeParm:
  1698. case Type::PackExpansion:
  1699. case Type::MacroQualified:
  1700. // Keep walking after single level desugaring.
  1701. type = type.getSingleStepDesugaredType(getContext());
  1702. break;
  1703. case Type::Typedef:
  1704. case Type::Decltype:
  1705. case Type::Auto:
  1706. case Type::DeducedTemplateSpecialization:
  1707. // Stop walking: nothing to do.
  1708. return;
  1709. case Type::TypeOfExpr:
  1710. // Stop walking: emit typeof expression.
  1711. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1712. return;
  1713. case Type::Atomic:
  1714. type = cast<AtomicType>(ty)->getValueType();
  1715. break;
  1716. case Type::Pipe:
  1717. type = cast<PipeType>(ty)->getElementType();
  1718. break;
  1719. }
  1720. } while (type->isVariablyModifiedType());
  1721. }
  1722. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1723. if (getContext().getBuiltinVaListType()->isArrayType())
  1724. return EmitPointerWithAlignment(E);
  1725. return EmitLValue(E).getAddress();
  1726. }
  1727. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1728. return EmitLValue(E).getAddress();
  1729. }
  1730. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1731. const APValue &Init) {
  1732. assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
  1733. if (CGDebugInfo *Dbg = getDebugInfo())
  1734. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1735. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1736. }
  1737. CodeGenFunction::PeepholeProtection
  1738. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1739. // At the moment, the only aggressive peephole we do in IR gen
  1740. // is trunc(zext) folding, but if we add more, we can easily
  1741. // extend this protection.
  1742. if (!rvalue.isScalar()) return PeepholeProtection();
  1743. llvm::Value *value = rvalue.getScalarVal();
  1744. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1745. // Just make an extra bitcast.
  1746. assert(HaveInsertPoint());
  1747. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1748. Builder.GetInsertBlock());
  1749. PeepholeProtection protection;
  1750. protection.Inst = inst;
  1751. return protection;
  1752. }
  1753. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1754. if (!protection.Inst) return;
  1755. // In theory, we could try to duplicate the peepholes now, but whatever.
  1756. protection.Inst->eraseFromParent();
  1757. }
  1758. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1759. QualType Ty, SourceLocation Loc,
  1760. SourceLocation AssumptionLoc,
  1761. llvm::Value *Alignment,
  1762. llvm::Value *OffsetValue) {
  1763. llvm::Value *TheCheck;
  1764. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1765. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1766. if (SanOpts.has(SanitizerKind::Alignment)) {
  1767. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1768. OffsetValue, TheCheck, Assumption);
  1769. }
  1770. }
  1771. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1772. const Expr *E,
  1773. SourceLocation AssumptionLoc,
  1774. llvm::Value *Alignment,
  1775. llvm::Value *OffsetValue) {
  1776. if (auto *CE = dyn_cast<CastExpr>(E))
  1777. E = CE->getSubExprAsWritten();
  1778. QualType Ty = E->getType();
  1779. SourceLocation Loc = E->getExprLoc();
  1780. EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1781. OffsetValue);
  1782. }
  1783. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  1784. llvm::Value *AnnotatedVal,
  1785. StringRef AnnotationStr,
  1786. SourceLocation Location) {
  1787. llvm::Value *Args[4] = {
  1788. AnnotatedVal,
  1789. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1790. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1791. CGM.EmitAnnotationLineNo(Location)
  1792. };
  1793. return Builder.CreateCall(AnnotationFn, Args);
  1794. }
  1795. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1796. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1797. // FIXME We create a new bitcast for every annotation because that's what
  1798. // llvm-gcc was doing.
  1799. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1800. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1801. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1802. I->getAnnotation(), D->getLocation());
  1803. }
  1804. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1805. Address Addr) {
  1806. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1807. llvm::Value *V = Addr.getPointer();
  1808. llvm::Type *VTy = V->getType();
  1809. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1810. CGM.Int8PtrTy);
  1811. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1812. // FIXME Always emit the cast inst so we can differentiate between
  1813. // annotation on the first field of a struct and annotation on the struct
  1814. // itself.
  1815. if (VTy != CGM.Int8PtrTy)
  1816. V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
  1817. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1818. V = Builder.CreateBitCast(V, VTy);
  1819. }
  1820. return Address(V, Addr.getAlignment());
  1821. }
  1822. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1823. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1824. : CGF(CGF) {
  1825. assert(!CGF->IsSanitizerScope);
  1826. CGF->IsSanitizerScope = true;
  1827. }
  1828. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1829. CGF->IsSanitizerScope = false;
  1830. }
  1831. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1832. const llvm::Twine &Name,
  1833. llvm::BasicBlock *BB,
  1834. llvm::BasicBlock::iterator InsertPt) const {
  1835. LoopStack.InsertHelper(I);
  1836. if (IsSanitizerScope)
  1837. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1838. }
  1839. void CGBuilderInserter::InsertHelper(
  1840. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1841. llvm::BasicBlock::iterator InsertPt) const {
  1842. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1843. if (CGF)
  1844. CGF->InsertHelper(I, Name, BB, InsertPt);
  1845. }
  1846. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1847. CodeGenModule &CGM, const FunctionDecl *FD,
  1848. std::string &FirstMissing) {
  1849. // If there aren't any required features listed then go ahead and return.
  1850. if (ReqFeatures.empty())
  1851. return false;
  1852. // Now build up the set of caller features and verify that all the required
  1853. // features are there.
  1854. llvm::StringMap<bool> CallerFeatureMap;
  1855. CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
  1856. // If we have at least one of the features in the feature list return
  1857. // true, otherwise return false.
  1858. return std::all_of(
  1859. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1860. SmallVector<StringRef, 1> OrFeatures;
  1861. Feature.split(OrFeatures, '|');
  1862. return llvm::any_of(OrFeatures, [&](StringRef Feature) {
  1863. if (!CallerFeatureMap.lookup(Feature)) {
  1864. FirstMissing = Feature.str();
  1865. return false;
  1866. }
  1867. return true;
  1868. });
  1869. });
  1870. }
  1871. // Emits an error if we don't have a valid set of target features for the
  1872. // called function.
  1873. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1874. const FunctionDecl *TargetDecl) {
  1875. return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
  1876. }
  1877. // Emits an error if we don't have a valid set of target features for the
  1878. // called function.
  1879. void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
  1880. const FunctionDecl *TargetDecl) {
  1881. // Early exit if this is an indirect call.
  1882. if (!TargetDecl)
  1883. return;
  1884. // Get the current enclosing function if it exists. If it doesn't
  1885. // we can't check the target features anyhow.
  1886. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
  1887. if (!FD)
  1888. return;
  1889. // Grab the required features for the call. For a builtin this is listed in
  1890. // the td file with the default cpu, for an always_inline function this is any
  1891. // listed cpu and any listed features.
  1892. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1893. std::string MissingFeature;
  1894. if (BuiltinID) {
  1895. SmallVector<StringRef, 1> ReqFeatures;
  1896. const char *FeatureList =
  1897. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1898. // Return if the builtin doesn't have any required features.
  1899. if (!FeatureList || StringRef(FeatureList) == "")
  1900. return;
  1901. StringRef(FeatureList).split(ReqFeatures, ',');
  1902. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1903. CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
  1904. << TargetDecl->getDeclName()
  1905. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1906. } else if (TargetDecl->hasAttr<TargetAttr>() ||
  1907. TargetDecl->hasAttr<CPUSpecificAttr>()) {
  1908. // Get the required features for the callee.
  1909. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  1910. TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
  1911. SmallVector<StringRef, 1> ReqFeatures;
  1912. llvm::StringMap<bool> CalleeFeatureMap;
  1913. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1914. for (const auto &F : ParsedAttr.Features) {
  1915. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  1916. ReqFeatures.push_back(StringRef(F).substr(1));
  1917. }
  1918. for (const auto &F : CalleeFeatureMap) {
  1919. // Only positive features are "required".
  1920. if (F.getValue())
  1921. ReqFeatures.push_back(F.getKey());
  1922. }
  1923. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1924. CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
  1925. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1926. }
  1927. }
  1928. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1929. if (!CGM.getCodeGenOpts().SanitizeStats)
  1930. return;
  1931. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1932. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1933. CGM.getSanStats().create(IRB, SSK);
  1934. }
  1935. llvm::Value *
  1936. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  1937. llvm::Value *Condition = nullptr;
  1938. if (!RO.Conditions.Architecture.empty())
  1939. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  1940. if (!RO.Conditions.Features.empty()) {
  1941. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  1942. Condition =
  1943. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  1944. }
  1945. return Condition;
  1946. }
  1947. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  1948. llvm::Function *Resolver,
  1949. CGBuilderTy &Builder,
  1950. llvm::Function *FuncToReturn,
  1951. bool SupportsIFunc) {
  1952. if (SupportsIFunc) {
  1953. Builder.CreateRet(FuncToReturn);
  1954. return;
  1955. }
  1956. llvm::SmallVector<llvm::Value *, 10> Args;
  1957. llvm::for_each(Resolver->args(),
  1958. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  1959. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  1960. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  1961. if (Resolver->getReturnType()->isVoidTy())
  1962. Builder.CreateRetVoid();
  1963. else
  1964. Builder.CreateRet(Result);
  1965. }
  1966. void CodeGenFunction::EmitMultiVersionResolver(
  1967. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  1968. assert((getContext().getTargetInfo().getTriple().getArch() ==
  1969. llvm::Triple::x86 ||
  1970. getContext().getTargetInfo().getTriple().getArch() ==
  1971. llvm::Triple::x86_64) &&
  1972. "Only implemented for x86 targets");
  1973. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  1974. // Main function's basic block.
  1975. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  1976. Builder.SetInsertPoint(CurBlock);
  1977. EmitX86CpuInit();
  1978. for (const MultiVersionResolverOption &RO : Options) {
  1979. Builder.SetInsertPoint(CurBlock);
  1980. llvm::Value *Condition = FormResolverCondition(RO);
  1981. // The 'default' or 'generic' case.
  1982. if (!Condition) {
  1983. assert(&RO == Options.end() - 1 &&
  1984. "Default or Generic case must be last");
  1985. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  1986. SupportsIFunc);
  1987. return;
  1988. }
  1989. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  1990. CGBuilderTy RetBuilder(*this, RetBlock);
  1991. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  1992. SupportsIFunc);
  1993. CurBlock = createBasicBlock("resolver_else", Resolver);
  1994. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  1995. }
  1996. // If no generic/default, emit an unreachable.
  1997. Builder.SetInsertPoint(CurBlock);
  1998. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  1999. TrapCall->setDoesNotReturn();
  2000. TrapCall->setDoesNotThrow();
  2001. Builder.CreateUnreachable();
  2002. Builder.ClearInsertionPoint();
  2003. }
  2004. // Loc - where the diagnostic will point, where in the source code this
  2005. // alignment has failed.
  2006. // SecondaryLoc - if present (will be present if sufficiently different from
  2007. // Loc), the diagnostic will additionally point a "Note:" to this location.
  2008. // It should be the location where the __attribute__((assume_aligned))
  2009. // was written e.g.
  2010. void CodeGenFunction::EmitAlignmentAssumptionCheck(
  2011. llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
  2012. SourceLocation SecondaryLoc, llvm::Value *Alignment,
  2013. llvm::Value *OffsetValue, llvm::Value *TheCheck,
  2014. llvm::Instruction *Assumption) {
  2015. assert(Assumption && isa<llvm::CallInst>(Assumption) &&
  2016. cast<llvm::CallInst>(Assumption)->getCalledValue() ==
  2017. llvm::Intrinsic::getDeclaration(
  2018. Builder.GetInsertBlock()->getParent()->getParent(),
  2019. llvm::Intrinsic::assume) &&
  2020. "Assumption should be a call to llvm.assume().");
  2021. assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
  2022. "Assumption should be the last instruction of the basic block, "
  2023. "since the basic block is still being generated.");
  2024. if (!SanOpts.has(SanitizerKind::Alignment))
  2025. return;
  2026. // Don't check pointers to volatile data. The behavior here is implementation-
  2027. // defined.
  2028. if (Ty->getPointeeType().isVolatileQualified())
  2029. return;
  2030. // We need to temorairly remove the assumption so we can insert the
  2031. // sanitizer check before it, else the check will be dropped by optimizations.
  2032. Assumption->removeFromParent();
  2033. {
  2034. SanitizerScope SanScope(this);
  2035. if (!OffsetValue)
  2036. OffsetValue = Builder.getInt1(0); // no offset.
  2037. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
  2038. EmitCheckSourceLocation(SecondaryLoc),
  2039. EmitCheckTypeDescriptor(Ty)};
  2040. llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
  2041. EmitCheckValue(Alignment),
  2042. EmitCheckValue(OffsetValue)};
  2043. EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
  2044. SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
  2045. }
  2046. // We are now in the (new, empty) "cont" basic block.
  2047. // Reintroduce the assumption.
  2048. Builder.Insert(Assumption);
  2049. // FIXME: Assumption still has it's original basic block as it's Parent.
  2050. }
  2051. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2052. if (CGDebugInfo *DI = getDebugInfo())
  2053. return DI->SourceLocToDebugLoc(Location);
  2054. return llvm::DebugLoc();
  2055. }