CodeGenFunction.cpp 91 KB

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