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 "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "clang/Basic/PrettyStackTrace.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/InlineAsm.h" 22 #include "llvm/Intrinsics.h" 23 #include "llvm/Target/TargetData.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===----------------------------------------------------------------------===// 28 // Statement Emission 29 //===----------------------------------------------------------------------===// 30 31 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 32 if (CGDebugInfo *DI = getDebugInfo()) { 33 if (isa<DeclStmt>(S)) 34 DI->setLocation(S->getLocEnd()); 35 else 36 DI->setLocation(S->getLocStart()); 37 DI->UpdateLineDirectiveRegion(Builder); 38 DI->EmitStopPoint(Builder); 39 } 40 } 41 42 void CodeGenFunction::EmitStmt(const Stmt *S) { 43 assert(S && "Null statement?"); 44 45 // Check if we can handle this without bothering to generate an 46 // insert point or debug info. 47 if (EmitSimpleStmt(S)) 48 return; 49 50 // Check if we are generating unreachable code. 51 if (!HaveInsertPoint()) { 52 // If so, and the statement doesn't contain a label, then we do not need to 53 // generate actual code. This is safe because (1) the current point is 54 // unreachable, so we don't need to execute the code, and (2) we've already 55 // handled the statements which update internal data structures (like the 56 // local variable map) which could be used by subsequent statements. 57 if (!ContainsLabel(S)) { 58 // Verify that any decl statements were handled as simple, they may be in 59 // scope of subsequent reachable statements. 60 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 61 return; 62 } 63 64 // Otherwise, make a new block to hold the code. 65 EnsureInsertPoint(); 66 } 67 68 // Generate a stoppoint if we are emitting debug info. 69 EmitStopPoint(S); 70 71 switch (S->getStmtClass()) { 72 case Stmt::NoStmtClass: 73 case Stmt::CXXCatchStmtClass: 74 case Stmt::SwitchCaseClass: 75 llvm_unreachable("invalid statement class to emit generically"); 76 case Stmt::NullStmtClass: 77 case Stmt::CompoundStmtClass: 78 case Stmt::DeclStmtClass: 79 case Stmt::LabelStmtClass: 80 case Stmt::GotoStmtClass: 81 case Stmt::BreakStmtClass: 82 case Stmt::ContinueStmtClass: 83 case Stmt::DefaultStmtClass: 84 case Stmt::CaseStmtClass: 85 llvm_unreachable("should have emitted these statements as simple"); 86 87 #define STMT(Type, Base) 88 #define ABSTRACT_STMT(Op) 89 #define EXPR(Type, Base) \ 90 case Stmt::Type##Class: 91 #include "clang/AST/StmtNodes.inc" 92 { 93 // Remember the block we came in on. 94 llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 95 assert(incoming && "expression emission must have an insertion point"); 96 97 EmitIgnoredExpr(cast<Expr>(S)); 98 99 llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 100 assert(outgoing && "expression emission cleared block!"); 101 102 // The expression emitters assume (reasonably!) that the insertion 103 // point is always set. To maintain that, the call-emission code 104 // for noreturn functions has to enter a new block with no 105 // predecessors. We want to kill that block and mark the current 106 // insertion point unreachable in the common case of a call like 107 // "exit();". Since expression emission doesn't otherwise create 108 // blocks with no predecessors, we can just test for that. 109 // However, we must be careful not to do this to our incoming 110 // block, because *statement* emission does sometimes create 111 // reachable blocks which will have no predecessors until later in 112 // the function. This occurs with, e.g., labels that are not 113 // reachable by fallthrough. 114 if (incoming != outgoing && outgoing->use_empty()) { 115 outgoing->eraseFromParent(); 116 Builder.ClearInsertionPoint(); 117 } 118 break; 119 } 120 121 case Stmt::IndirectGotoStmtClass: 122 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 123 124 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 125 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break; 126 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break; 127 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break; 128 129 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 130 131 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 132 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 133 134 case Stmt::ObjCAtTryStmtClass: 135 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 136 break; 137 case Stmt::ObjCAtCatchStmtClass: 138 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt"); 139 break; 140 case Stmt::ObjCAtFinallyStmtClass: 141 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt"); 142 break; 143 case Stmt::ObjCAtThrowStmtClass: 144 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 145 break; 146 case Stmt::ObjCAtSynchronizedStmtClass: 147 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 148 break; 149 case Stmt::ObjCForCollectionStmtClass: 150 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 151 break; 152 153 case Stmt::CXXTryStmtClass: 154 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 155 break; 156 } 157 } 158 159 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) { 160 switch (S->getStmtClass()) { 161 default: return false; 162 case Stmt::NullStmtClass: break; 163 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break; 164 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break; 165 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break; 166 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break; 167 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break; 168 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break; 169 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break; 170 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break; 171 } 172 173 return true; 174 } 175 176 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 177 /// this captures the expression result of the last sub-statement and returns it 178 /// (for use by the statement expression extension). 179 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 180 AggValueSlot AggSlot) { 181 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 182 "LLVM IR generation of compound statement ('{}')"); 183 184 CGDebugInfo *DI = getDebugInfo(); 185 if (DI) { 186 DI->setLocation(S.getLBracLoc()); 187 DI->EmitRegionStart(Builder); 188 } 189 190 // Keep track of the current cleanup stack depth. 191 RunCleanupsScope Scope(*this); 192 193 for (CompoundStmt::const_body_iterator I = S.body_begin(), 194 E = S.body_end()-GetLast; I != E; ++I) 195 EmitStmt(*I); 196 197 if (DI) { 198 DI->setLocation(S.getRBracLoc()); 199 DI->EmitRegionEnd(Builder); 200 } 201 202 RValue RV; 203 if (!GetLast) 204 RV = RValue::get(0); 205 else { 206 // We have to special case labels here. They are statements, but when put 207 // at the end of a statement expression, they yield the value of their 208 // subexpression. Handle this by walking through all labels we encounter, 209 // emitting them before we evaluate the subexpr. 210 const Stmt *LastStmt = S.body_back(); 211 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) { 212 EmitLabel(*LS); 213 LastStmt = LS->getSubStmt(); 214 } 215 216 EnsureInsertPoint(); 217 218 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot); 219 } 220 221 return RV; 222 } 223 224 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 225 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 226 227 // If there is a cleanup stack, then we it isn't worth trying to 228 // simplify this block (we would need to remove it from the scope map 229 // and cleanup entry). 230 if (!EHStack.empty()) 231 return; 232 233 // Can only simplify direct branches. 234 if (!BI || !BI->isUnconditional()) 235 return; 236 237 BB->replaceAllUsesWith(BI->getSuccessor(0)); 238 BI->eraseFromParent(); 239 BB->eraseFromParent(); 240 } 241 242 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 243 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 244 245 // Fall out of the current block (if necessary). 246 EmitBranch(BB); 247 248 if (IsFinished && BB->use_empty()) { 249 delete BB; 250 return; 251 } 252 253 // Place the block after the current block, if possible, or else at 254 // the end of the function. 255 if (CurBB && CurBB->getParent()) 256 CurFn->getBasicBlockList().insertAfter(CurBB, BB); 257 else 258 CurFn->getBasicBlockList().push_back(BB); 259 Builder.SetInsertPoint(BB); 260 } 261 262 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 263 // Emit a branch from the current block to the target one if this 264 // was a real block. If this was just a fall-through block after a 265 // terminator, don't emit it. 266 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 267 268 if (!CurBB || CurBB->getTerminator()) { 269 // If there is no insert point or the previous block is already 270 // terminated, don't touch it. 271 } else { 272 // Otherwise, create a fall-through branch. 273 Builder.CreateBr(Target); 274 } 275 276 Builder.ClearInsertionPoint(); 277 } 278 279 CodeGenFunction::JumpDest 280 CodeGenFunction::getJumpDestForLabel(const LabelStmt *S) { 281 JumpDest &Dest = LabelMap[S]; 282 if (Dest.isValid()) return Dest; 283 284 // Create, but don't insert, the new block. 285 Dest = JumpDest(createBasicBlock(S->getName()), 286 EHScopeStack::stable_iterator::invalid(), 287 NextCleanupDestIndex++); 288 return Dest; 289 } 290 291 void CodeGenFunction::EmitLabel(const LabelStmt &S) { 292 JumpDest &Dest = LabelMap[&S]; 293 294 // If we didn't need a forward reference to this label, just go 295 // ahead and create a destination at the current scope. 296 if (!Dest.isValid()) { 297 Dest = getJumpDestInCurrentScope(S.getName()); 298 299 // Otherwise, we need to give this label a target depth and remove 300 // it from the branch-fixups list. 301 } else { 302 assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 303 Dest = JumpDest(Dest.getBlock(), 304 EHStack.stable_begin(), 305 Dest.getDestIndex()); 306 307 ResolveBranchFixups(Dest.getBlock()); 308 } 309 310 EmitBlock(Dest.getBlock()); 311 } 312 313 314 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 315 EmitLabel(S); 316 EmitStmt(S.getSubStmt()); 317 } 318 319 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 320 // If this code is reachable then emit a stop point (if generating 321 // debug info). We have to do this ourselves because we are on the 322 // "simple" statement path. 323 if (HaveInsertPoint()) 324 EmitStopPoint(&S); 325 326 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel())); 327 } 328 329 330 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 331 if (const LabelStmt *Target = S.getConstantTarget()) { 332 EmitBranchThroughCleanup(getJumpDestForLabel(Target)); 333 return; 334 } 335 336 // Ensure that we have an i8* for our PHI node. 337 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 338 llvm::Type::getInt8PtrTy(VMContext), 339 "addr"); 340 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 341 342 343 // Get the basic block for the indirect goto. 344 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 345 346 // The first instruction in the block has to be the PHI for the switch dest, 347 // add an entry for this branch. 348 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 349 350 EmitBranch(IndGotoBB); 351 } 352 353 void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 354 // C99 6.8.4.1: The first substatement is executed if the expression compares 355 // unequal to 0. The condition must be a scalar type. 356 RunCleanupsScope ConditionScope(*this); 357 358 if (S.getConditionVariable()) 359 EmitAutoVarDecl(*S.getConditionVariable()); 360 361 // If the condition constant folds and can be elided, try to avoid emitting 362 // the condition and the dead arm of the if/else. 363 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) { 364 // Figure out which block (then or else) is executed. 365 const Stmt *Executed = S.getThen(), *Skipped = S.getElse(); 366 if (Cond == -1) // Condition false? 367 std::swap(Executed, Skipped); 368 369 // If the skipped block has no labels in it, just emit the executed block. 370 // This avoids emitting dead code and simplifies the CFG substantially. 371 if (!ContainsLabel(Skipped)) { 372 if (Executed) { 373 RunCleanupsScope ExecutedScope(*this); 374 EmitStmt(Executed); 375 } 376 return; 377 } 378 } 379 380 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 381 // the conditional branch. 382 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 383 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 384 llvm::BasicBlock *ElseBlock = ContBlock; 385 if (S.getElse()) 386 ElseBlock = createBasicBlock("if.else"); 387 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); 388 389 // Emit the 'then' code. 390 EmitBlock(ThenBlock); 391 { 392 RunCleanupsScope ThenScope(*this); 393 EmitStmt(S.getThen()); 394 } 395 EmitBranch(ContBlock); 396 397 // Emit the 'else' code if present. 398 if (const Stmt *Else = S.getElse()) { 399 EmitBlock(ElseBlock); 400 { 401 RunCleanupsScope ElseScope(*this); 402 EmitStmt(Else); 403 } 404 EmitBranch(ContBlock); 405 } 406 407 // Emit the continuation block for code after the if. 408 EmitBlock(ContBlock, true); 409 } 410 411 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { 412 // Emit the header for the loop, which will also become 413 // the continue target. 414 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond"); 415 EmitBlock(LoopHeader.getBlock()); 416 417 // Create an exit block for when the condition fails, which will 418 // also become the break target. 419 JumpDest LoopExit = getJumpDestInCurrentScope("while.end"); 420 421 // Store the blocks to use for break and continue. 422 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader)); 423 424 // C++ [stmt.while]p2: 425 // When the condition of a while statement is a declaration, the 426 // scope of the variable that is declared extends from its point 427 // of declaration (3.3.2) to the end of the while statement. 428 // [...] 429 // The object created in a condition is destroyed and created 430 // with each iteration of the loop. 431 RunCleanupsScope ConditionScope(*this); 432 433 if (S.getConditionVariable()) 434 EmitAutoVarDecl(*S.getConditionVariable()); 435 436 // Evaluate the conditional in the while header. C99 6.8.5.1: The 437 // evaluation of the controlling expression takes place before each 438 // execution of the loop body. 439 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 440 441 // while(1) is common, avoid extra exit blocks. Be sure 442 // to correctly handle break/continue though. 443 bool EmitBoolCondBranch = true; 444 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 445 if (C->isOne()) 446 EmitBoolCondBranch = false; 447 448 // As long as the condition is true, go to the loop body. 449 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 450 if (EmitBoolCondBranch) { 451 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 452 if (ConditionScope.requiresCleanups()) 453 ExitBlock = createBasicBlock("while.exit"); 454 455 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 456 457 if (ExitBlock != LoopExit.getBlock()) { 458 EmitBlock(ExitBlock); 459 EmitBranchThroughCleanup(LoopExit); 460 } 461 } 462 463 // Emit the loop body. We have to emit this in a cleanup scope 464 // because it might be a singleton DeclStmt. 465 { 466 RunCleanupsScope BodyScope(*this); 467 EmitBlock(LoopBody); 468 EmitStmt(S.getBody()); 469 } 470 471 BreakContinueStack.pop_back(); 472 473 // Immediately force cleanup. 474 ConditionScope.ForceCleanup(); 475 476 // Branch to the loop header again. 477 EmitBranch(LoopHeader.getBlock()); 478 479 // Emit the exit block. 480 EmitBlock(LoopExit.getBlock(), true); 481 482 // The LoopHeader typically is just a branch if we skipped emitting 483 // a branch, try to erase it. 484 if (!EmitBoolCondBranch) 485 SimplifyForwardingBlocks(LoopHeader.getBlock()); 486 } 487 488 void CodeGenFunction::EmitDoStmt(const DoStmt &S) { 489 JumpDest LoopExit = getJumpDestInCurrentScope("do.end"); 490 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond"); 491 492 // Store the blocks to use for break and continue. 493 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond)); 494 495 // Emit the body of the loop. 496 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 497 EmitBlock(LoopBody); 498 { 499 RunCleanupsScope BodyScope(*this); 500 EmitStmt(S.getBody()); 501 } 502 503 BreakContinueStack.pop_back(); 504 505 EmitBlock(LoopCond.getBlock()); 506 507 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 508 // after each execution of the loop body." 509 510 // Evaluate the conditional in the while header. 511 // C99 6.8.5p2/p4: The first substatement is executed if the expression 512 // compares unequal to 0. The condition must be a scalar type. 513 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 514 515 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 516 // to correctly handle break/continue though. 517 bool EmitBoolCondBranch = true; 518 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 519 if (C->isZero()) 520 EmitBoolCondBranch = false; 521 522 // As long as the condition is true, iterate the loop. 523 if (EmitBoolCondBranch) 524 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock()); 525 526 // Emit the exit block. 527 EmitBlock(LoopExit.getBlock()); 528 529 // The DoCond block typically is just a branch if we skipped 530 // emitting a branch, try to erase it. 531 if (!EmitBoolCondBranch) 532 SimplifyForwardingBlocks(LoopCond.getBlock()); 533 } 534 535 void CodeGenFunction::EmitForStmt(const ForStmt &S) { 536 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 537 538 RunCleanupsScope ForScope(*this); 539 540 CGDebugInfo *DI = getDebugInfo(); 541 if (DI) { 542 DI->setLocation(S.getSourceRange().getBegin()); 543 DI->EmitRegionStart(Builder); 544 } 545 546 // Evaluate the first part before the loop. 547 if (S.getInit()) 548 EmitStmt(S.getInit()); 549 550 // Start the loop with a block that tests the condition. 551 // If there's an increment, the continue scope will be overwritten 552 // later. 553 JumpDest Continue = getJumpDestInCurrentScope("for.cond"); 554 llvm::BasicBlock *CondBlock = Continue.getBlock(); 555 EmitBlock(CondBlock); 556 557 // Create a cleanup scope for the condition variable cleanups. 558 RunCleanupsScope ConditionScope(*this); 559 560 llvm::Value *BoolCondVal = 0; 561 if (S.getCond()) { 562 // If the for statement has a condition scope, emit the local variable 563 // declaration. 564 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 565 if (S.getConditionVariable()) { 566 EmitAutoVarDecl(*S.getConditionVariable()); 567 } 568 569 // If there are any cleanups between here and the loop-exit scope, 570 // create a block to stage a loop exit along. 571 if (ForScope.requiresCleanups()) 572 ExitBlock = createBasicBlock("for.cond.cleanup"); 573 574 // As long as the condition is true, iterate the loop. 575 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 576 577 // C99 6.8.5p2/p4: The first substatement is executed if the expression 578 // compares unequal to 0. The condition must be a scalar type. 579 BoolCondVal = EvaluateExprAsBool(S.getCond()); 580 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock); 581 582 if (ExitBlock != LoopExit.getBlock()) { 583 EmitBlock(ExitBlock); 584 EmitBranchThroughCleanup(LoopExit); 585 } 586 587 EmitBlock(ForBody); 588 } else { 589 // Treat it as a non-zero constant. Don't even create a new block for the 590 // body, just fall into it. 591 } 592 593 // If the for loop doesn't have an increment we can just use the 594 // condition as the continue block. Otherwise we'll need to create 595 // a block for it (in the current scope, i.e. in the scope of the 596 // condition), and that we will become our continue block. 597 if (S.getInc()) 598 Continue = getJumpDestInCurrentScope("for.inc"); 599 600 // Store the blocks to use for break and continue. 601 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 602 603 { 604 // Create a separate cleanup scope for the body, in case it is not 605 // a compound statement. 606 RunCleanupsScope BodyScope(*this); 607 EmitStmt(S.getBody()); 608 } 609 610 // If there is an increment, emit it next. 611 if (S.getInc()) { 612 EmitBlock(Continue.getBlock()); 613 EmitStmt(S.getInc()); 614 } 615 616 BreakContinueStack.pop_back(); 617 618 ConditionScope.ForceCleanup(); 619 EmitBranch(CondBlock); 620 621 ForScope.ForceCleanup(); 622 623 if (DI) { 624 DI->setLocation(S.getSourceRange().getEnd()); 625 DI->EmitRegionEnd(Builder); 626 } 627 628 // Emit the fall-through block. 629 EmitBlock(LoopExit.getBlock(), true); 630 } 631 632 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 633 if (RV.isScalar()) { 634 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 635 } else if (RV.isAggregate()) { 636 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty); 637 } else { 638 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false); 639 } 640 EmitBranchThroughCleanup(ReturnBlock); 641 } 642 643 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 644 /// if the function returns void, or may be missing one if the function returns 645 /// non-void. Fun stuff :). 646 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 647 // Emit the result value, even if unused, to evalute the side effects. 648 const Expr *RV = S.getRetValue(); 649 650 // FIXME: Clean this up by using an LValue for ReturnTemp, 651 // EmitStoreThroughLValue, and EmitAnyExpr. 652 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() && 653 !Target.useGlobalsForAutomaticVariables()) { 654 // Apply the named return value optimization for this return statement, 655 // which means doing nothing: the appropriate result has already been 656 // constructed into the NRVO variable. 657 658 // If there is an NRVO flag for this variable, set it to 1 into indicate 659 // that the cleanup code should not destroy the variable. 660 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) { 661 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext); 662 llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1); 663 Builder.CreateStore(One, NRVOFlag); 664 } 665 } else if (!ReturnValue) { 666 // Make sure not to return anything, but evaluate the expression 667 // for side effects. 668 if (RV) 669 EmitAnyExpr(RV); 670 } else if (RV == 0) { 671 // Do nothing (return value is left uninitialized) 672 } else if (FnRetTy->isReferenceType()) { 673 // If this function returns a reference, take the address of the expression 674 // rather than the value. 675 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0); 676 Builder.CreateStore(Result.getScalarVal(), ReturnValue); 677 } else if (!hasAggregateLLVMType(RV->getType())) { 678 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 679 } else if (RV->getType()->isAnyComplexType()) { 680 EmitComplexExprIntoAddr(RV, ReturnValue, false); 681 } else { 682 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true)); 683 } 684 685 EmitBranchThroughCleanup(ReturnBlock); 686 } 687 688 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 689 // As long as debug info is modeled with instructions, we have to ensure we 690 // have a place to insert here and write the stop point here. 691 if (getDebugInfo()) { 692 EnsureInsertPoint(); 693 EmitStopPoint(&S); 694 } 695 696 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end(); 697 I != E; ++I) 698 EmitDecl(**I); 699 } 700 701 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 702 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 703 704 // If this code is reachable then emit a stop point (if generating 705 // debug info). We have to do this ourselves because we are on the 706 // "simple" statement path. 707 if (HaveInsertPoint()) 708 EmitStopPoint(&S); 709 710 JumpDest Block = BreakContinueStack.back().BreakBlock; 711 EmitBranchThroughCleanup(Block); 712 } 713 714 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 715 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 716 717 // If this code is reachable then emit a stop point (if generating 718 // debug info). We have to do this ourselves because we are on the 719 // "simple" statement path. 720 if (HaveInsertPoint()) 721 EmitStopPoint(&S); 722 723 JumpDest Block = BreakContinueStack.back().ContinueBlock; 724 EmitBranchThroughCleanup(Block); 725 } 726 727 /// EmitCaseStmtRange - If case statement range is not too big then 728 /// add multiple cases to switch instruction, one for each value within 729 /// the range. If range is too big then emit "if" condition check. 730 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { 731 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 732 733 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext()); 734 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext()); 735 736 // Emit the code for this case. We do this first to make sure it is 737 // properly chained from our predecessor before generating the 738 // switch machinery to enter this block. 739 EmitBlock(createBasicBlock("sw.bb")); 740 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 741 EmitStmt(S.getSubStmt()); 742 743 // If range is empty, do nothing. 744 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 745 return; 746 747 llvm::APInt Range = RHS - LHS; 748 // FIXME: parameters such as this should not be hardcoded. 749 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 750 // Range is small enough to add multiple switch instruction cases. 751 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) { 752 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest); 753 LHS++; 754 } 755 return; 756 } 757 758 // The range is too big. Emit "if" condition into a new block, 759 // making sure to save and restore the current insertion point. 760 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 761 762 // Push this test onto the chain of range checks (which terminates 763 // in the default basic block). The switch's default will be changed 764 // to the top of this chain after switch emission is complete. 765 llvm::BasicBlock *FalseDest = CaseRangeBlock; 766 CaseRangeBlock = createBasicBlock("sw.caserange"); 767 768 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 769 Builder.SetInsertPoint(CaseRangeBlock); 770 771 // Emit range check. 772 llvm::Value *Diff = 773 Builder.CreateSub(SwitchInsn->getCondition(), 774 llvm::ConstantInt::get(VMContext, LHS), "tmp"); 775 llvm::Value *Cond = 776 Builder.CreateICmpULE(Diff, 777 llvm::ConstantInt::get(VMContext, Range), "tmp"); 778 Builder.CreateCondBr(Cond, CaseDest, FalseDest); 779 780 // Restore the appropriate insertion point. 781 if (RestoreBB) 782 Builder.SetInsertPoint(RestoreBB); 783 else 784 Builder.ClearInsertionPoint(); 785 } 786 787 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { 788 if (S.getRHS()) { 789 EmitCaseStmtRange(S); 790 return; 791 } 792 793 EmitBlock(createBasicBlock("sw.bb")); 794 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 795 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext()); 796 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 797 798 // Recursively emitting the statement is acceptable, but is not wonderful for 799 // code where we have many case statements nested together, i.e.: 800 // case 1: 801 // case 2: 802 // case 3: etc. 803 // Handling this recursively will create a new block for each case statement 804 // that falls through to the next case which is IR intensive. It also causes 805 // deep recursion which can run into stack depth limitations. Handle 806 // sequential non-range case statements specially. 807 const CaseStmt *CurCase = &S; 808 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 809 810 // Otherwise, iteratively add consequtive cases to this switch stmt. 811 while (NextCase && NextCase->getRHS() == 0) { 812 CurCase = NextCase; 813 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext()); 814 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 815 816 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 817 } 818 819 // Normal default recursion for non-cases. 820 EmitStmt(CurCase->getSubStmt()); 821 } 822 823 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { 824 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 825 assert(DefaultBlock->empty() && 826 "EmitDefaultStmt: Default block already defined?"); 827 EmitBlock(DefaultBlock); 828 EmitStmt(S.getSubStmt()); 829 } 830 831 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 832 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog"); 833 834 RunCleanupsScope ConditionScope(*this); 835 836 if (S.getConditionVariable()) 837 EmitAutoVarDecl(*S.getConditionVariable()); 838 839 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 840 841 // Handle nested switch statements. 842 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 843 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 844 845 // Create basic block to hold stuff that comes after switch 846 // statement. We also need to create a default block now so that 847 // explicit case ranges tests can have a place to jump to on 848 // failure. 849 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 850 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 851 CaseRangeBlock = DefaultBlock; 852 853 // Clear the insertion point to indicate we are in unreachable code. 854 Builder.ClearInsertionPoint(); 855 856 // All break statements jump to NextBlock. If BreakContinueStack is non empty 857 // then reuse last ContinueBlock. 858 JumpDest OuterContinue; 859 if (!BreakContinueStack.empty()) 860 OuterContinue = BreakContinueStack.back().ContinueBlock; 861 862 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue)); 863 864 // Emit switch body. 865 EmitStmt(S.getBody()); 866 867 BreakContinueStack.pop_back(); 868 869 // Update the default block in case explicit case range tests have 870 // been chained on top. 871 SwitchInsn->setSuccessor(0, CaseRangeBlock); 872 873 // If a default was never emitted: 874 if (!DefaultBlock->getParent()) { 875 // If we have cleanups, emit the default block so that there's a 876 // place to jump through the cleanups from. 877 if (ConditionScope.requiresCleanups()) { 878 EmitBlock(DefaultBlock); 879 880 // Otherwise, just forward the default block to the switch end. 881 } else { 882 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock()); 883 delete DefaultBlock; 884 } 885 } 886 887 ConditionScope.ForceCleanup(); 888 889 // Emit continuation. 890 EmitBlock(SwitchExit.getBlock(), true); 891 892 SwitchInsn = SavedSwitchInsn; 893 CaseRangeBlock = SavedCRBlock; 894 } 895 896 static std::string 897 SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 898 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) { 899 std::string Result; 900 901 while (*Constraint) { 902 switch (*Constraint) { 903 default: 904 Result += Target.convertConstraint(*Constraint); 905 break; 906 // Ignore these 907 case '*': 908 case '?': 909 case '!': 910 case '=': // Will see this and the following in mult-alt constraints. 911 case '+': 912 break; 913 case ',': 914 Result += "|"; 915 break; 916 case 'g': 917 Result += "imr"; 918 break; 919 case '[': { 920 assert(OutCons && 921 "Must pass output names to constraints with a symbolic name"); 922 unsigned Index; 923 bool result = Target.resolveSymbolicName(Constraint, 924 &(*OutCons)[0], 925 OutCons->size(), Index); 926 assert(result && "Could not resolve symbolic name"); (void)result; 927 Result += llvm::utostr(Index); 928 break; 929 } 930 } 931 932 Constraint++; 933 } 934 935 return Result; 936 } 937 938 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared 939 /// as using a particular register add that as a constraint that will be used 940 /// in this asm stmt. 941 static std::string 942 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, 943 const TargetInfo &Target, CodeGenModule &CGM, 944 const AsmStmt &Stmt) { 945 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr); 946 if (!AsmDeclRef) 947 return Constraint; 948 const ValueDecl &Value = *AsmDeclRef->getDecl(); 949 const VarDecl *Variable = dyn_cast<VarDecl>(&Value); 950 if (!Variable) 951 return Constraint; 952 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>(); 953 if (!Attr) 954 return Constraint; 955 llvm::StringRef Register = Attr->getLabel(); 956 assert(Target.isValidGCCRegisterName(Register)); 957 // FIXME: We should check which registers are compatible with "r" or "x". 958 if (Constraint != "r" && Constraint != "x") { 959 CGM.ErrorUnsupported(&Stmt, "__asm__"); 960 return Constraint; 961 } 962 return "{" + Register.str() + "}"; 963 } 964 965 llvm::Value* 966 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S, 967 const TargetInfo::ConstraintInfo &Info, 968 LValue InputValue, QualType InputType, 969 std::string &ConstraintStr) { 970 llvm::Value *Arg; 971 if (Info.allowsRegister() || !Info.allowsMemory()) { 972 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) { 973 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal(); 974 } else { 975 const llvm::Type *Ty = ConvertType(InputType); 976 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty); 977 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 978 Ty = llvm::IntegerType::get(VMContext, Size); 979 Ty = llvm::PointerType::getUnqual(Ty); 980 981 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(), 982 Ty)); 983 } else { 984 Arg = InputValue.getAddress(); 985 ConstraintStr += '*'; 986 } 987 } 988 } else { 989 Arg = InputValue.getAddress(); 990 ConstraintStr += '*'; 991 } 992 993 return Arg; 994 } 995 996 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, 997 const TargetInfo::ConstraintInfo &Info, 998 const Expr *InputExpr, 999 std::string &ConstraintStr) { 1000 if (Info.allowsRegister() || !Info.allowsMemory()) 1001 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) 1002 return EmitScalarExpr(InputExpr); 1003 1004 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 1005 LValue Dest = EmitLValue(InputExpr); 1006 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr); 1007 } 1008 1009 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline 1010 /// asm call instruction. The !srcloc MDNode contains a list of constant 1011 /// integers which are the source locations of the start of each line in the 1012 /// asm. 1013 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, 1014 CodeGenFunction &CGF) { 1015 llvm::SmallVector<llvm::Value *, 8> Locs; 1016 // Add the location of the first line to the MDNode. 1017 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1018 Str->getLocStart().getRawEncoding())); 1019 llvm::StringRef StrVal = Str->getString(); 1020 if (!StrVal.empty()) { 1021 const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); 1022 const LangOptions &LangOpts = CGF.CGM.getLangOptions(); 1023 1024 // Add the location of the start of each subsequent line of the asm to the 1025 // MDNode. 1026 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) { 1027 if (StrVal[i] != '\n') continue; 1028 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts, 1029 CGF.Target); 1030 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1031 LineLoc.getRawEncoding())); 1032 } 1033 } 1034 1035 return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size()); 1036 } 1037 1038 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 1039 // Analyze the asm string to decompose it into its pieces. We know that Sema 1040 // has already done this, so it is guaranteed to be successful. 1041 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces; 1042 unsigned DiagOffs; 1043 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs); 1044 1045 // Assemble the pieces into the final asm string. 1046 std::string AsmString; 1047 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { 1048 if (Pieces[i].isString()) 1049 AsmString += Pieces[i].getString(); 1050 else if (Pieces[i].getModifier() == '\0') 1051 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo()); 1052 else 1053 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' + 1054 Pieces[i].getModifier() + '}'; 1055 } 1056 1057 // Get all the output and input constraints together. 1058 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1059 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1060 1061 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1062 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), 1063 S.getOutputName(i)); 1064 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid; 1065 assert(IsValid && "Failed to parse output constraint"); 1066 OutputConstraintInfos.push_back(Info); 1067 } 1068 1069 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1070 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), 1071 S.getInputName(i)); 1072 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(), 1073 S.getNumOutputs(), Info); 1074 assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 1075 InputConstraintInfos.push_back(Info); 1076 } 1077 1078 std::string Constraints; 1079 1080 std::vector<LValue> ResultRegDests; 1081 std::vector<QualType> ResultRegQualTys; 1082 std::vector<const llvm::Type *> ResultRegTypes; 1083 std::vector<const llvm::Type *> ResultTruncRegTypes; 1084 std::vector<const llvm::Type*> ArgTypes; 1085 std::vector<llvm::Value*> Args; 1086 1087 // Keep track of inout constraints. 1088 std::string InOutConstraints; 1089 std::vector<llvm::Value*> InOutArgs; 1090 std::vector<const llvm::Type*> InOutArgTypes; 1091 1092 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1093 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 1094 1095 // Simplify the output constraint. 1096 std::string OutputConstraint(S.getOutputConstraint(i)); 1097 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target); 1098 1099 const Expr *OutExpr = S.getOutputExpr(i); 1100 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 1101 1102 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target, 1103 CGM, S); 1104 1105 LValue Dest = EmitLValue(OutExpr); 1106 if (!Constraints.empty()) 1107 Constraints += ','; 1108 1109 // If this is a register output, then make the inline asm return it 1110 // by-value. If this is a memory result, return the value by-reference. 1111 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) { 1112 Constraints += "=" + OutputConstraint; 1113 ResultRegQualTys.push_back(OutExpr->getType()); 1114 ResultRegDests.push_back(Dest); 1115 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 1116 ResultTruncRegTypes.push_back(ResultRegTypes.back()); 1117 1118 // If this output is tied to an input, and if the input is larger, then 1119 // we need to set the actual result type of the inline asm node to be the 1120 // same as the input type. 1121 if (Info.hasMatchingInput()) { 1122 unsigned InputNo; 1123 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 1124 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 1125 if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 1126 break; 1127 } 1128 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 1129 1130 QualType InputTy = S.getInputExpr(InputNo)->getType(); 1131 QualType OutputType = OutExpr->getType(); 1132 1133 uint64_t InputSize = getContext().getTypeSize(InputTy); 1134 if (getContext().getTypeSize(OutputType) < InputSize) { 1135 // Form the asm to return the value as a larger integer or fp type. 1136 ResultRegTypes.back() = ConvertType(InputTy); 1137 } 1138 } 1139 if (const llvm::Type* AdjTy = 1140 Target.adjustInlineAsmType(OutputConstraint, ResultRegTypes.back(), 1141 VMContext)) 1142 ResultRegTypes.back() = AdjTy; 1143 } else { 1144 ArgTypes.push_back(Dest.getAddress()->getType()); 1145 Args.push_back(Dest.getAddress()); 1146 Constraints += "=*"; 1147 Constraints += OutputConstraint; 1148 } 1149 1150 if (Info.isReadWrite()) { 1151 InOutConstraints += ','; 1152 1153 const Expr *InputExpr = S.getOutputExpr(i); 1154 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), 1155 InOutConstraints); 1156 1157 if (Info.allowsRegister()) 1158 InOutConstraints += llvm::utostr(i); 1159 else 1160 InOutConstraints += OutputConstraint; 1161 1162 InOutArgTypes.push_back(Arg->getType()); 1163 InOutArgs.push_back(Arg); 1164 } 1165 } 1166 1167 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); 1168 1169 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1170 const Expr *InputExpr = S.getInputExpr(i); 1171 1172 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1173 1174 if (!Constraints.empty()) 1175 Constraints += ','; 1176 1177 // Simplify the input constraint. 1178 std::string InputConstraint(S.getInputConstraint(i)); 1179 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target, 1180 &OutputConstraintInfos); 1181 1182 InputConstraint = 1183 AddVariableConstraints(InputConstraint, 1184 *InputExpr->IgnoreParenNoopCasts(getContext()), 1185 Target, CGM, S); 1186 1187 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints); 1188 1189 // If this input argument is tied to a larger output result, extend the 1190 // input to be the same size as the output. The LLVM backend wants to see 1191 // the input and output of a matching constraint be the same size. Note 1192 // that GCC does not define what the top bits are here. We use zext because 1193 // that is usually cheaper, but LLVM IR should really get an anyext someday. 1194 if (Info.hasTiedOperand()) { 1195 unsigned Output = Info.getTiedOperand(); 1196 QualType OutputType = S.getOutputExpr(Output)->getType(); 1197 QualType InputTy = InputExpr->getType(); 1198 1199 if (getContext().getTypeSize(OutputType) > 1200 getContext().getTypeSize(InputTy)) { 1201 // Use ptrtoint as appropriate so that we can do our extension. 1202 if (isa<llvm::PointerType>(Arg->getType())) 1203 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy); 1204 const llvm::Type *OutputTy = ConvertType(OutputType); 1205 if (isa<llvm::IntegerType>(OutputTy)) 1206 Arg = Builder.CreateZExt(Arg, OutputTy); 1207 else 1208 Arg = Builder.CreateFPExt(Arg, OutputTy); 1209 } 1210 } 1211 if (const llvm::Type* AdjTy = 1212 Target.adjustInlineAsmType(InputConstraint, Arg->getType(), 1213 VMContext)) 1214 Arg = Builder.CreateBitCast(Arg, AdjTy); 1215 1216 ArgTypes.push_back(Arg->getType()); 1217 Args.push_back(Arg); 1218 Constraints += InputConstraint; 1219 } 1220 1221 // Append the "input" part of inout constraints last. 1222 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 1223 ArgTypes.push_back(InOutArgTypes[i]); 1224 Args.push_back(InOutArgs[i]); 1225 } 1226 Constraints += InOutConstraints; 1227 1228 // Clobbers 1229 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 1230 llvm::StringRef Clobber = S.getClobber(i)->getString(); 1231 1232 Clobber = Target.getNormalizedGCCRegisterName(Clobber); 1233 1234 if (i != 0 || NumConstraints != 0) 1235 Constraints += ','; 1236 1237 Constraints += "~{"; 1238 Constraints += Clobber; 1239 Constraints += '}'; 1240 } 1241 1242 // Add machine specific clobbers 1243 std::string MachineClobbers = Target.getClobbers(); 1244 if (!MachineClobbers.empty()) { 1245 if (!Constraints.empty()) 1246 Constraints += ','; 1247 Constraints += MachineClobbers; 1248 } 1249 1250 const llvm::Type *ResultType; 1251 if (ResultRegTypes.empty()) 1252 ResultType = llvm::Type::getVoidTy(VMContext); 1253 else if (ResultRegTypes.size() == 1) 1254 ResultType = ResultRegTypes[0]; 1255 else 1256 ResultType = llvm::StructType::get(VMContext, ResultRegTypes); 1257 1258 const llvm::FunctionType *FTy = 1259 llvm::FunctionType::get(ResultType, ArgTypes, false); 1260 1261 llvm::InlineAsm *IA = 1262 llvm::InlineAsm::get(FTy, AsmString, Constraints, 1263 S.isVolatile() || S.getNumOutputs() == 0); 1264 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end()); 1265 Result->addAttribute(~0, llvm::Attribute::NoUnwind); 1266 1267 // Slap the source location of the inline asm into a !srcloc metadata on the 1268 // call. 1269 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this)); 1270 1271 // Extract all of the register value results from the asm. 1272 std::vector<llvm::Value*> RegResults; 1273 if (ResultRegTypes.size() == 1) { 1274 RegResults.push_back(Result); 1275 } else { 1276 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 1277 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult"); 1278 RegResults.push_back(Tmp); 1279 } 1280 } 1281 1282 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 1283 llvm::Value *Tmp = RegResults[i]; 1284 1285 // If the result type of the LLVM IR asm doesn't match the result type of 1286 // the expression, do the conversion. 1287 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 1288 const llvm::Type *TruncTy = ResultTruncRegTypes[i]; 1289 1290 // Truncate the integer result to the right size, note that TruncTy can be 1291 // a pointer. 1292 if (TruncTy->isFloatingPointTy()) 1293 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 1294 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 1295 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy); 1296 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, 1297 (unsigned)ResSize)); 1298 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 1299 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 1300 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType()); 1301 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext, 1302 (unsigned)TmpSize)); 1303 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1304 } else if (TruncTy->isIntegerTy()) { 1305 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1306 } else if (TruncTy->isVectorTy()) { 1307 Tmp = Builder.CreateBitCast(Tmp, TruncTy); 1308 } 1309 } 1310 1311 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i], 1312 ResultRegQualTys[i]); 1313 } 1314 } 1315