1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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 contains code to emit Stmt nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/PrettyStackTrace.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/MDBuilder.h"
28
29 using namespace clang;
30 using namespace CodeGen;
31
32 //===----------------------------------------------------------------------===//
33 // Statement Emission
34 //===----------------------------------------------------------------------===//
35
EmitStopPoint(const Stmt * S)36 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
37 if (CGDebugInfo *DI = getDebugInfo()) {
38 SourceLocation Loc;
39 Loc = S->getBeginLoc();
40 DI->EmitLocation(Builder, Loc);
41
42 LastStopPoint = Loc;
43 }
44 }
45
EmitStmt(const Stmt * S,ArrayRef<const Attr * > Attrs)46 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
47 assert(S && "Null statement?");
48 PGO.setCurrentStmt(S);
49
50 // These statements have their own debug info handling.
51 if (EmitSimpleStmt(S))
52 return;
53
54 // Check if we are generating unreachable code.
55 if (!HaveInsertPoint()) {
56 // If so, and the statement doesn't contain a label, then we do not need to
57 // generate actual code. This is safe because (1) the current point is
58 // unreachable, so we don't need to execute the code, and (2) we've already
59 // handled the statements which update internal data structures (like the
60 // local variable map) which could be used by subsequent statements.
61 if (!ContainsLabel(S)) {
62 // Verify that any decl statements were handled as simple, they may be in
63 // scope of subsequent reachable statements.
64 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
65 return;
66 }
67
68 // Otherwise, make a new block to hold the code.
69 EnsureInsertPoint();
70 }
71
72 // Generate a stoppoint if we are emitting debug info.
73 EmitStopPoint(S);
74
75 // Ignore all OpenMP directives except for simd if OpenMP with Simd is
76 // enabled.
77 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) {
78 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) {
79 EmitSimpleOMPExecutableDirective(*D);
80 return;
81 }
82 }
83
84 switch (S->getStmtClass()) {
85 case Stmt::NoStmtClass:
86 case Stmt::CXXCatchStmtClass:
87 case Stmt::SEHExceptStmtClass:
88 case Stmt::SEHFinallyStmtClass:
89 case Stmt::MSDependentExistsStmtClass:
90 llvm_unreachable("invalid statement class to emit generically");
91 case Stmt::NullStmtClass:
92 case Stmt::CompoundStmtClass:
93 case Stmt::DeclStmtClass:
94 case Stmt::LabelStmtClass:
95 case Stmt::AttributedStmtClass:
96 case Stmt::GotoStmtClass:
97 case Stmt::BreakStmtClass:
98 case Stmt::ContinueStmtClass:
99 case Stmt::DefaultStmtClass:
100 case Stmt::CaseStmtClass:
101 case Stmt::SEHLeaveStmtClass:
102 llvm_unreachable("should have emitted these statements as simple");
103
104 #define STMT(Type, Base)
105 #define ABSTRACT_STMT(Op)
106 #define EXPR(Type, Base) \
107 case Stmt::Type##Class:
108 #include "clang/AST/StmtNodes.inc"
109 {
110 // Remember the block we came in on.
111 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
112 assert(incoming && "expression emission must have an insertion point");
113
114 EmitIgnoredExpr(cast<Expr>(S));
115
116 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
117 assert(outgoing && "expression emission cleared block!");
118
119 // The expression emitters assume (reasonably!) that the insertion
120 // point is always set. To maintain that, the call-emission code
121 // for noreturn functions has to enter a new block with no
122 // predecessors. We want to kill that block and mark the current
123 // insertion point unreachable in the common case of a call like
124 // "exit();". Since expression emission doesn't otherwise create
125 // blocks with no predecessors, we can just test for that.
126 // However, we must be careful not to do this to our incoming
127 // block, because *statement* emission does sometimes create
128 // reachable blocks which will have no predecessors until later in
129 // the function. This occurs with, e.g., labels that are not
130 // reachable by fallthrough.
131 if (incoming != outgoing && outgoing->use_empty()) {
132 outgoing->eraseFromParent();
133 Builder.ClearInsertionPoint();
134 }
135 break;
136 }
137
138 case Stmt::IndirectGotoStmtClass:
139 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
140
141 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
142 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break;
143 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break;
144 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break;
145
146 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
147
148 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
149 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
150 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
151 case Stmt::CoroutineBodyStmtClass:
152 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S));
153 break;
154 case Stmt::CoreturnStmtClass:
155 EmitCoreturnStmt(cast<CoreturnStmt>(*S));
156 break;
157 case Stmt::CapturedStmtClass: {
158 const CapturedStmt *CS = cast<CapturedStmt>(S);
159 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
160 }
161 break;
162 case Stmt::ObjCAtTryStmtClass:
163 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
164 break;
165 case Stmt::ObjCAtCatchStmtClass:
166 llvm_unreachable(
167 "@catch statements should be handled by EmitObjCAtTryStmt");
168 case Stmt::ObjCAtFinallyStmtClass:
169 llvm_unreachable(
170 "@finally statements should be handled by EmitObjCAtTryStmt");
171 case Stmt::ObjCAtThrowStmtClass:
172 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
173 break;
174 case Stmt::ObjCAtSynchronizedStmtClass:
175 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
176 break;
177 case Stmt::ObjCForCollectionStmtClass:
178 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
179 break;
180 case Stmt::ObjCAutoreleasePoolStmtClass:
181 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
182 break;
183
184 case Stmt::CXXTryStmtClass:
185 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
186 break;
187 case Stmt::CXXForRangeStmtClass:
188 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs);
189 break;
190 case Stmt::SEHTryStmtClass:
191 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
192 break;
193 case Stmt::OMPParallelDirectiveClass:
194 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
195 break;
196 case Stmt::OMPSimdDirectiveClass:
197 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
198 break;
199 case Stmt::OMPForDirectiveClass:
200 EmitOMPForDirective(cast<OMPForDirective>(*S));
201 break;
202 case Stmt::OMPForSimdDirectiveClass:
203 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
204 break;
205 case Stmt::OMPSectionsDirectiveClass:
206 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
207 break;
208 case Stmt::OMPSectionDirectiveClass:
209 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
210 break;
211 case Stmt::OMPSingleDirectiveClass:
212 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
213 break;
214 case Stmt::OMPMasterDirectiveClass:
215 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
216 break;
217 case Stmt::OMPCriticalDirectiveClass:
218 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
219 break;
220 case Stmt::OMPParallelForDirectiveClass:
221 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
222 break;
223 case Stmt::OMPParallelForSimdDirectiveClass:
224 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
225 break;
226 case Stmt::OMPParallelSectionsDirectiveClass:
227 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
228 break;
229 case Stmt::OMPTaskDirectiveClass:
230 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
231 break;
232 case Stmt::OMPTaskyieldDirectiveClass:
233 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
234 break;
235 case Stmt::OMPBarrierDirectiveClass:
236 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
237 break;
238 case Stmt::OMPTaskwaitDirectiveClass:
239 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
240 break;
241 case Stmt::OMPTaskgroupDirectiveClass:
242 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
243 break;
244 case Stmt::OMPFlushDirectiveClass:
245 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
246 break;
247 case Stmt::OMPOrderedDirectiveClass:
248 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
249 break;
250 case Stmt::OMPAtomicDirectiveClass:
251 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
252 break;
253 case Stmt::OMPTargetDirectiveClass:
254 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
255 break;
256 case Stmt::OMPTeamsDirectiveClass:
257 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
258 break;
259 case Stmt::OMPCancellationPointDirectiveClass:
260 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
261 break;
262 case Stmt::OMPCancelDirectiveClass:
263 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
264 break;
265 case Stmt::OMPTargetDataDirectiveClass:
266 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
267 break;
268 case Stmt::OMPTargetEnterDataDirectiveClass:
269 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
270 break;
271 case Stmt::OMPTargetExitDataDirectiveClass:
272 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
273 break;
274 case Stmt::OMPTargetParallelDirectiveClass:
275 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
276 break;
277 case Stmt::OMPTargetParallelForDirectiveClass:
278 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
279 break;
280 case Stmt::OMPTaskLoopDirectiveClass:
281 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
282 break;
283 case Stmt::OMPTaskLoopSimdDirectiveClass:
284 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
285 break;
286 case Stmt::OMPDistributeDirectiveClass:
287 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
288 break;
289 case Stmt::OMPTargetUpdateDirectiveClass:
290 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
291 break;
292 case Stmt::OMPDistributeParallelForDirectiveClass:
293 EmitOMPDistributeParallelForDirective(
294 cast<OMPDistributeParallelForDirective>(*S));
295 break;
296 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
297 EmitOMPDistributeParallelForSimdDirective(
298 cast<OMPDistributeParallelForSimdDirective>(*S));
299 break;
300 case Stmt::OMPDistributeSimdDirectiveClass:
301 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
302 break;
303 case Stmt::OMPTargetParallelForSimdDirectiveClass:
304 EmitOMPTargetParallelForSimdDirective(
305 cast<OMPTargetParallelForSimdDirective>(*S));
306 break;
307 case Stmt::OMPTargetSimdDirectiveClass:
308 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S));
309 break;
310 case Stmt::OMPTeamsDistributeDirectiveClass:
311 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S));
312 break;
313 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
314 EmitOMPTeamsDistributeSimdDirective(
315 cast<OMPTeamsDistributeSimdDirective>(*S));
316 break;
317 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
318 EmitOMPTeamsDistributeParallelForSimdDirective(
319 cast<OMPTeamsDistributeParallelForSimdDirective>(*S));
320 break;
321 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
322 EmitOMPTeamsDistributeParallelForDirective(
323 cast<OMPTeamsDistributeParallelForDirective>(*S));
324 break;
325 case Stmt::OMPTargetTeamsDirectiveClass:
326 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S));
327 break;
328 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
329 EmitOMPTargetTeamsDistributeDirective(
330 cast<OMPTargetTeamsDistributeDirective>(*S));
331 break;
332 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
333 EmitOMPTargetTeamsDistributeParallelForDirective(
334 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
335 break;
336 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
337 EmitOMPTargetTeamsDistributeParallelForSimdDirective(
338 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
339 break;
340 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
341 EmitOMPTargetTeamsDistributeSimdDirective(
342 cast<OMPTargetTeamsDistributeSimdDirective>(*S));
343 break;
344 }
345 }
346
EmitSimpleStmt(const Stmt * S)347 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
348 switch (S->getStmtClass()) {
349 default: return false;
350 case Stmt::NullStmtClass: break;
351 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
352 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
353 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
354 case Stmt::AttributedStmtClass:
355 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
356 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
357 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
358 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
359 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
360 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
361 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
362 }
363
364 return true;
365 }
366
367 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
368 /// this captures the expression result of the last sub-statement and returns it
369 /// (for use by the statement expression extension).
EmitCompoundStmt(const CompoundStmt & S,bool GetLast,AggValueSlot AggSlot)370 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
371 AggValueSlot AggSlot) {
372 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
373 "LLVM IR generation of compound statement ('{}')");
374
375 // Keep track of the current cleanup stack depth, including debug scopes.
376 LexicalScope Scope(*this, S.getSourceRange());
377
378 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
379 }
380
381 Address
EmitCompoundStmtWithoutScope(const CompoundStmt & S,bool GetLast,AggValueSlot AggSlot)382 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
383 bool GetLast,
384 AggValueSlot AggSlot) {
385
386 for (CompoundStmt::const_body_iterator I = S.body_begin(),
387 E = S.body_end()-GetLast; I != E; ++I)
388 EmitStmt(*I);
389
390 Address RetAlloca = Address::invalid();
391 if (GetLast) {
392 // We have to special case labels here. They are statements, but when put
393 // at the end of a statement expression, they yield the value of their
394 // subexpression. Handle this by walking through all labels we encounter,
395 // emitting them before we evaluate the subexpr.
396 const Stmt *LastStmt = S.body_back();
397 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
398 EmitLabel(LS->getDecl());
399 LastStmt = LS->getSubStmt();
400 }
401
402 EnsureInsertPoint();
403
404 QualType ExprTy = cast<Expr>(LastStmt)->getType();
405 if (hasAggregateEvaluationKind(ExprTy)) {
406 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
407 } else {
408 // We can't return an RValue here because there might be cleanups at
409 // the end of the StmtExpr. Because of that, we have to emit the result
410 // here into a temporary alloca.
411 RetAlloca = CreateMemTemp(ExprTy);
412 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
413 /*IsInit*/false);
414 }
415
416 }
417
418 return RetAlloca;
419 }
420
SimplifyForwardingBlocks(llvm::BasicBlock * BB)421 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
422 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
423
424 // If there is a cleanup stack, then we it isn't worth trying to
425 // simplify this block (we would need to remove it from the scope map
426 // and cleanup entry).
427 if (!EHStack.empty())
428 return;
429
430 // Can only simplify direct branches.
431 if (!BI || !BI->isUnconditional())
432 return;
433
434 // Can only simplify empty blocks.
435 if (BI->getIterator() != BB->begin())
436 return;
437
438 BB->replaceAllUsesWith(BI->getSuccessor(0));
439 BI->eraseFromParent();
440 BB->eraseFromParent();
441 }
442
EmitBlock(llvm::BasicBlock * BB,bool IsFinished)443 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
444 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
445
446 // Fall out of the current block (if necessary).
447 EmitBranch(BB);
448
449 if (IsFinished && BB->use_empty()) {
450 delete BB;
451 return;
452 }
453
454 // Place the block after the current block, if possible, or else at
455 // the end of the function.
456 if (CurBB && CurBB->getParent())
457 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
458 else
459 CurFn->getBasicBlockList().push_back(BB);
460 Builder.SetInsertPoint(BB);
461 }
462
EmitBranch(llvm::BasicBlock * Target)463 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
464 // Emit a branch from the current block to the target one if this
465 // was a real block. If this was just a fall-through block after a
466 // terminator, don't emit it.
467 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
468
469 if (!CurBB || CurBB->getTerminator()) {
470 // If there is no insert point or the previous block is already
471 // terminated, don't touch it.
472 } else {
473 // Otherwise, create a fall-through branch.
474 Builder.CreateBr(Target);
475 }
476
477 Builder.ClearInsertionPoint();
478 }
479
EmitBlockAfterUses(llvm::BasicBlock * block)480 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
481 bool inserted = false;
482 for (llvm::User *u : block->users()) {
483 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
484 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
485 block);
486 inserted = true;
487 break;
488 }
489 }
490
491 if (!inserted)
492 CurFn->getBasicBlockList().push_back(block);
493
494 Builder.SetInsertPoint(block);
495 }
496
497 CodeGenFunction::JumpDest
getJumpDestForLabel(const LabelDecl * D)498 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
499 JumpDest &Dest = LabelMap[D];
500 if (Dest.isValid()) return Dest;
501
502 // Create, but don't insert, the new block.
503 Dest = JumpDest(createBasicBlock(D->getName()),
504 EHScopeStack::stable_iterator::invalid(),
505 NextCleanupDestIndex++);
506 return Dest;
507 }
508
EmitLabel(const LabelDecl * D)509 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
510 // Add this label to the current lexical scope if we're within any
511 // normal cleanups. Jumps "in" to this label --- when permitted by
512 // the language --- may need to be routed around such cleanups.
513 if (EHStack.hasNormalCleanups() && CurLexicalScope)
514 CurLexicalScope->addLabel(D);
515
516 JumpDest &Dest = LabelMap[D];
517
518 // If we didn't need a forward reference to this label, just go
519 // ahead and create a destination at the current scope.
520 if (!Dest.isValid()) {
521 Dest = getJumpDestInCurrentScope(D->getName());
522
523 // Otherwise, we need to give this label a target depth and remove
524 // it from the branch-fixups list.
525 } else {
526 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
527 Dest.setScopeDepth(EHStack.stable_begin());
528 ResolveBranchFixups(Dest.getBlock());
529 }
530
531 EmitBlock(Dest.getBlock());
532 incrementProfileCounter(D->getStmt());
533 }
534
535 /// Change the cleanup scope of the labels in this lexical scope to
536 /// match the scope of the enclosing context.
rescopeLabels()537 void CodeGenFunction::LexicalScope::rescopeLabels() {
538 assert(!Labels.empty());
539 EHScopeStack::stable_iterator innermostScope
540 = CGF.EHStack.getInnermostNormalCleanup();
541
542 // Change the scope depth of all the labels.
543 for (SmallVectorImpl<const LabelDecl*>::const_iterator
544 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
545 assert(CGF.LabelMap.count(*i));
546 JumpDest &dest = CGF.LabelMap.find(*i)->second;
547 assert(dest.getScopeDepth().isValid());
548 assert(innermostScope.encloses(dest.getScopeDepth()));
549 dest.setScopeDepth(innermostScope);
550 }
551
552 // Reparent the labels if the new scope also has cleanups.
553 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
554 ParentScope->Labels.append(Labels.begin(), Labels.end());
555 }
556 }
557
558
EmitLabelStmt(const LabelStmt & S)559 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
560 EmitLabel(S.getDecl());
561 EmitStmt(S.getSubStmt());
562 }
563
EmitAttributedStmt(const AttributedStmt & S)564 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
565 EmitStmt(S.getSubStmt(), S.getAttrs());
566 }
567
EmitGotoStmt(const GotoStmt & S)568 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
569 // If this code is reachable then emit a stop point (if generating
570 // debug info). We have to do this ourselves because we are on the
571 // "simple" statement path.
572 if (HaveInsertPoint())
573 EmitStopPoint(&S);
574
575 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
576 }
577
578
EmitIndirectGotoStmt(const IndirectGotoStmt & S)579 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
580 if (const LabelDecl *Target = S.getConstantTarget()) {
581 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
582 return;
583 }
584
585 // Ensure that we have an i8* for our PHI node.
586 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
587 Int8PtrTy, "addr");
588 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
589
590 // Get the basic block for the indirect goto.
591 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
592
593 // The first instruction in the block has to be the PHI for the switch dest,
594 // add an entry for this branch.
595 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
596
597 EmitBranch(IndGotoBB);
598 }
599
EmitIfStmt(const IfStmt & S)600 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
601 // C99 6.8.4.1: The first substatement is executed if the expression compares
602 // unequal to 0. The condition must be a scalar type.
603 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
604
605 if (S.getInit())
606 EmitStmt(S.getInit());
607
608 if (S.getConditionVariable())
609 EmitDecl(*S.getConditionVariable());
610
611 // If the condition constant folds and can be elided, try to avoid emitting
612 // the condition and the dead arm of the if/else.
613 bool CondConstant;
614 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
615 S.isConstexpr())) {
616 // Figure out which block (then or else) is executed.
617 const Stmt *Executed = S.getThen();
618 const Stmt *Skipped = S.getElse();
619 if (!CondConstant) // Condition false?
620 std::swap(Executed, Skipped);
621
622 // If the skipped block has no labels in it, just emit the executed block.
623 // This avoids emitting dead code and simplifies the CFG substantially.
624 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
625 if (CondConstant)
626 incrementProfileCounter(&S);
627 if (Executed) {
628 RunCleanupsScope ExecutedScope(*this);
629 EmitStmt(Executed);
630 }
631 return;
632 }
633 }
634
635 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
636 // the conditional branch.
637 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
638 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
639 llvm::BasicBlock *ElseBlock = ContBlock;
640 if (S.getElse())
641 ElseBlock = createBasicBlock("if.else");
642
643 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
644 getProfileCount(S.getThen()));
645
646 // Emit the 'then' code.
647 EmitBlock(ThenBlock);
648 incrementProfileCounter(&S);
649 {
650 RunCleanupsScope ThenScope(*this);
651 EmitStmt(S.getThen());
652 }
653 EmitBranch(ContBlock);
654
655 // Emit the 'else' code if present.
656 if (const Stmt *Else = S.getElse()) {
657 {
658 // There is no need to emit line number for an unconditional branch.
659 auto NL = ApplyDebugLocation::CreateEmpty(*this);
660 EmitBlock(ElseBlock);
661 }
662 {
663 RunCleanupsScope ElseScope(*this);
664 EmitStmt(Else);
665 }
666 {
667 // There is no need to emit line number for an unconditional branch.
668 auto NL = ApplyDebugLocation::CreateEmpty(*this);
669 EmitBranch(ContBlock);
670 }
671 }
672
673 // Emit the continuation block for code after the if.
674 EmitBlock(ContBlock, true);
675 }
676
EmitWhileStmt(const WhileStmt & S,ArrayRef<const Attr * > WhileAttrs)677 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
678 ArrayRef<const Attr *> WhileAttrs) {
679 // Emit the header for the loop, which will also become
680 // the continue target.
681 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
682 EmitBlock(LoopHeader.getBlock());
683
684 const SourceRange &R = S.getSourceRange();
685 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
686 SourceLocToDebugLoc(R.getBegin()),
687 SourceLocToDebugLoc(R.getEnd()));
688
689 // Create an exit block for when the condition fails, which will
690 // also become the break target.
691 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
692
693 // Store the blocks to use for break and continue.
694 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
695
696 // C++ [stmt.while]p2:
697 // When the condition of a while statement is a declaration, the
698 // scope of the variable that is declared extends from its point
699 // of declaration (3.3.2) to the end of the while statement.
700 // [...]
701 // The object created in a condition is destroyed and created
702 // with each iteration of the loop.
703 RunCleanupsScope ConditionScope(*this);
704
705 if (S.getConditionVariable())
706 EmitDecl(*S.getConditionVariable());
707
708 // Evaluate the conditional in the while header. C99 6.8.5.1: The
709 // evaluation of the controlling expression takes place before each
710 // execution of the loop body.
711 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
712
713 // while(1) is common, avoid extra exit blocks. Be sure
714 // to correctly handle break/continue though.
715 bool EmitBoolCondBranch = true;
716 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
717 if (C->isOne())
718 EmitBoolCondBranch = false;
719
720 // As long as the condition is true, go to the loop body.
721 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
722 if (EmitBoolCondBranch) {
723 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
724 if (ConditionScope.requiresCleanups())
725 ExitBlock = createBasicBlock("while.exit");
726 Builder.CreateCondBr(
727 BoolCondVal, LoopBody, ExitBlock,
728 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
729
730 if (ExitBlock != LoopExit.getBlock()) {
731 EmitBlock(ExitBlock);
732 EmitBranchThroughCleanup(LoopExit);
733 }
734 }
735
736 // Emit the loop body. We have to emit this in a cleanup scope
737 // because it might be a singleton DeclStmt.
738 {
739 RunCleanupsScope BodyScope(*this);
740 EmitBlock(LoopBody);
741 incrementProfileCounter(&S);
742 EmitStmt(S.getBody());
743 }
744
745 BreakContinueStack.pop_back();
746
747 // Immediately force cleanup.
748 ConditionScope.ForceCleanup();
749
750 EmitStopPoint(&S);
751 // Branch to the loop header again.
752 EmitBranch(LoopHeader.getBlock());
753
754 LoopStack.pop();
755
756 // Emit the exit block.
757 EmitBlock(LoopExit.getBlock(), true);
758
759 // The LoopHeader typically is just a branch if we skipped emitting
760 // a branch, try to erase it.
761 if (!EmitBoolCondBranch)
762 SimplifyForwardingBlocks(LoopHeader.getBlock());
763 }
764
EmitDoStmt(const DoStmt & S,ArrayRef<const Attr * > DoAttrs)765 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
766 ArrayRef<const Attr *> DoAttrs) {
767 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
768 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
769
770 uint64_t ParentCount = getCurrentProfileCount();
771
772 // Store the blocks to use for break and continue.
773 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
774
775 // Emit the body of the loop.
776 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
777
778 EmitBlockWithFallThrough(LoopBody, &S);
779 {
780 RunCleanupsScope BodyScope(*this);
781 EmitStmt(S.getBody());
782 }
783
784 EmitBlock(LoopCond.getBlock());
785
786 const SourceRange &R = S.getSourceRange();
787 LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
788 SourceLocToDebugLoc(R.getBegin()),
789 SourceLocToDebugLoc(R.getEnd()));
790
791 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
792 // after each execution of the loop body."
793
794 // Evaluate the conditional in the while header.
795 // C99 6.8.5p2/p4: The first substatement is executed if the expression
796 // compares unequal to 0. The condition must be a scalar type.
797 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
798
799 BreakContinueStack.pop_back();
800
801 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
802 // to correctly handle break/continue though.
803 bool EmitBoolCondBranch = true;
804 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
805 if (C->isZero())
806 EmitBoolCondBranch = false;
807
808 // As long as the condition is true, iterate the loop.
809 if (EmitBoolCondBranch) {
810 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
811 Builder.CreateCondBr(
812 BoolCondVal, LoopBody, LoopExit.getBlock(),
813 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
814 }
815
816 LoopStack.pop();
817
818 // Emit the exit block.
819 EmitBlock(LoopExit.getBlock());
820
821 // The DoCond block typically is just a branch if we skipped
822 // emitting a branch, try to erase it.
823 if (!EmitBoolCondBranch)
824 SimplifyForwardingBlocks(LoopCond.getBlock());
825 }
826
EmitForStmt(const ForStmt & S,ArrayRef<const Attr * > ForAttrs)827 void CodeGenFunction::EmitForStmt(const ForStmt &S,
828 ArrayRef<const Attr *> ForAttrs) {
829 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
830
831 LexicalScope ForScope(*this, S.getSourceRange());
832
833 // Evaluate the first part before the loop.
834 if (S.getInit())
835 EmitStmt(S.getInit());
836
837 // Start the loop with a block that tests the condition.
838 // If there's an increment, the continue scope will be overwritten
839 // later.
840 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
841 llvm::BasicBlock *CondBlock = Continue.getBlock();
842 EmitBlock(CondBlock);
843
844 const SourceRange &R = S.getSourceRange();
845 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
846 SourceLocToDebugLoc(R.getBegin()),
847 SourceLocToDebugLoc(R.getEnd()));
848
849 // If the for loop doesn't have an increment we can just use the
850 // condition as the continue block. Otherwise we'll need to create
851 // a block for it (in the current scope, i.e. in the scope of the
852 // condition), and that we will become our continue block.
853 if (S.getInc())
854 Continue = getJumpDestInCurrentScope("for.inc");
855
856 // Store the blocks to use for break and continue.
857 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
858
859 // Create a cleanup scope for the condition variable cleanups.
860 LexicalScope ConditionScope(*this, S.getSourceRange());
861
862 if (S.getCond()) {
863 // If the for statement has a condition scope, emit the local variable
864 // declaration.
865 if (S.getConditionVariable()) {
866 EmitDecl(*S.getConditionVariable());
867 }
868
869 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
870 // If there are any cleanups between here and the loop-exit scope,
871 // create a block to stage a loop exit along.
872 if (ForScope.requiresCleanups())
873 ExitBlock = createBasicBlock("for.cond.cleanup");
874
875 // As long as the condition is true, iterate the loop.
876 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
877
878 // C99 6.8.5p2/p4: The first substatement is executed if the expression
879 // compares unequal to 0. The condition must be a scalar type.
880 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
881 Builder.CreateCondBr(
882 BoolCondVal, ForBody, ExitBlock,
883 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
884
885 if (ExitBlock != LoopExit.getBlock()) {
886 EmitBlock(ExitBlock);
887 EmitBranchThroughCleanup(LoopExit);
888 }
889
890 EmitBlock(ForBody);
891 } else {
892 // Treat it as a non-zero constant. Don't even create a new block for the
893 // body, just fall into it.
894 }
895 incrementProfileCounter(&S);
896
897 {
898 // Create a separate cleanup scope for the body, in case it is not
899 // a compound statement.
900 RunCleanupsScope BodyScope(*this);
901 EmitStmt(S.getBody());
902 }
903
904 // If there is an increment, emit it next.
905 if (S.getInc()) {
906 EmitBlock(Continue.getBlock());
907 EmitStmt(S.getInc());
908 }
909
910 BreakContinueStack.pop_back();
911
912 ConditionScope.ForceCleanup();
913
914 EmitStopPoint(&S);
915 EmitBranch(CondBlock);
916
917 ForScope.ForceCleanup();
918
919 LoopStack.pop();
920
921 // Emit the fall-through block.
922 EmitBlock(LoopExit.getBlock(), true);
923 }
924
925 void
EmitCXXForRangeStmt(const CXXForRangeStmt & S,ArrayRef<const Attr * > ForAttrs)926 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
927 ArrayRef<const Attr *> ForAttrs) {
928 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
929
930 LexicalScope ForScope(*this, S.getSourceRange());
931
932 // Evaluate the first pieces before the loop.
933 if (S.getInit())
934 EmitStmt(S.getInit());
935 EmitStmt(S.getRangeStmt());
936 EmitStmt(S.getBeginStmt());
937 EmitStmt(S.getEndStmt());
938
939 // Start the loop with a block that tests the condition.
940 // If there's an increment, the continue scope will be overwritten
941 // later.
942 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
943 EmitBlock(CondBlock);
944
945 const SourceRange &R = S.getSourceRange();
946 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs,
947 SourceLocToDebugLoc(R.getBegin()),
948 SourceLocToDebugLoc(R.getEnd()));
949
950 // If there are any cleanups between here and the loop-exit scope,
951 // create a block to stage a loop exit along.
952 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
953 if (ForScope.requiresCleanups())
954 ExitBlock = createBasicBlock("for.cond.cleanup");
955
956 // The loop body, consisting of the specified body and the loop variable.
957 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
958
959 // The body is executed if the expression, contextually converted
960 // to bool, is true.
961 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
962 Builder.CreateCondBr(
963 BoolCondVal, ForBody, ExitBlock,
964 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
965
966 if (ExitBlock != LoopExit.getBlock()) {
967 EmitBlock(ExitBlock);
968 EmitBranchThroughCleanup(LoopExit);
969 }
970
971 EmitBlock(ForBody);
972 incrementProfileCounter(&S);
973
974 // Create a block for the increment. In case of a 'continue', we jump there.
975 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
976
977 // Store the blocks to use for break and continue.
978 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
979
980 {
981 // Create a separate cleanup scope for the loop variable and body.
982 LexicalScope BodyScope(*this, S.getSourceRange());
983 EmitStmt(S.getLoopVarStmt());
984 EmitStmt(S.getBody());
985 }
986
987 EmitStopPoint(&S);
988 // If there is an increment, emit it next.
989 EmitBlock(Continue.getBlock());
990 EmitStmt(S.getInc());
991
992 BreakContinueStack.pop_back();
993
994 EmitBranch(CondBlock);
995
996 ForScope.ForceCleanup();
997
998 LoopStack.pop();
999
1000 // Emit the fall-through block.
1001 EmitBlock(LoopExit.getBlock(), true);
1002 }
1003
EmitReturnOfRValue(RValue RV,QualType Ty)1004 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
1005 if (RV.isScalar()) {
1006 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
1007 } else if (RV.isAggregate()) {
1008 LValue Dest = MakeAddrLValue(ReturnValue, Ty);
1009 LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
1010 EmitAggregateCopy(Dest, Src, Ty, overlapForReturnValue());
1011 } else {
1012 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
1013 /*init*/ true);
1014 }
1015 EmitBranchThroughCleanup(ReturnBlock);
1016 }
1017
1018 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
1019 /// if the function returns void, or may be missing one if the function returns
1020 /// non-void. Fun stuff :).
EmitReturnStmt(const ReturnStmt & S)1021 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
1022 if (requiresReturnValueCheck()) {
1023 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc());
1024 auto *SLocPtr =
1025 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false,
1026 llvm::GlobalVariable::PrivateLinkage, SLoc);
1027 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1028 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr);
1029 assert(ReturnLocation.isValid() && "No valid return location");
1030 Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy),
1031 ReturnLocation);
1032 }
1033
1034 // Returning from an outlined SEH helper is UB, and we already warn on it.
1035 if (IsOutlinedSEHHelper) {
1036 Builder.CreateUnreachable();
1037 Builder.ClearInsertionPoint();
1038 }
1039
1040 // Emit the result value, even if unused, to evaluate the side effects.
1041 const Expr *RV = S.getRetValue();
1042
1043 // Treat block literals in a return expression as if they appeared
1044 // in their own scope. This permits a small, easily-implemented
1045 // exception to our over-conservative rules about not jumping to
1046 // statements following block literals with non-trivial cleanups.
1047 RunCleanupsScope cleanupScope(*this);
1048 if (const FullExpr *fe = dyn_cast_or_null<FullExpr>(RV)) {
1049 enterFullExpression(fe);
1050 RV = fe->getSubExpr();
1051 }
1052
1053 // FIXME: Clean this up by using an LValue for ReturnTemp,
1054 // EmitStoreThroughLValue, and EmitAnyExpr.
1055 if (getLangOpts().ElideConstructors &&
1056 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1057 // Apply the named return value optimization for this return statement,
1058 // which means doing nothing: the appropriate result has already been
1059 // constructed into the NRVO variable.
1060
1061 // If there is an NRVO flag for this variable, set it to 1 into indicate
1062 // that the cleanup code should not destroy the variable.
1063 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1064 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1065 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1066 // Make sure not to return anything, but evaluate the expression
1067 // for side effects.
1068 if (RV)
1069 EmitAnyExpr(RV);
1070 } else if (!RV) {
1071 // Do nothing (return value is left uninitialized)
1072 } else if (FnRetTy->isReferenceType()) {
1073 // If this function returns a reference, take the address of the expression
1074 // rather than the value.
1075 RValue Result = EmitReferenceBindingToExpr(RV);
1076 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1077 } else {
1078 switch (getEvaluationKind(RV->getType())) {
1079 case TEK_Scalar:
1080 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1081 break;
1082 case TEK_Complex:
1083 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1084 /*isInit*/ true);
1085 break;
1086 case TEK_Aggregate:
1087 EmitAggExpr(RV, AggValueSlot::forAddr(
1088 ReturnValue, Qualifiers(),
1089 AggValueSlot::IsDestructed,
1090 AggValueSlot::DoesNotNeedGCBarriers,
1091 AggValueSlot::IsNotAliased,
1092 overlapForReturnValue()));
1093 break;
1094 }
1095 }
1096
1097 ++NumReturnExprs;
1098 if (!RV || RV->isEvaluatable(getContext()))
1099 ++NumSimpleReturnExprs;
1100
1101 cleanupScope.ForceCleanup();
1102 EmitBranchThroughCleanup(ReturnBlock);
1103 }
1104
EmitDeclStmt(const DeclStmt & S)1105 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1106 // As long as debug info is modeled with instructions, we have to ensure we
1107 // have a place to insert here and write the stop point here.
1108 if (HaveInsertPoint())
1109 EmitStopPoint(&S);
1110
1111 for (const auto *I : S.decls())
1112 EmitDecl(*I);
1113 }
1114
EmitBreakStmt(const BreakStmt & S)1115 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1116 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1117
1118 // If this code is reachable then emit a stop point (if generating
1119 // debug info). We have to do this ourselves because we are on the
1120 // "simple" statement path.
1121 if (HaveInsertPoint())
1122 EmitStopPoint(&S);
1123
1124 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1125 }
1126
EmitContinueStmt(const ContinueStmt & S)1127 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1128 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1129
1130 // If this code is reachable then emit a stop point (if generating
1131 // debug info). We have to do this ourselves because we are on the
1132 // "simple" statement path.
1133 if (HaveInsertPoint())
1134 EmitStopPoint(&S);
1135
1136 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1137 }
1138
1139 /// EmitCaseStmtRange - If case statement range is not too big then
1140 /// add multiple cases to switch instruction, one for each value within
1141 /// the range. If range is too big then emit "if" condition check.
EmitCaseStmtRange(const CaseStmt & S)1142 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1143 assert(S.getRHS() && "Expected RHS value in CaseStmt");
1144
1145 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1146 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1147
1148 // Emit the code for this case. We do this first to make sure it is
1149 // properly chained from our predecessor before generating the
1150 // switch machinery to enter this block.
1151 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1152 EmitBlockWithFallThrough(CaseDest, &S);
1153 EmitStmt(S.getSubStmt());
1154
1155 // If range is empty, do nothing.
1156 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1157 return;
1158
1159 llvm::APInt Range = RHS - LHS;
1160 // FIXME: parameters such as this should not be hardcoded.
1161 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1162 // Range is small enough to add multiple switch instruction cases.
1163 uint64_t Total = getProfileCount(&S);
1164 unsigned NCases = Range.getZExtValue() + 1;
1165 // We only have one region counter for the entire set of cases here, so we
1166 // need to divide the weights evenly between the generated cases, ensuring
1167 // that the total weight is preserved. E.g., a weight of 5 over three cases
1168 // will be distributed as weights of 2, 2, and 1.
1169 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1170 for (unsigned I = 0; I != NCases; ++I) {
1171 if (SwitchWeights)
1172 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1173 if (Rem)
1174 Rem--;
1175 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1176 ++LHS;
1177 }
1178 return;
1179 }
1180
1181 // The range is too big. Emit "if" condition into a new block,
1182 // making sure to save and restore the current insertion point.
1183 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1184
1185 // Push this test onto the chain of range checks (which terminates
1186 // in the default basic block). The switch's default will be changed
1187 // to the top of this chain after switch emission is complete.
1188 llvm::BasicBlock *FalseDest = CaseRangeBlock;
1189 CaseRangeBlock = createBasicBlock("sw.caserange");
1190
1191 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1192 Builder.SetInsertPoint(CaseRangeBlock);
1193
1194 // Emit range check.
1195 llvm::Value *Diff =
1196 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1197 llvm::Value *Cond =
1198 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1199
1200 llvm::MDNode *Weights = nullptr;
1201 if (SwitchWeights) {
1202 uint64_t ThisCount = getProfileCount(&S);
1203 uint64_t DefaultCount = (*SwitchWeights)[0];
1204 Weights = createProfileWeights(ThisCount, DefaultCount);
1205
1206 // Since we're chaining the switch default through each large case range, we
1207 // need to update the weight for the default, ie, the first case, to include
1208 // this case.
1209 (*SwitchWeights)[0] += ThisCount;
1210 }
1211 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1212
1213 // Restore the appropriate insertion point.
1214 if (RestoreBB)
1215 Builder.SetInsertPoint(RestoreBB);
1216 else
1217 Builder.ClearInsertionPoint();
1218 }
1219
EmitCaseStmt(const CaseStmt & S)1220 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1221 // If there is no enclosing switch instance that we're aware of, then this
1222 // case statement and its block can be elided. This situation only happens
1223 // when we've constant-folded the switch, are emitting the constant case,
1224 // and part of the constant case includes another case statement. For
1225 // instance: switch (4) { case 4: do { case 5: } while (1); }
1226 if (!SwitchInsn) {
1227 EmitStmt(S.getSubStmt());
1228 return;
1229 }
1230
1231 // Handle case ranges.
1232 if (S.getRHS()) {
1233 EmitCaseStmtRange(S);
1234 return;
1235 }
1236
1237 llvm::ConstantInt *CaseVal =
1238 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1239
1240 // If the body of the case is just a 'break', try to not emit an empty block.
1241 // If we're profiling or we're not optimizing, leave the block in for better
1242 // debug and coverage analysis.
1243 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1244 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1245 isa<BreakStmt>(S.getSubStmt())) {
1246 JumpDest Block = BreakContinueStack.back().BreakBlock;
1247
1248 // Only do this optimization if there are no cleanups that need emitting.
1249 if (isObviouslyBranchWithoutCleanups(Block)) {
1250 if (SwitchWeights)
1251 SwitchWeights->push_back(getProfileCount(&S));
1252 SwitchInsn->addCase(CaseVal, Block.getBlock());
1253
1254 // If there was a fallthrough into this case, make sure to redirect it to
1255 // the end of the switch as well.
1256 if (Builder.GetInsertBlock()) {
1257 Builder.CreateBr(Block.getBlock());
1258 Builder.ClearInsertionPoint();
1259 }
1260 return;
1261 }
1262 }
1263
1264 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1265 EmitBlockWithFallThrough(CaseDest, &S);
1266 if (SwitchWeights)
1267 SwitchWeights->push_back(getProfileCount(&S));
1268 SwitchInsn->addCase(CaseVal, CaseDest);
1269
1270 // Recursively emitting the statement is acceptable, but is not wonderful for
1271 // code where we have many case statements nested together, i.e.:
1272 // case 1:
1273 // case 2:
1274 // case 3: etc.
1275 // Handling this recursively will create a new block for each case statement
1276 // that falls through to the next case which is IR intensive. It also causes
1277 // deep recursion which can run into stack depth limitations. Handle
1278 // sequential non-range case statements specially.
1279 const CaseStmt *CurCase = &S;
1280 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1281
1282 // Otherwise, iteratively add consecutive cases to this switch stmt.
1283 while (NextCase && NextCase->getRHS() == nullptr) {
1284 CurCase = NextCase;
1285 llvm::ConstantInt *CaseVal =
1286 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1287
1288 if (SwitchWeights)
1289 SwitchWeights->push_back(getProfileCount(NextCase));
1290 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1291 CaseDest = createBasicBlock("sw.bb");
1292 EmitBlockWithFallThrough(CaseDest, &S);
1293 }
1294
1295 SwitchInsn->addCase(CaseVal, CaseDest);
1296 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1297 }
1298
1299 // Normal default recursion for non-cases.
1300 EmitStmt(CurCase->getSubStmt());
1301 }
1302
EmitDefaultStmt(const DefaultStmt & S)1303 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1304 // If there is no enclosing switch instance that we're aware of, then this
1305 // default statement can be elided. This situation only happens when we've
1306 // constant-folded the switch.
1307 if (!SwitchInsn) {
1308 EmitStmt(S.getSubStmt());
1309 return;
1310 }
1311
1312 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1313 assert(DefaultBlock->empty() &&
1314 "EmitDefaultStmt: Default block already defined?");
1315
1316 EmitBlockWithFallThrough(DefaultBlock, &S);
1317
1318 EmitStmt(S.getSubStmt());
1319 }
1320
1321 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1322 /// constant value that is being switched on, see if we can dead code eliminate
1323 /// the body of the switch to a simple series of statements to emit. Basically,
1324 /// on a switch (5) we want to find these statements:
1325 /// case 5:
1326 /// printf(...); <--
1327 /// ++i; <--
1328 /// break;
1329 ///
1330 /// and add them to the ResultStmts vector. If it is unsafe to do this
1331 /// transformation (for example, one of the elided statements contains a label
1332 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1333 /// should include statements after it (e.g. the printf() line is a substmt of
1334 /// the case) then return CSFC_FallThrough. If we handled it and found a break
1335 /// statement, then return CSFC_Success.
1336 ///
1337 /// If Case is non-null, then we are looking for the specified case, checking
1338 /// that nothing we jump over contains labels. If Case is null, then we found
1339 /// the case and are looking for the break.
1340 ///
1341 /// If the recursive walk actually finds our Case, then we set FoundCase to
1342 /// true.
1343 ///
1344 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
CollectStatementsForCase(const Stmt * S,const SwitchCase * Case,bool & FoundCase,SmallVectorImpl<const Stmt * > & ResultStmts)1345 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1346 const SwitchCase *Case,
1347 bool &FoundCase,
1348 SmallVectorImpl<const Stmt*> &ResultStmts) {
1349 // If this is a null statement, just succeed.
1350 if (!S)
1351 return Case ? CSFC_Success : CSFC_FallThrough;
1352
1353 // If this is the switchcase (case 4: or default) that we're looking for, then
1354 // we're in business. Just add the substatement.
1355 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1356 if (S == Case) {
1357 FoundCase = true;
1358 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1359 ResultStmts);
1360 }
1361
1362 // Otherwise, this is some other case or default statement, just ignore it.
1363 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1364 ResultStmts);
1365 }
1366
1367 // If we are in the live part of the code and we found our break statement,
1368 // return a success!
1369 if (!Case && isa<BreakStmt>(S))
1370 return CSFC_Success;
1371
1372 // If this is a switch statement, then it might contain the SwitchCase, the
1373 // break, or neither.
1374 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1375 // Handle this as two cases: we might be looking for the SwitchCase (if so
1376 // the skipped statements must be skippable) or we might already have it.
1377 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1378 bool StartedInLiveCode = FoundCase;
1379 unsigned StartSize = ResultStmts.size();
1380
1381 // If we've not found the case yet, scan through looking for it.
1382 if (Case) {
1383 // Keep track of whether we see a skipped declaration. The code could be
1384 // using the declaration even if it is skipped, so we can't optimize out
1385 // the decl if the kept statements might refer to it.
1386 bool HadSkippedDecl = false;
1387
1388 // If we're looking for the case, just see if we can skip each of the
1389 // substatements.
1390 for (; Case && I != E; ++I) {
1391 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I);
1392
1393 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1394 case CSFC_Failure: return CSFC_Failure;
1395 case CSFC_Success:
1396 // A successful result means that either 1) that the statement doesn't
1397 // have the case and is skippable, or 2) does contain the case value
1398 // and also contains the break to exit the switch. In the later case,
1399 // we just verify the rest of the statements are elidable.
1400 if (FoundCase) {
1401 // If we found the case and skipped declarations, we can't do the
1402 // optimization.
1403 if (HadSkippedDecl)
1404 return CSFC_Failure;
1405
1406 for (++I; I != E; ++I)
1407 if (CodeGenFunction::ContainsLabel(*I, true))
1408 return CSFC_Failure;
1409 return CSFC_Success;
1410 }
1411 break;
1412 case CSFC_FallThrough:
1413 // If we have a fallthrough condition, then we must have found the
1414 // case started to include statements. Consider the rest of the
1415 // statements in the compound statement as candidates for inclusion.
1416 assert(FoundCase && "Didn't find case but returned fallthrough?");
1417 // We recursively found Case, so we're not looking for it anymore.
1418 Case = nullptr;
1419
1420 // If we found the case and skipped declarations, we can't do the
1421 // optimization.
1422 if (HadSkippedDecl)
1423 return CSFC_Failure;
1424 break;
1425 }
1426 }
1427
1428 if (!FoundCase)
1429 return CSFC_Success;
1430
1431 assert(!HadSkippedDecl && "fallthrough after skipping decl");
1432 }
1433
1434 // If we have statements in our range, then we know that the statements are
1435 // live and need to be added to the set of statements we're tracking.
1436 bool AnyDecls = false;
1437 for (; I != E; ++I) {
1438 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I);
1439
1440 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1441 case CSFC_Failure: return CSFC_Failure;
1442 case CSFC_FallThrough:
1443 // A fallthrough result means that the statement was simple and just
1444 // included in ResultStmt, keep adding them afterwards.
1445 break;
1446 case CSFC_Success:
1447 // A successful result means that we found the break statement and
1448 // stopped statement inclusion. We just ensure that any leftover stmts
1449 // are skippable and return success ourselves.
1450 for (++I; I != E; ++I)
1451 if (CodeGenFunction::ContainsLabel(*I, true))
1452 return CSFC_Failure;
1453 return CSFC_Success;
1454 }
1455 }
1456
1457 // If we're about to fall out of a scope without hitting a 'break;', we
1458 // can't perform the optimization if there were any decls in that scope
1459 // (we'd lose their end-of-lifetime).
1460 if (AnyDecls) {
1461 // If the entire compound statement was live, there's one more thing we
1462 // can try before giving up: emit the whole thing as a single statement.
1463 // We can do that unless the statement contains a 'break;'.
1464 // FIXME: Such a break must be at the end of a construct within this one.
1465 // We could emit this by just ignoring the BreakStmts entirely.
1466 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) {
1467 ResultStmts.resize(StartSize);
1468 ResultStmts.push_back(S);
1469 } else {
1470 return CSFC_Failure;
1471 }
1472 }
1473
1474 return CSFC_FallThrough;
1475 }
1476
1477 // Okay, this is some other statement that we don't handle explicitly, like a
1478 // for statement or increment etc. If we are skipping over this statement,
1479 // just verify it doesn't have labels, which would make it invalid to elide.
1480 if (Case) {
1481 if (CodeGenFunction::ContainsLabel(S, true))
1482 return CSFC_Failure;
1483 return CSFC_Success;
1484 }
1485
1486 // Otherwise, we want to include this statement. Everything is cool with that
1487 // so long as it doesn't contain a break out of the switch we're in.
1488 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1489
1490 // Otherwise, everything is great. Include the statement and tell the caller
1491 // that we fall through and include the next statement as well.
1492 ResultStmts.push_back(S);
1493 return CSFC_FallThrough;
1494 }
1495
1496 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1497 /// then invoke CollectStatementsForCase to find the list of statements to emit
1498 /// for a switch on constant. See the comment above CollectStatementsForCase
1499 /// for more details.
FindCaseStatementsForValue(const SwitchStmt & S,const llvm::APSInt & ConstantCondValue,SmallVectorImpl<const Stmt * > & ResultStmts,ASTContext & C,const SwitchCase * & ResultCase)1500 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1501 const llvm::APSInt &ConstantCondValue,
1502 SmallVectorImpl<const Stmt*> &ResultStmts,
1503 ASTContext &C,
1504 const SwitchCase *&ResultCase) {
1505 // First step, find the switch case that is being branched to. We can do this
1506 // efficiently by scanning the SwitchCase list.
1507 const SwitchCase *Case = S.getSwitchCaseList();
1508 const DefaultStmt *DefaultCase = nullptr;
1509
1510 for (; Case; Case = Case->getNextSwitchCase()) {
1511 // It's either a default or case. Just remember the default statement in
1512 // case we're not jumping to any numbered cases.
1513 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1514 DefaultCase = DS;
1515 continue;
1516 }
1517
1518 // Check to see if this case is the one we're looking for.
1519 const CaseStmt *CS = cast<CaseStmt>(Case);
1520 // Don't handle case ranges yet.
1521 if (CS->getRHS()) return false;
1522
1523 // If we found our case, remember it as 'case'.
1524 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1525 break;
1526 }
1527
1528 // If we didn't find a matching case, we use a default if it exists, or we
1529 // elide the whole switch body!
1530 if (!Case) {
1531 // It is safe to elide the body of the switch if it doesn't contain labels
1532 // etc. If it is safe, return successfully with an empty ResultStmts list.
1533 if (!DefaultCase)
1534 return !CodeGenFunction::ContainsLabel(&S);
1535 Case = DefaultCase;
1536 }
1537
1538 // Ok, we know which case is being jumped to, try to collect all the
1539 // statements that follow it. This can fail for a variety of reasons. Also,
1540 // check to see that the recursive walk actually found our case statement.
1541 // Insane cases like this can fail to find it in the recursive walk since we
1542 // don't handle every stmt kind:
1543 // switch (4) {
1544 // while (1) {
1545 // case 4: ...
1546 bool FoundCase = false;
1547 ResultCase = Case;
1548 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1549 ResultStmts) != CSFC_Failure &&
1550 FoundCase;
1551 }
1552
EmitSwitchStmt(const SwitchStmt & S)1553 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1554 // Handle nested switch statements.
1555 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1556 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1557 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1558
1559 // See if we can constant fold the condition of the switch and therefore only
1560 // emit the live case statement (if any) of the switch.
1561 llvm::APSInt ConstantCondValue;
1562 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1563 SmallVector<const Stmt*, 4> CaseStmts;
1564 const SwitchCase *Case = nullptr;
1565 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1566 getContext(), Case)) {
1567 if (Case)
1568 incrementProfileCounter(Case);
1569 RunCleanupsScope ExecutedScope(*this);
1570
1571 if (S.getInit())
1572 EmitStmt(S.getInit());
1573
1574 // Emit the condition variable if needed inside the entire cleanup scope
1575 // used by this special case for constant folded switches.
1576 if (S.getConditionVariable())
1577 EmitDecl(*S.getConditionVariable());
1578
1579 // At this point, we are no longer "within" a switch instance, so
1580 // we can temporarily enforce this to ensure that any embedded case
1581 // statements are not emitted.
1582 SwitchInsn = nullptr;
1583
1584 // Okay, we can dead code eliminate everything except this case. Emit the
1585 // specified series of statements and we're good.
1586 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1587 EmitStmt(CaseStmts[i]);
1588 incrementProfileCounter(&S);
1589
1590 // Now we want to restore the saved switch instance so that nested
1591 // switches continue to function properly
1592 SwitchInsn = SavedSwitchInsn;
1593
1594 return;
1595 }
1596 }
1597
1598 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1599
1600 RunCleanupsScope ConditionScope(*this);
1601
1602 if (S.getInit())
1603 EmitStmt(S.getInit());
1604
1605 if (S.getConditionVariable())
1606 EmitDecl(*S.getConditionVariable());
1607 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1608
1609 // Create basic block to hold stuff that comes after switch
1610 // statement. We also need to create a default block now so that
1611 // explicit case ranges tests can have a place to jump to on
1612 // failure.
1613 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1614 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1615 if (PGO.haveRegionCounts()) {
1616 // Walk the SwitchCase list to find how many there are.
1617 uint64_t DefaultCount = 0;
1618 unsigned NumCases = 0;
1619 for (const SwitchCase *Case = S.getSwitchCaseList();
1620 Case;
1621 Case = Case->getNextSwitchCase()) {
1622 if (isa<DefaultStmt>(Case))
1623 DefaultCount = getProfileCount(Case);
1624 NumCases += 1;
1625 }
1626 SwitchWeights = new SmallVector<uint64_t, 16>();
1627 SwitchWeights->reserve(NumCases);
1628 // The default needs to be first. We store the edge count, so we already
1629 // know the right weight.
1630 SwitchWeights->push_back(DefaultCount);
1631 }
1632 CaseRangeBlock = DefaultBlock;
1633
1634 // Clear the insertion point to indicate we are in unreachable code.
1635 Builder.ClearInsertionPoint();
1636
1637 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1638 // then reuse last ContinueBlock.
1639 JumpDest OuterContinue;
1640 if (!BreakContinueStack.empty())
1641 OuterContinue = BreakContinueStack.back().ContinueBlock;
1642
1643 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1644
1645 // Emit switch body.
1646 EmitStmt(S.getBody());
1647
1648 BreakContinueStack.pop_back();
1649
1650 // Update the default block in case explicit case range tests have
1651 // been chained on top.
1652 SwitchInsn->setDefaultDest(CaseRangeBlock);
1653
1654 // If a default was never emitted:
1655 if (!DefaultBlock->getParent()) {
1656 // If we have cleanups, emit the default block so that there's a
1657 // place to jump through the cleanups from.
1658 if (ConditionScope.requiresCleanups()) {
1659 EmitBlock(DefaultBlock);
1660
1661 // Otherwise, just forward the default block to the switch end.
1662 } else {
1663 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1664 delete DefaultBlock;
1665 }
1666 }
1667
1668 ConditionScope.ForceCleanup();
1669
1670 // Emit continuation.
1671 EmitBlock(SwitchExit.getBlock(), true);
1672 incrementProfileCounter(&S);
1673
1674 // If the switch has a condition wrapped by __builtin_unpredictable,
1675 // create metadata that specifies that the switch is unpredictable.
1676 // Don't bother if not optimizing because that metadata would not be used.
1677 auto *Call = dyn_cast<CallExpr>(S.getCond());
1678 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1679 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1680 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1681 llvm::MDBuilder MDHelper(getLLVMContext());
1682 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1683 MDHelper.createUnpredictable());
1684 }
1685 }
1686
1687 if (SwitchWeights) {
1688 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1689 "switch weights do not match switch cases");
1690 // If there's only one jump destination there's no sense weighting it.
1691 if (SwitchWeights->size() > 1)
1692 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1693 createProfileWeights(*SwitchWeights));
1694 delete SwitchWeights;
1695 }
1696 SwitchInsn = SavedSwitchInsn;
1697 SwitchWeights = SavedSwitchWeights;
1698 CaseRangeBlock = SavedCRBlock;
1699 }
1700
1701 static std::string
SimplifyConstraint(const char * Constraint,const TargetInfo & Target,SmallVectorImpl<TargetInfo::ConstraintInfo> * OutCons=nullptr)1702 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1703 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1704 std::string Result;
1705
1706 while (*Constraint) {
1707 switch (*Constraint) {
1708 default:
1709 Result += Target.convertConstraint(Constraint);
1710 break;
1711 // Ignore these
1712 case '*':
1713 case '?':
1714 case '!':
1715 case '=': // Will see this and the following in mult-alt constraints.
1716 case '+':
1717 break;
1718 case '#': // Ignore the rest of the constraint alternative.
1719 while (Constraint[1] && Constraint[1] != ',')
1720 Constraint++;
1721 break;
1722 case '&':
1723 case '%':
1724 Result += *Constraint;
1725 while (Constraint[1] && Constraint[1] == *Constraint)
1726 Constraint++;
1727 break;
1728 case ',':
1729 Result += "|";
1730 break;
1731 case 'g':
1732 Result += "imr";
1733 break;
1734 case '[': {
1735 assert(OutCons &&
1736 "Must pass output names to constraints with a symbolic name");
1737 unsigned Index;
1738 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1739 assert(result && "Could not resolve symbolic name"); (void)result;
1740 Result += llvm::utostr(Index);
1741 break;
1742 }
1743 }
1744
1745 Constraint++;
1746 }
1747
1748 return Result;
1749 }
1750
1751 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1752 /// as using a particular register add that as a constraint that will be used
1753 /// in this asm stmt.
1754 static std::string
AddVariableConstraints(const std::string & Constraint,const Expr & AsmExpr,const TargetInfo & Target,CodeGenModule & CGM,const AsmStmt & Stmt,const bool EarlyClobber)1755 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1756 const TargetInfo &Target, CodeGenModule &CGM,
1757 const AsmStmt &Stmt, const bool EarlyClobber) {
1758 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1759 if (!AsmDeclRef)
1760 return Constraint;
1761 const ValueDecl &Value = *AsmDeclRef->getDecl();
1762 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1763 if (!Variable)
1764 return Constraint;
1765 if (Variable->getStorageClass() != SC_Register)
1766 return Constraint;
1767 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1768 if (!Attr)
1769 return Constraint;
1770 StringRef Register = Attr->getLabel();
1771 assert(Target.isValidGCCRegisterName(Register));
1772 // We're using validateOutputConstraint here because we only care if
1773 // this is a register constraint.
1774 TargetInfo::ConstraintInfo Info(Constraint, "");
1775 if (Target.validateOutputConstraint(Info) &&
1776 !Info.allowsRegister()) {
1777 CGM.ErrorUnsupported(&Stmt, "__asm__");
1778 return Constraint;
1779 }
1780 // Canonicalize the register here before returning it.
1781 Register = Target.getNormalizedGCCRegisterName(Register);
1782 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1783 }
1784
1785 llvm::Value*
EmitAsmInputLValue(const TargetInfo::ConstraintInfo & Info,LValue InputValue,QualType InputType,std::string & ConstraintStr,SourceLocation Loc)1786 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1787 LValue InputValue, QualType InputType,
1788 std::string &ConstraintStr,
1789 SourceLocation Loc) {
1790 llvm::Value *Arg;
1791 if (Info.allowsRegister() || !Info.allowsMemory()) {
1792 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1793 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1794 } else {
1795 llvm::Type *Ty = ConvertType(InputType);
1796 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1797 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1798 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1799 Ty = llvm::PointerType::getUnqual(Ty);
1800
1801 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1802 Ty));
1803 } else {
1804 Arg = InputValue.getPointer();
1805 ConstraintStr += '*';
1806 }
1807 }
1808 } else {
1809 Arg = InputValue.getPointer();
1810 ConstraintStr += '*';
1811 }
1812
1813 return Arg;
1814 }
1815
EmitAsmInput(const TargetInfo::ConstraintInfo & Info,const Expr * InputExpr,std::string & ConstraintStr)1816 llvm::Value* CodeGenFunction::EmitAsmInput(
1817 const TargetInfo::ConstraintInfo &Info,
1818 const Expr *InputExpr,
1819 std::string &ConstraintStr) {
1820 // If this can't be a register or memory, i.e., has to be a constant
1821 // (immediate or symbolic), try to emit it as such.
1822 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1823 if (Info.requiresImmediateConstant()) {
1824 Expr::EvalResult EVResult;
1825 InputExpr->EvaluateAsRValue(EVResult, getContext(), true);
1826
1827 llvm::APSInt IntResult;
1828 if (!EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
1829 getContext()))
1830 llvm_unreachable("Invalid immediate constant!");
1831
1832 return llvm::ConstantInt::get(getLLVMContext(), IntResult);
1833 }
1834
1835 Expr::EvalResult Result;
1836 if (InputExpr->EvaluateAsInt(Result, getContext()))
1837 return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt());
1838 }
1839
1840 if (Info.allowsRegister() || !Info.allowsMemory())
1841 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1842 return EmitScalarExpr(InputExpr);
1843 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1844 return EmitScalarExpr(InputExpr);
1845 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1846 LValue Dest = EmitLValue(InputExpr);
1847 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1848 InputExpr->getExprLoc());
1849 }
1850
1851 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1852 /// asm call instruction. The !srcloc MDNode contains a list of constant
1853 /// integers which are the source locations of the start of each line in the
1854 /// asm.
getAsmSrcLocInfo(const StringLiteral * Str,CodeGenFunction & CGF)1855 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1856 CodeGenFunction &CGF) {
1857 SmallVector<llvm::Metadata *, 8> Locs;
1858 // Add the location of the first line to the MDNode.
1859 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1860 CGF.Int32Ty, Str->getBeginLoc().getRawEncoding())));
1861 StringRef StrVal = Str->getString();
1862 if (!StrVal.empty()) {
1863 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1864 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1865 unsigned StartToken = 0;
1866 unsigned ByteOffset = 0;
1867
1868 // Add the location of the start of each subsequent line of the asm to the
1869 // MDNode.
1870 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1871 if (StrVal[i] != '\n') continue;
1872 SourceLocation LineLoc = Str->getLocationOfByte(
1873 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1874 Locs.push_back(llvm::ConstantAsMetadata::get(
1875 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1876 }
1877 }
1878
1879 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1880 }
1881
EmitAsmStmt(const AsmStmt & S)1882 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1883 // Assemble the final asm string.
1884 std::string AsmString = S.generateAsmString(getContext());
1885
1886 // Get all the output and input constraints together.
1887 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1888 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1889
1890 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1891 StringRef Name;
1892 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1893 Name = GAS->getOutputName(i);
1894 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1895 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1896 assert(IsValid && "Failed to parse output constraint");
1897 OutputConstraintInfos.push_back(Info);
1898 }
1899
1900 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1901 StringRef Name;
1902 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1903 Name = GAS->getInputName(i);
1904 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1905 bool IsValid =
1906 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1907 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1908 InputConstraintInfos.push_back(Info);
1909 }
1910
1911 std::string Constraints;
1912
1913 std::vector<LValue> ResultRegDests;
1914 std::vector<QualType> ResultRegQualTys;
1915 std::vector<llvm::Type *> ResultRegTypes;
1916 std::vector<llvm::Type *> ResultTruncRegTypes;
1917 std::vector<llvm::Type *> ArgTypes;
1918 std::vector<llvm::Value*> Args;
1919
1920 // Keep track of inout constraints.
1921 std::string InOutConstraints;
1922 std::vector<llvm::Value*> InOutArgs;
1923 std::vector<llvm::Type*> InOutArgTypes;
1924
1925 // An inline asm can be marked readonly if it meets the following conditions:
1926 // - it doesn't have any sideeffects
1927 // - it doesn't clobber memory
1928 // - it doesn't return a value by-reference
1929 // It can be marked readnone if it doesn't have any input memory constraints
1930 // in addition to meeting the conditions listed above.
1931 bool ReadOnly = true, ReadNone = true;
1932
1933 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1934 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1935
1936 // Simplify the output constraint.
1937 std::string OutputConstraint(S.getOutputConstraint(i));
1938 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1939 getTarget(), &OutputConstraintInfos);
1940
1941 const Expr *OutExpr = S.getOutputExpr(i);
1942 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1943
1944 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1945 getTarget(), CGM, S,
1946 Info.earlyClobber());
1947
1948 LValue Dest = EmitLValue(OutExpr);
1949 if (!Constraints.empty())
1950 Constraints += ',';
1951
1952 // If this is a register output, then make the inline asm return it
1953 // by-value. If this is a memory result, return the value by-reference.
1954 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1955 Constraints += "=" + OutputConstraint;
1956 ResultRegQualTys.push_back(OutExpr->getType());
1957 ResultRegDests.push_back(Dest);
1958 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1959 ResultTruncRegTypes.push_back(ResultRegTypes.back());
1960
1961 // If this output is tied to an input, and if the input is larger, then
1962 // we need to set the actual result type of the inline asm node to be the
1963 // same as the input type.
1964 if (Info.hasMatchingInput()) {
1965 unsigned InputNo;
1966 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1967 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1968 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1969 break;
1970 }
1971 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1972
1973 QualType InputTy = S.getInputExpr(InputNo)->getType();
1974 QualType OutputType = OutExpr->getType();
1975
1976 uint64_t InputSize = getContext().getTypeSize(InputTy);
1977 if (getContext().getTypeSize(OutputType) < InputSize) {
1978 // Form the asm to return the value as a larger integer or fp type.
1979 ResultRegTypes.back() = ConvertType(InputTy);
1980 }
1981 }
1982 if (llvm::Type* AdjTy =
1983 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1984 ResultRegTypes.back()))
1985 ResultRegTypes.back() = AdjTy;
1986 else {
1987 CGM.getDiags().Report(S.getAsmLoc(),
1988 diag::err_asm_invalid_type_in_input)
1989 << OutExpr->getType() << OutputConstraint;
1990 }
1991
1992 // Update largest vector width for any vector types.
1993 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back()))
1994 LargestVectorWidth = std::max(LargestVectorWidth,
1995 VT->getPrimitiveSizeInBits());
1996 } else {
1997 ArgTypes.push_back(Dest.getAddress().getType());
1998 Args.push_back(Dest.getPointer());
1999 Constraints += "=*";
2000 Constraints += OutputConstraint;
2001 ReadOnly = ReadNone = false;
2002 }
2003
2004 if (Info.isReadWrite()) {
2005 InOutConstraints += ',';
2006
2007 const Expr *InputExpr = S.getOutputExpr(i);
2008 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
2009 InOutConstraints,
2010 InputExpr->getExprLoc());
2011
2012 if (llvm::Type* AdjTy =
2013 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
2014 Arg->getType()))
2015 Arg = Builder.CreateBitCast(Arg, AdjTy);
2016
2017 // Update largest vector width for any vector types.
2018 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2019 LargestVectorWidth = std::max(LargestVectorWidth,
2020 VT->getPrimitiveSizeInBits());
2021 if (Info.allowsRegister())
2022 InOutConstraints += llvm::utostr(i);
2023 else
2024 InOutConstraints += OutputConstraint;
2025
2026 InOutArgTypes.push_back(Arg->getType());
2027 InOutArgs.push_back(Arg);
2028 }
2029 }
2030
2031 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
2032 // to the return value slot. Only do this when returning in registers.
2033 if (isa<MSAsmStmt>(&S)) {
2034 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
2035 if (RetAI.isDirect() || RetAI.isExtend()) {
2036 // Make a fake lvalue for the return value slot.
2037 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
2038 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
2039 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
2040 ResultRegDests, AsmString, S.getNumOutputs());
2041 SawAsmBlock = true;
2042 }
2043 }
2044
2045 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
2046 const Expr *InputExpr = S.getInputExpr(i);
2047
2048 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2049
2050 if (Info.allowsMemory())
2051 ReadNone = false;
2052
2053 if (!Constraints.empty())
2054 Constraints += ',';
2055
2056 // Simplify the input constraint.
2057 std::string InputConstraint(S.getInputConstraint(i));
2058 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
2059 &OutputConstraintInfos);
2060
2061 InputConstraint = AddVariableConstraints(
2062 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
2063 getTarget(), CGM, S, false /* No EarlyClobber */);
2064
2065 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
2066
2067 // If this input argument is tied to a larger output result, extend the
2068 // input to be the same size as the output. The LLVM backend wants to see
2069 // the input and output of a matching constraint be the same size. Note
2070 // that GCC does not define what the top bits are here. We use zext because
2071 // that is usually cheaper, but LLVM IR should really get an anyext someday.
2072 if (Info.hasTiedOperand()) {
2073 unsigned Output = Info.getTiedOperand();
2074 QualType OutputType = S.getOutputExpr(Output)->getType();
2075 QualType InputTy = InputExpr->getType();
2076
2077 if (getContext().getTypeSize(OutputType) >
2078 getContext().getTypeSize(InputTy)) {
2079 // Use ptrtoint as appropriate so that we can do our extension.
2080 if (isa<llvm::PointerType>(Arg->getType()))
2081 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
2082 llvm::Type *OutputTy = ConvertType(OutputType);
2083 if (isa<llvm::IntegerType>(OutputTy))
2084 Arg = Builder.CreateZExt(Arg, OutputTy);
2085 else if (isa<llvm::PointerType>(OutputTy))
2086 Arg = Builder.CreateZExt(Arg, IntPtrTy);
2087 else {
2088 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
2089 Arg = Builder.CreateFPExt(Arg, OutputTy);
2090 }
2091 }
2092 }
2093 if (llvm::Type* AdjTy =
2094 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
2095 Arg->getType()))
2096 Arg = Builder.CreateBitCast(Arg, AdjTy);
2097 else
2098 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2099 << InputExpr->getType() << InputConstraint;
2100
2101 // Update largest vector width for any vector types.
2102 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType()))
2103 LargestVectorWidth = std::max(LargestVectorWidth,
2104 VT->getPrimitiveSizeInBits());
2105
2106 ArgTypes.push_back(Arg->getType());
2107 Args.push_back(Arg);
2108 Constraints += InputConstraint;
2109 }
2110
2111 // Append the "input" part of inout constraints last.
2112 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2113 ArgTypes.push_back(InOutArgTypes[i]);
2114 Args.push_back(InOutArgs[i]);
2115 }
2116 Constraints += InOutConstraints;
2117
2118 // Clobbers
2119 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2120 StringRef Clobber = S.getClobber(i);
2121
2122 if (Clobber == "memory")
2123 ReadOnly = ReadNone = false;
2124 else if (Clobber != "cc")
2125 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2126
2127 if (!Constraints.empty())
2128 Constraints += ',';
2129
2130 Constraints += "~{";
2131 Constraints += Clobber;
2132 Constraints += '}';
2133 }
2134
2135 // Add machine specific clobbers
2136 std::string MachineClobbers = getTarget().getClobbers();
2137 if (!MachineClobbers.empty()) {
2138 if (!Constraints.empty())
2139 Constraints += ',';
2140 Constraints += MachineClobbers;
2141 }
2142
2143 llvm::Type *ResultType;
2144 if (ResultRegTypes.empty())
2145 ResultType = VoidTy;
2146 else if (ResultRegTypes.size() == 1)
2147 ResultType = ResultRegTypes[0];
2148 else
2149 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2150
2151 llvm::FunctionType *FTy =
2152 llvm::FunctionType::get(ResultType, ArgTypes, false);
2153
2154 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2155 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2156 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2157 llvm::InlineAsm *IA =
2158 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2159 /* IsAlignStack */ false, AsmDialect);
2160 llvm::CallInst *Result =
2161 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
2162 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2163 llvm::Attribute::NoUnwind);
2164
2165 // Attach readnone and readonly attributes.
2166 if (!HasSideEffect) {
2167 if (ReadNone)
2168 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2169 llvm::Attribute::ReadNone);
2170 else if (ReadOnly)
2171 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2172 llvm::Attribute::ReadOnly);
2173 }
2174
2175 // Slap the source location of the inline asm into a !srcloc metadata on the
2176 // call.
2177 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2178 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2179 *this));
2180 } else {
2181 // At least put the line number on MS inline asm blobs.
2182 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2183 Result->setMetadata("srcloc",
2184 llvm::MDNode::get(getLLVMContext(),
2185 llvm::ConstantAsMetadata::get(Loc)));
2186 }
2187
2188 if (getLangOpts().assumeFunctionsAreConvergent()) {
2189 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as
2190 // convergent (meaning, they may call an intrinsically convergent op, such
2191 // as bar.sync, and so can't have certain optimizations applied around
2192 // them).
2193 Result->addAttribute(llvm::AttributeList::FunctionIndex,
2194 llvm::Attribute::Convergent);
2195 }
2196
2197 // Extract all of the register value results from the asm.
2198 std::vector<llvm::Value*> RegResults;
2199 if (ResultRegTypes.size() == 1) {
2200 RegResults.push_back(Result);
2201 } else {
2202 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2203 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2204 RegResults.push_back(Tmp);
2205 }
2206 }
2207
2208 assert(RegResults.size() == ResultRegTypes.size());
2209 assert(RegResults.size() == ResultTruncRegTypes.size());
2210 assert(RegResults.size() == ResultRegDests.size());
2211 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2212 llvm::Value *Tmp = RegResults[i];
2213
2214 // If the result type of the LLVM IR asm doesn't match the result type of
2215 // the expression, do the conversion.
2216 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2217 llvm::Type *TruncTy = ResultTruncRegTypes[i];
2218
2219 // Truncate the integer result to the right size, note that TruncTy can be
2220 // a pointer.
2221 if (TruncTy->isFloatingPointTy())
2222 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2223 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2224 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2225 Tmp = Builder.CreateTrunc(Tmp,
2226 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2227 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2228 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2229 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2230 Tmp = Builder.CreatePtrToInt(Tmp,
2231 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2232 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2233 } else if (TruncTy->isIntegerTy()) {
2234 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy);
2235 } else if (TruncTy->isVectorTy()) {
2236 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2237 }
2238 }
2239
2240 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2241 }
2242 }
2243
InitCapturedStruct(const CapturedStmt & S)2244 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2245 const RecordDecl *RD = S.getCapturedRecordDecl();
2246 QualType RecordTy = getContext().getRecordType(RD);
2247
2248 // Initialize the captured struct.
2249 LValue SlotLV =
2250 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2251
2252 RecordDecl::field_iterator CurField = RD->field_begin();
2253 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2254 E = S.capture_init_end();
2255 I != E; ++I, ++CurField) {
2256 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2257 if (CurField->hasCapturedVLAType()) {
2258 auto VAT = CurField->getCapturedVLAType();
2259 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2260 } else {
2261 EmitInitializerForField(*CurField, LV, *I);
2262 }
2263 }
2264
2265 return SlotLV;
2266 }
2267
2268 /// Generate an outlined function for the body of a CapturedStmt, store any
2269 /// captured variables into the captured struct, and call the outlined function.
2270 llvm::Function *
EmitCapturedStmt(const CapturedStmt & S,CapturedRegionKind K)2271 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2272 LValue CapStruct = InitCapturedStruct(S);
2273
2274 // Emit the CapturedDecl
2275 CodeGenFunction CGF(CGM, true);
2276 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2277 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2278 delete CGF.CapturedStmtInfo;
2279
2280 // Emit call to the helper function.
2281 EmitCallOrInvoke(F, CapStruct.getPointer());
2282
2283 return F;
2284 }
2285
GenerateCapturedStmtArgument(const CapturedStmt & S)2286 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2287 LValue CapStruct = InitCapturedStruct(S);
2288 return CapStruct.getAddress();
2289 }
2290
2291 /// Creates the outlined function for a CapturedStmt.
2292 llvm::Function *
GenerateCapturedStmtFunction(const CapturedStmt & S)2293 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2294 assert(CapturedStmtInfo &&
2295 "CapturedStmtInfo should be set when generating the captured function");
2296 const CapturedDecl *CD = S.getCapturedDecl();
2297 const RecordDecl *RD = S.getCapturedRecordDecl();
2298 SourceLocation Loc = S.getBeginLoc();
2299 assert(CD->hasBody() && "missing CapturedDecl body");
2300
2301 // Build the argument list.
2302 ASTContext &Ctx = CGM.getContext();
2303 FunctionArgList Args;
2304 Args.append(CD->param_begin(), CD->param_end());
2305
2306 // Create the function declaration.
2307 const CGFunctionInfo &FuncInfo =
2308 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2309 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2310
2311 llvm::Function *F =
2312 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2313 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2314 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2315 if (CD->isNothrow())
2316 F->addFnAttr(llvm::Attribute::NoUnwind);
2317
2318 // Generate the function.
2319 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
2320 CD->getBody()->getBeginLoc());
2321 // Set the context parameter in CapturedStmtInfo.
2322 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2323 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2324
2325 // Initialize variable-length arrays.
2326 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2327 Ctx.getTagDeclType(RD));
2328 for (auto *FD : RD->fields()) {
2329 if (FD->hasCapturedVLAType()) {
2330 auto *ExprArg =
2331 EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc())
2332 .getScalarVal();
2333 auto VAT = FD->getCapturedVLAType();
2334 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2335 }
2336 }
2337
2338 // If 'this' is captured, load it into CXXThisValue.
2339 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2340 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2341 LValue ThisLValue = EmitLValueForField(Base, FD);
2342 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2343 }
2344
2345 PGO.assignRegionCounters(GlobalDecl(CD), F);
2346 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2347 FinishFunction(CD->getBodyRBrace());
2348
2349 return F;
2350 }
2351